diff --git a/Cargo.lock b/Cargo.lock index 9a1dc4b..1168db5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -739,6 +739,7 @@ dependencies = [ "uuid", "walkdir", "werkbank-exec", + "yaml-rust2", "zip", ] diff --git a/compliance-agent/Cargo.toml b/compliance-agent/Cargo.toml index c0f6705..96a06bc 100644 --- a/compliance-agent/Cargo.toml +++ b/compliance-agent/Cargo.toml @@ -55,6 +55,8 @@ walkdir = "2" toml = "0.8" # Read-only XML tree parsing for PLCopen project files (POU extraction). roxmltree = "0.20" +# kas project files (Yocto layer pins); already in the tree through firmwerk-core. +yaml-rust2 = { version = "0.13", default-features = false } base64 = "0.22" urlencoding = "2" futures-util = "0.3" diff --git a/compliance-agent/src/evidence/compliance.rs b/compliance-agent/src/evidence/compliance.rs index 27b66ae..7de974c 100644 --- a/compliance-agent/src/evidence/compliance.rs +++ b/compliance-agent/src/evidence/compliance.rs @@ -72,7 +72,13 @@ pub enum SbomCoverage { } /// The tools that check a target's components rather than its code. -const COMPONENT_TOOLS: [&str; 4] = ["syft", "osv", "dotnet-lifecycle", "build-lifecycle"]; +const COMPONENT_TOOLS: [&str; 5] = [ + "syft", + "osv", + "dotnet-lifecycle", + "build-lifecycle", + "yocto-release", +]; /// The tool a skipped stage of a scan run stands for, when that stage is one /// a control's binding relies on. diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index 3a21512..0136265 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -51,3 +51,4 @@ pub mod variants; pub mod vendor; pub mod vex_lifecycle; pub mod yocto_inventory; +pub mod yocto_pins; diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index a63ac5b..94aa5ec 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -390,6 +390,16 @@ impl PipelineOrchestrator { run_findings.completed(scanner); } all_findings.extend(findings); + // Yocto layers: what they pin, and whether their release is supported. + if repo.yocto_layers { + if let Some(found) = self + .check_yocto_release(&repo_path, repo, scan_run_id, &vendor) + .await + { + run_findings.completed(crate::pipeline::yocto_pins::release::SCANNER); + all_findings.extend(found); + } + } run_findings.label(&mut all_findings); group_repetitive(&mut all_findings, &grouping); run_findings.save_new(&self.db, &mut all_findings).await?; @@ -2347,6 +2357,57 @@ impl PipelineOrchestrator { .await; } + /// Read the layer pins of the Yocto layer tree at `tree` and store them on + /// the target. The support-status finding of its release, `None` when the + /// release is unknown (recorded on the run as a skipped stage). + async fn check_yocto_release( + &self, + tree: &std::path::Path, + repo: &RepoView, + scan_run_id: &str, + vendor: &[String], + ) -> Option> { + use crate::pipeline::yocto_pins::{self, release}; + let (root, excluded) = (tree.to_path_buf(), vendor.to_vec()); + let pins = tokio::task::spawn_blocking(move || yocto_pins::read(&root, &excluded)) + .await + .ok()?; + if let (Some(oid), Ok(stored)) = (repo.id, mongodb::bson::to_bson(&pins)) { + if let Err(e) = self + .db + .onboarded_targets() + .update_one( + doc! { "_id": oid }, + doc! { "$set": { "layer_pins": stored } }, + ) + .await + { + tracing::warn!(target_id = %oid, "layer pins not stored: {e}"); + } + } + let Some(found) = &pins.release else { + self.skip_stage( + scan_run_id, + SkippedStage::new( + yocto_pins::STAGE, + SkipCode::ReleaseUnknown, + "the Yocto release could not be read from the layer pins (kas, repo \ + manifest, submodules) or LAYERSERIES_COMPAT, so its support period was \ + not checked", + ), + ) + .await; + return None; + }; + let repo_id = repo.id.map(|id| id.to_hex()).unwrap_or_default(); + let today = chrono::Utc::now().date_naive(); + Some( + release::finding(&repo_id, found, today) + .into_iter() + .collect(), + ) + } + /// 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 { diff --git a/compliance-agent/src/pipeline/recipe_lint/mod.rs b/compliance-agent/src/pipeline/recipe_lint/mod.rs index 079e4c5..53990b3 100644 --- a/compliance-agent/src/pipeline/recipe_lint/mod.rs +++ b/compliance-agent/src/pipeline/recipe_lint/mod.rs @@ -234,6 +234,10 @@ pub(crate) struct Layer { pub release: Option<&'static str>, /// An upstream layer, which is not linted. pub upstream: bool, + /// The collections its `layer.conf` declares (`BBFILE_COLLECTIONS`). + pub collections: Vec, + /// Every release its `LAYERSERIES_COMPAT_*` names, as written. + pub compat: Vec, /// Its files relative to the tree; a nested layer's files are its own. pub files: Vec, } @@ -311,7 +315,7 @@ fn is_read(inner: &str) -> bool { /// The layers of the tree under `root`, outside the `excluded` directories: /// each directory holding a `conf/layer.conf`. A tree without one (loose /// recipes) is read as a single layer. -fn layers(root: &Path, excluded: &[String]) -> Vec { +pub(crate) fn layers(root: &Path, excluded: &[String]) -> Vec { let files: Vec = walkdir::WalkDir::new(root) .min_depth(1) .into_iter() @@ -365,6 +369,8 @@ fn layers(root: &Path, excluded: &[String]) -> Vec { release: oldest_release(&compat), files: Vec::new(), dir, + collections, + compat, }; let mut files = by_dir.remove(&layer.dir).unwrap_or_default(); files.retain(|f| is_read(layer.inner(f))); @@ -376,7 +382,7 @@ fn layers(root: &Path, excluded: &[String]) -> Vec { } /// `path` relative to `root`, `/`-separated. -fn rel_path(root: &Path, path: &Path) -> String { +pub(crate) fn rel_path(root: &Path, path: &Path) -> String { path.strip_prefix(root) .unwrap_or(path) .to_string_lossy() diff --git a/compliance-agent/src/pipeline/yocto_pins/gitmodules.rs b/compliance-agent/src/pipeline/yocto_pins/gitmodules.rs new file mode 100644 index 0000000..69282cd --- /dev/null +++ b/compliance-agent/src/pipeline/yocto_pins/gitmodules.rs @@ -0,0 +1,177 @@ +//! Git submodules as layer pins: `.gitmodules` names each submodule's path, +//! URL and branch, and the tree's HEAD commit records the commit each +//! submodule is pinned to (its gitlink). An uploaded archive has no `.git`, +//! so its submodules have no commit. + +use std::path::Path; + +use compliance_core::models::{LayerPin, PinSource}; +use git2::Repository; + +use super::{clean_ref, read_small}; + +/// The file submodules are declared in. +pub(crate) const GITMODULES: &str = ".gitmodules"; + +/// The git file mode of a gitlink: a commit of another repository. +const GITLINK_MODE: i32 = 0o160000; + +/// One `[submodule ""]` section. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(crate) struct Submodule { + pub name: String, + pub path: Option, + pub url: Option, + pub branch: Option, +} + +/// The submodules a `.gitmodules` text declares, in order. +pub(crate) fn parse(text: &str) -> Vec { + let mut out: Vec = Vec::new(); + // Only keys inside a `[submodule "…"]` section count. + let mut in_submodule = false; + for line in text.lines().map(str::trim) { + if line.is_empty() || line.starts_with('#') || line.starts_with(';') { + continue; + } + if let Some(section) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { + let name = section + .trim() + .strip_prefix("submodule") + .map(|rest| rest.trim().trim_matches('"').to_string()); + in_submodule = name.is_some(); + if let Some(name) = name { + out.push(Submodule { + name, + ..Submodule::default() + }); + } + continue; + } + let (Some(current), true) = (out.last_mut(), in_submodule) else { + continue; + }; + let Some((key, value)) = line.split_once('=') else { + continue; + }; + let value = value.trim().trim_matches('"').to_string(); + match key.trim().to_ascii_lowercase().as_str() { + "path" => current.path = Some(value), + "url" => current.url = Some(value), + "branch" => current.branch = Some(value), + _ => {} + } + } + out +} + +/// The commit the HEAD tree of the repository at `root` records at `path`, +/// when `root` is a git checkout and `path` a gitlink there. +fn gitlink(repo: &Repository, path: &str) -> Option { + let tree = repo.head().ok()?.peel_to_tree().ok()?; + let entry = tree.get_path(Path::new(path)).ok()?; + (entry.filemode() == GITLINK_MODE).then(|| entry.id().to_string()) +} + +/// The submodules of the tree under `root` as pins, and their paths (whose +/// own kas files and manifests are another repository's, not the tree's). +pub(crate) fn pins(root: &Path) -> (Vec, Vec) { + let Some(text) = read_small(&root.join(GITMODULES)) else { + return (Vec::new(), Vec::new()); + }; + // `open`, not `discover`: only a checkout rooted at the tree counts. + let repo = Repository::open(root).ok(); + let submodules = parse(&text); + let paths = submodules.iter().filter_map(|s| s.path.clone()).collect(); + let pins = submodules + .into_iter() + .map(|s| LayerPin { + commit: repo + .as_ref() + .zip(s.path.as_deref()) + .and_then(|(repo, path)| gitlink(repo, path)), + branch: s.branch.as_deref().and_then(clean_ref), + url: s.url, + name: s.name, + source: PinSource::GitSubmodule, + file: GITMODULES.to_string(), + }) + .collect(); + (pins, paths) +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + use crate::pipeline::recipe_lint::tests::tree; + + const GITMODULES_TEXT: &str = "# layers\n[submodule \"poky\"]\n\tpath = layers/poky\n\t\ + url = https://git.yoctoproject.org/poky\n\tbranch = kirkstone\n\ + [core]\n\tpath = not-a-submodule\n\ + [submodule \"meta-oe\"]\n\tpath = layers/meta-openembedded\n\t\ + url = \"https://github.com/openembedded/meta-openembedded.git\"\n"; + + #[test] + fn gitmodules_sections_are_read() { + let found = parse(GITMODULES_TEXT); + assert_eq!(found.len(), 2); + assert_eq!(found[0].name, "poky"); + assert_eq!(found[0].path.as_deref(), Some("layers/poky")); + assert_eq!(found[0].branch.as_deref(), Some("kirkstone")); + assert_eq!(found[1].name, "meta-oe"); + assert_eq!( + found[1].url.as_deref(), + Some("https://github.com/openembedded/meta-openembedded.git") + ); + assert_eq!(found[1].branch, None); + } + + #[test] + fn an_archive_has_submodules_without_commits() { + let t = tree(&[(GITMODULES, GITMODULES_TEXT)]); + let (pins, paths) = pins(&t.0); + assert_eq!(paths, ["layers/poky", "layers/meta-openembedded"]); + assert_eq!(pins[0].source, PinSource::GitSubmodule); + assert_eq!(pins[0].file, ".gitmodules"); + assert_eq!(pins[0].commit, None); + } + + #[test] + fn a_checkout_pins_each_submodule_to_its_gitlink_commit() { + let t = tree(&[(GITMODULES, GITMODULES_TEXT), ("README", "x")]); + let repo = Repository::init(&t.0).expect("init"); + let sig = git2::Signature::now("t", "t@example.com").expect("sig"); + // A commit of the layer repository the gitlink points at. + let pinned = git2::Oid::from_str("0123456789abcdef0123456789abcdef01234567").expect("oid"); + let mut index = repo.index().expect("index"); + index.add_path(Path::new(GITMODULES)).expect("add"); + index.add_path(Path::new("README")).expect("add"); + index + .add(&git2::IndexEntry { + ctime: git2::IndexTime::new(0, 0), + mtime: git2::IndexTime::new(0, 0), + dev: 0, + ino: 0, + mode: 0o160000, + uid: 0, + gid: 0, + file_size: 0, + id: pinned, + flags: 0, + flags_extended: 0, + path: b"layers/poky".to_vec(), + }) + .expect("gitlink"); + let tree_id = index.write_tree().expect("tree"); + let commit_tree = repo.find_tree(tree_id).expect("tree"); + repo.commit(Some("HEAD"), &sig, &sig, "layers", &commit_tree, &[]) + .expect("commit"); + + let (pins, _) = pins(&t.0); + assert_eq!(pins[0].commit.as_deref(), Some(pinned.to_string().as_str())); + assert_eq!(pins[0].branch.as_deref(), Some("kirkstone")); + // meta-oe has no gitlink in HEAD. + assert_eq!(pins[1].commit, None); + } +} diff --git a/compliance-agent/src/pipeline/yocto_pins/kas.rs b/compliance-agent/src/pipeline/yocto_pins/kas.rs new file mode 100644 index 0000000..1a1ea50 --- /dev/null +++ b/compliance-agent/src/pipeline/yocto_pins/kas.rs @@ -0,0 +1,493 @@ +//! kas project files as layer pins. +//! +//! A kas file (`kas*.yml`, `kas/*.yml`) lists the repositories a build +//! fetches under `repos:`, each with its `url`, `branch`, `tag`, `commit` or +//! the older `refspec`. `header.includes` merges other kas files in before the +//! file's own settings; only local includes are read: an include from another +//! repository (`repo:` / `file:`) or a URL is named, never fetched. A lock +//! file beside a kas file (`kas.lock.yml`) pins commits under +//! `overrides.repos`. + +use std::collections::{BTreeSet, HashMap}; +use std::path::Path; + +use compliance_core::models::{LayerPin, PinSource}; +use yaml_rust2::parser::{Event, Parser}; +use yaml_rust2::{Yaml, YamlLoader}; + +use super::{clean_ref, is_commit, local_include, read_small}; + +/// Most YAML nodes a kas file may expand to, aliases included: a file of +/// nested aliases ("billion laughs") is refused instead of expanded. +const MAX_NODES: usize = 100_000; + +/// Whether `rel` (relative to the tree) names a kas project file: `kas*.yml` +/// anywhere, or any YAML file in a `kas/` directory. Lock files are read with +/// the file they lock, not on their own. +pub(crate) fn is_kas_file(rel: &str) -> bool { + let name = rel.rsplit('/').next().unwrap_or(rel); + let yaml = name.ends_with(".yml") || name.ends_with(".yaml"); + let in_kas_dir = rel.split('/').rev().nth(1) == Some("kas"); + yaml && !is_lock_file(name) && (name.starts_with("kas") || in_kas_dir) +} + +fn is_lock_file(name: &str) -> bool { + name.ends_with(".lock.yml") || name.ends_with(".lock.yaml") +} + +/// The lock file kas reads beside `rel` (`x.yml` -> `x.lock.yml`). +fn lock_file(rel: &str) -> Option { + let (stem, ext) = rel.rsplit_once('.')?; + Some(format!("{stem}.lock.{ext}")) +} + +/// How many nodes the YAML `text` expands to with its aliases resolved; +/// `None` past [`MAX_NODES`] or when it does not parse. +fn expanded_nodes(text: &str) -> Option { + let mut parser = Parser::new_from_str(text); + // Open collections: (anchor id, nodes so far). + let mut open: Vec<(usize, usize)> = Vec::new(); + let mut anchors: HashMap = HashMap::new(); + let mut total = 0usize; + loop { + let (event, _) = parser.next_token().ok()?; + let done = match event { + Event::StreamEnd => break, + Event::SequenceStart(anchor, _) | Event::MappingStart(anchor, _) => { + open.push((anchor, 1)); + None + } + Event::SequenceEnd | Event::MappingEnd => { + let (anchor, nodes) = open.pop()?; + if anchor > 0 { + anchors.insert(anchor, nodes); + } + Some(nodes) + } + Event::Scalar(_, _, anchor, _) => { + if anchor > 0 { + anchors.insert(anchor, 1); + } + Some(1) + } + Event::Alias(anchor) => Some(anchors.get(&anchor).copied().unwrap_or(1)), + _ => None, + }; + if let Some(nodes) = done { + match open.last_mut() { + Some((_, parent)) => *parent = parent.saturating_add(nodes), + None => total = total.saturating_add(nodes), + } + let pending: usize = open.iter().map(|(_, n)| *n).sum(); + if total.saturating_add(pending) > MAX_NODES { + return None; + } + } + } + Some(total) +} + +/// The kas file `rel` under `root` as YAML: `None` when it is missing, too +/// large, not YAML, expands too far, or has no `header` (not a kas file). +fn load(root: &Path, rel: &str) -> Option { + let text = read_small(&root.join(rel))?; + expanded_nodes(&text)?; + let doc = YamlLoader::load_from_str(&text).ok()?.into_iter().next()?; + (!doc["header"].is_badvalue()).then_some(doc) +} + +/// A repository entry as the merged kas files describe it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +struct Repo { + url: Option, + branch: Option, + tag: Option, + refspec: Option, + commit: Option, + /// The last file that set any of it. + file: String, +} + +/// The repositories of one kas configuration, in the order they first +/// appear, and the default branch. +#[derive(Debug, Default)] +struct Merged { + repos: Vec<(String, Repo)>, + default_branch: Option, +} + +impl Merged { + fn repo(&mut self, name: &str) -> &mut Repo { + let index = match self.repos.iter().position(|(n, _)| n == name) { + Some(index) => index, + None => { + self.repos.push((name.to_string(), Repo::default())); + self.repos.len() - 1 + } + }; + &mut self.repos[index].1 + } + + /// Lay `doc` (the kas file `file`) over what is merged so far: its + /// settings override the included files'. + fn apply(&mut self, doc: &Yaml, file: &str) { + let text = |y: &Yaml| match y { + Yaml::String(s) => Some(s.clone()), + Yaml::Integer(i) => Some(i.to_string()), + Yaml::Real(r) => Some(r.clone()), + _ => None, + }; + let defaults = &doc["defaults"]["repos"]; + if let Some(branch) = text(&defaults["branch"]).or_else(|| text(&defaults["refspec"])) { + self.default_branch = Some(branch); + } + if let Some(repos) = doc["repos"].as_hash() { + for (key, value) in repos { + let Some(name) = text(key) else { continue }; + let repo = self.repo(&name); + repo.file = file.to_string(); + for (field, slot) in [ + ("url", &mut repo.url), + ("branch", &mut repo.branch), + ("tag", &mut repo.tag), + ("refspec", &mut repo.refspec), + ("commit", &mut repo.commit), + ] { + if let Some(v) = text(&value[field]) { + *slot = Some(v); + } + } + } + } + if let Some(overrides) = doc["overrides"]["repos"].as_hash() { + for (key, value) in overrides { + let (Some(name), Some(commit)) = (text(key), text(&value["commit"])) else { + continue; + }; + let repo = self.repo(&name); + repo.commit = Some(commit); + repo.file = file.to_string(); + } + } + } + + /// The pins of the repositories fetched from elsewhere (with a `url`). + fn pins(self) -> Vec { + let default_branch = self.default_branch; + self.repos + .into_iter() + .filter_map(|(name, repo)| { + let url = repo.url?; + // A refspec may be a commit (old kas files) or a branch. + let refspec_commit = repo.refspec.clone().filter(|r| is_commit(r)); + let named = repo + .branch + .or(repo.tag) + .or(repo.refspec.filter(|r| !is_commit(r))) + .or(default_branch.clone()); + Some(LayerPin { + name, + source: PinSource::Kas, + file: repo.file, + url: Some(url), + branch: named.as_deref().and_then(clean_ref), + commit: repo.commit.or(refspec_commit), + }) + }) + .collect() + } +} + +/// What the kas files of a tree pin. +#[derive(Debug, Default, PartialEq, Eq)] +pub(crate) struct KasPins { + pub pins: Vec, + /// Includes that were not read (remote ones, missing ones), as written. + pub unread_includes: BTreeSet, +} + +/// Reads kas files and their includes, each file once. +struct Reader<'a> { + root: &'a Path, + docs: HashMap>, + unread: BTreeSet, + /// Every file merged into a configuration so far. + visited: BTreeSet, +} + +impl Reader<'_> { + fn doc(&mut self, rel: &str) -> Option { + let root = self.root; + self.docs + .entry(rel.to_string()) + .or_insert_with(|| load(root, rel)) + .clone() + } + + /// The local files `doc` (the kas file `rel`) includes, in order; remote + /// and unresolvable ones are recorded as unread. + fn includes(&mut self, rel: &str, doc: &Yaml) -> Vec { + let Some(list) = doc["header"]["includes"].as_vec() else { + return Vec::new(); + }; + let mut out = Vec::new(); + for include in list { + match include { + Yaml::String(path) if path.contains("://") => { + self.unread.insert(path.clone()); + } + Yaml::String(path) => match local_include(self.root, rel, path) { + Some(found) => out.push(found), + None => { + self.unread.insert(path.clone()); + } + }, + // `repo:` + `file:`: a file in another repository. + Yaml::Hash(_) => { + let repo = include["repo"].as_str().unwrap_or("?"); + let file = include["file"].as_str().unwrap_or("?"); + self.unread.insert(format!("{repo}:{file}")); + } + _ => {} + } + } + out + } + + /// Merge `rel` with everything it includes into `merged`; `stack` holds + /// the files being read, so an include cycle ends. + fn merge(&mut self, rel: &str, merged: &mut Merged, stack: &mut Vec) { + if stack.iter().any(|s| s == rel) { + return; + } + let Some(doc) = self.doc(rel) else { + return; + }; + stack.push(rel.to_string()); + self.visited.insert(rel.to_string()); + for include in self.includes(rel, &doc) { + if self.doc(&include).is_some() { + self.merge(&include, merged, stack); + } else if !stack.contains(&include) { + self.unread.insert(include); + } + } + merged.apply(&doc, rel); + stack.pop(); + } +} + +/// The pins of the kas files `files` (relative to `root`). Each file no other +/// one includes is a configuration of its own; a pin several of them share +/// is listed once. +pub(crate) fn read(root: &Path, files: &[String]) -> KasPins { + let mut reader = Reader { + root, + docs: HashMap::new(), + unread: BTreeSet::new(), + visited: BTreeSet::new(), + }; + let mut included: BTreeSet = BTreeSet::new(); + for file in files { + if let Some(doc) = reader.doc(file) { + included.extend(reader.includes(file, &doc)); + } + } + let mut pins: Vec = Vec::new(); + // The files no other one includes first; then any left unread, which only + // an include cycle leaves. + let order = files + .iter() + .filter(|f| !included.contains(*f)) + .chain(files.iter().filter(|f| included.contains(*f))); + for file in order { + if reader.visited.contains(file) || reader.doc(file).is_none() { + continue; + } + let mut merged = Merged::default(); + reader.merge(file, &mut merged, &mut Vec::new()); + if let Some(lock) = lock_file(file).filter(|l| root.join(l).is_file()) { + if let Some(doc) = load(root, &lock) { + merged.apply(&doc, &lock); + } + } + for pin in merged.pins() { + if !pins.contains(&pin) { + pins.push(pin); + } + } + } + KasPins { + pins, + unread_includes: reader.unread, + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + use crate::pipeline::recipe_lint::tests::tree; + + const SHA: &str = "4a2d3b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a"; + + #[test] + fn kas_files_are_recognised_by_name_and_directory() { + assert!(is_kas_file("kas.yml")); + assert!(is_kas_file("kas-pump.yaml")); + assert!(is_kas_file("ci/kas/machine.yml")); + assert!(!is_kas_file("kas.lock.yml")); + assert!(!is_kas_file("docker-compose.yml")); + assert!(!is_kas_file("kas/readme.md")); + } + + #[test] + fn includes_are_merged_and_the_including_file_wins() { + let t = tree(&[ + ( + "kas.yml", + &format!( + "header:\n version: 14\n includes:\n - kas/common.yml\n \ + - repo: meta-vendor\n file: kas/vendor.yml\n \ + - https://example.com/remote.yml\n - kas/missing.yml\n\ + repos:\n poky:\n commit: {SHA}\n meta-pump:\n" + ), + ), + ( + "kas/common.yml", + "header:\n version: 14\ndefaults:\n repos:\n branch: kirkstone\n\ + repos:\n poky:\n url: https://git.yoctoproject.org/poky\n \ + branch: dunfell\n meta-openembedded:\n \ + url: https://github.com/openembedded/meta-openembedded\n", + ), + ]); + let files = vec!["kas.yml".to_string(), "kas/common.yml".to_string()]; + let read = read(&t.0, &files); + assert_eq!(read.pins.len(), 2, "{:?}", read.pins); + let poky = &read.pins[0]; + assert_eq!(poky.name, "poky"); + assert_eq!( + poky.url.as_deref(), + Some("https://git.yoctoproject.org/poky") + ); + assert_eq!(poky.branch.as_deref(), Some("dunfell")); + assert_eq!(poky.commit.as_deref(), Some(SHA)); + assert_eq!(poky.file, "kas.yml"); + // The default branch fills in, and the tree's own layer (no url) is + // not a pin. + assert_eq!(read.pins[1].branch.as_deref(), Some("kirkstone")); + assert_eq!(read.pins[1].file, "kas/common.yml"); + assert_eq!( + read.unread_includes.iter().collect::>(), + [ + "https://example.com/remote.yml", + "kas/missing.yml", + "meta-vendor:kas/vendor.yml" + ] + ); + } + + #[test] + fn an_include_cycle_ends() { + let t = tree(&[ + ( + "kas/a.yml", + "header:\n version: 14\n includes:\n - kas/b.yml\n\ + repos:\n poky:\n url: https://git.yoctoproject.org/poky\n", + ), + ( + "kas/b.yml", + "header:\n version: 14\n includes:\n - kas/a.yml\n\ + repos:\n poky:\n branch: scarthgap\n", + ), + ( + "kas-top.yml", + "header:\n version: 14\n includes:\n - kas/a.yml\n", + ), + ]); + let files: Vec = ["kas-top.yml", "kas/a.yml", "kas/b.yml"] + .map(String::from) + .to_vec(); + let read = read(&t.0, &files); + assert_eq!(read.pins.len(), 1); + assert_eq!(read.pins[0].branch.as_deref(), Some("scarthgap")); + assert!(read.unread_includes.is_empty()); + } + + #[test] + fn files_that_only_include_each_other_are_still_read_once() { + let t = tree(&[ + ( + "kas/a.yml", + "header:\n version: 14\n includes:\n - kas/b.yml\n\ + repos:\n poky:\n url: https://git.yoctoproject.org/poky\n", + ), + ( + "kas/b.yml", + "header:\n version: 14\n includes:\n - kas/a.yml\n", + ), + ]); + let files: Vec = ["kas/a.yml", "kas/b.yml"].map(String::from).to_vec(); + assert_eq!(read(&t.0, &files).pins.len(), 1); + } + + #[test] + fn an_include_leaving_the_tree_is_not_read() { + let t = tree(&[( + "kas.yml", + "header:\n version: 14\n includes:\n - ../../etc/kas.yml\n", + )]); + let read = read(&t.0, &["kas.yml".to_string()]); + assert!(read.pins.is_empty()); + assert!(read.unread_includes.contains("../../etc/kas.yml")); + } + + #[test] + fn a_lock_file_pins_the_commits_and_a_refspec_may_be_one() { + let t = tree(&[ + ( + "kas.yml", + &format!( + "header:\n version: 8\nrepos:\n poky:\n \ + url: https://git.yoctoproject.org/poky\n refspec: refs/heads/kirkstone\n \ + meta-oe:\n url: https://github.com/openembedded/meta-openembedded\n \ + refspec: {SHA}\n" + ), + ), + ( + "kas.lock.yml", + &format!("header:\n version: 14\noverrides:\n repos:\n poky:\n commit: {SHA}\n"), + ), + ]); + let read = read(&t.0, &["kas.yml".to_string()]); + assert_eq!(read.pins[0].branch.as_deref(), Some("kirkstone")); + assert_eq!(read.pins[0].commit.as_deref(), Some(SHA)); + assert_eq!(read.pins[0].file, "kas.lock.yml"); + assert_eq!(read.pins[1].branch, None); + assert_eq!(read.pins[1].commit.as_deref(), Some(SHA)); + } + + #[test] + fn yaml_without_a_header_or_with_an_alias_bomb_is_not_read() { + let mut bomb = + String::from("header:\n version: 14\na: &a [x, x, x, x, x, x, x, x, x, x]\n"); + let mut previous = 'a'; + for name in ['b', 'c', 'd', 'e', 'f', 'g'] { + bomb.push_str(&format!( + "{name}: &{name} [*{previous}, *{previous}, *{previous}, *{previous}, \ + *{previous}, *{previous}, *{previous}, *{previous}, *{previous}, *{previous}]\n" + )); + previous = name; + } + let t = tree(&[ + ("kas.yml", bomb.as_str()), + ( + "kas-plain.yml", + "repos:\n poky:\n url: https://x/poky\n", + ), + ]); + assert!(load(&t.0, "kas.yml").is_none()); + assert!(load(&t.0, "kas-plain.yml").is_none()); + assert_eq!(expanded_nodes("a: &a [1, 2]\nb: *a\n"), Some(9)); + } +} diff --git a/compliance-agent/src/pipeline/yocto_pins/manifest.rs b/compliance-agent/src/pipeline/yocto_pins/manifest.rs new file mode 100644 index 0000000..66b87d3 --- /dev/null +++ b/compliance-agent/src/pipeline/yocto_pins/manifest.rs @@ -0,0 +1,298 @@ +//! `repo` tool manifests as layer pins. +//! +//! A manifest (`default.xml` and the files it includes) names remotes +//! (``), a default (``) +//! and the projects to check out (``). A project's URL is its remote's `fetch` and its name; its +//! revision is its own, else the remote's, else the default's. A revision may +//! be a commit, then `upstream` (or `dest-branch`) names the branch. +//! `` is read from the manifest's own directory, never fetched. + +use std::collections::BTreeSet; +use std::path::Path; + +use compliance_core::models::{LayerPin, PinSource}; + +use super::{clean_ref, is_commit, local_include, read_small}; + +/// Most manifest files one configuration may include. +const MAX_FILES: usize = 32; + +/// Whether `text` is a `repo` manifest: a `` root with projects or +/// includes (an Android app manifest is a `` without either). +fn is_manifest(doc: &roxmltree::Document<'_>) -> bool { + let root = doc.root_element(); + root.has_tag_name("manifest") + && root + .children() + .any(|c| c.has_tag_name("project") || c.has_tag_name("include")) +} + +/// One ``, with what it inherits not yet filled in. +#[derive(Debug, Clone)] +struct Project { + name: String, + remote: Option, + revision: Option, + upstream: Option, + file: String, +} + +/// Everything one manifest configuration declares, includes merged in +/// document order. +#[derive(Debug, Default)] +struct Declared { + /// name -> (fetch, revision) + remotes: Vec<(String, String, Option)>, + default_remote: Option, + default_revision: Option, + projects: Vec, + /// The files read, includes too. + files: Vec, +} + +/// Read the manifest `rel` under `root` and the files it includes into +/// `declared`; `stack` ends include cycles, `unread` collects includes that +/// could not be read. +fn declare( + root: &Path, + rel: &str, + declared: &mut Declared, + stack: &mut Vec, + unread: &mut BTreeSet, +) { + if stack.iter().any(|s| s == rel) || declared.files.len() >= MAX_FILES { + return; + } + let Some(text) = read_small(&root.join(rel)) else { + unread.insert(rel.to_string()); + return; + }; + // roxmltree refuses a DTD by default, so no entity can expand. + let Ok(doc) = roxmltree::Document::parse(&text) else { + unread.insert(rel.to_string()); + return; + }; + declared.files.push(rel.to_string()); + stack.push(rel.to_string()); + let attr = |n: &roxmltree::Node<'_, '_>, a: &str| n.attribute(a).map(str::to_string); + for node in doc.root_element().children().filter(|n| n.is_element()) { + match node.tag_name().name() { + "remote" => { + if let (Some(name), Some(fetch)) = (attr(&node, "name"), attr(&node, "fetch")) { + declared + .remotes + .push((name, fetch, attr(&node, "revision"))); + } + } + "default" => { + declared.default_remote = attr(&node, "remote").or(declared.default_remote.take()); + declared.default_revision = + attr(&node, "revision").or(declared.default_revision.take()); + } + "project" => { + if let Some(name) = attr(&node, "name") { + declared.projects.push(Project { + name, + remote: attr(&node, "remote"), + revision: attr(&node, "revision"), + upstream: attr(&node, "upstream").or_else(|| attr(&node, "dest-branch")), + file: rel.to_string(), + }); + } + } + "extend-project" => { + let name = attr(&node, "name"); + for project in declared + .projects + .iter_mut() + .filter(|p| Some(&p.name) == name.as_ref()) + { + if let Some(revision) = attr(&node, "revision") { + project.revision = Some(revision); + project.file = rel.to_string(); + } + if let Some(remote) = attr(&node, "remote") { + project.remote = Some(remote); + } + } + } + "remove-project" => { + let name = attr(&node, "name"); + declared.projects.retain(|p| Some(&p.name) != name.as_ref()); + } + "include" => { + let Some(name) = attr(&node, "name") else { + continue; + }; + match local_include(root, rel, &name) { + Some(found) => declare(root, &found, declared, stack, unread), + None => { + unread.insert(name); + } + } + } + _ => {} + } + } + stack.pop(); +} + +impl Declared { + fn pins(self) -> Vec { + let remote = |name: Option<&String>| { + name.and_then(|n| self.remotes.iter().rev().find(|(r, _, _)| r == n)) + }; + self.projects + .iter() + .map(|p| { + let remote = remote(p.remote.as_ref().or(self.default_remote.as_ref())); + let revision = p + .revision + .clone() + .or_else(|| remote.and_then(|(_, _, r)| r.clone())) + .or_else(|| self.default_revision.clone()); + let (branch, commit) = match revision { + Some(r) if is_commit(&r) => (p.upstream.clone(), Some(r)), + other => (other, None), + }; + LayerPin { + name: p.name.clone(), + source: PinSource::RepoManifest, + file: p.file.clone(), + url: remote + .map(|(_, fetch, _)| format!("{}/{}", fetch.trim_end_matches('/'), p.name)), + branch: branch.as_deref().and_then(clean_ref), + commit, + } + }) + .collect() + } +} + +/// What the manifests among `files` (XML files relative to `root`) pin, and +/// the includes that were not read. A manifest another one includes is read +/// with it, not on its own. +pub(crate) fn read(root: &Path, files: &[String]) -> (Vec, BTreeSet) { + let mut manifests: Vec = Vec::new(); + let mut included: BTreeSet = BTreeSet::new(); + for file in files { + let Some(text) = read_small(&root.join(file)) else { + continue; + }; + let Ok(doc) = roxmltree::Document::parse(&text) else { + continue; + }; + if !is_manifest(&doc) { + continue; + } + manifests.push(file.clone()); + included.extend( + doc.root_element() + .children() + .filter(|n| n.has_tag_name("include")) + .filter_map(|n| n.attribute("name")) + .filter_map(|name| local_include(root, file, name)), + ); + } + let mut pins: Vec = Vec::new(); + let mut unread = BTreeSet::new(); + let mut visited: BTreeSet = BTreeSet::new(); + // The manifests no other one includes first; then any left unread, + // which only an include cycle leaves. + let order = manifests + .iter() + .filter(|m| !included.contains(*m)) + .chain(manifests.iter().filter(|m| included.contains(*m))); + for manifest in order { + if visited.contains(manifest) { + continue; + } + let mut declared = Declared::default(); + declare(root, manifest, &mut declared, &mut Vec::new(), &mut unread); + visited.extend(declared.files.iter().cloned()); + for pin in declared.pins() { + if !pins.contains(&pin) { + pins.push(pin); + } + } + } + (pins, unread) +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + use crate::pipeline::recipe_lint::tests::tree; + + const SHA: &str = "4a2d3b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a"; + + #[test] + fn projects_inherit_remote_and_revision_and_includes_are_read() { + let t = tree(&[ + ( + "manifests/default.xml", + &format!( + "\n\n\ + \n\ + \n\ + \n\ + \n\ + \n\ + \n\ + \n\ + \n\ + \n\n" + ), + ), + ( + "manifests/bsp.xml", + "\n\n\ + \n\n", + ), + ( + "app/AndroidManifest.xml", + "", + ), + ]); + let files: Vec = [ + "manifests/default.xml", + "manifests/bsp.xml", + "app/AndroidManifest.xml", + ] + .map(String::from) + .to_vec(); + let (pins, unread) = read(&t.0, &files); + let names: Vec<&str> = pins.iter().map(|p| p.name.as_str()).collect(); + assert_eq!(names, ["poky", "meta-openembedded", "meta-arm"]); + assert_eq!( + pins[0].url.as_deref(), + Some("https://git.yoctoproject.org/poky") + ); + assert_eq!(pins[0].commit.as_deref(), Some(SHA)); + assert_eq!(pins[0].branch.as_deref(), Some("kirkstone")); + assert_eq!(pins[0].source, PinSource::RepoManifest); + assert_eq!( + pins[1].url.as_deref(), + Some("https://github.com/openembedded/meta-openembedded") + ); + assert_eq!(pins[1].branch.as_deref(), Some("scarthgap")); + assert_eq!(pins[2].branch.as_deref(), Some("yocto-4.0.3")); + assert_eq!(pins[2].file, "manifests/bsp.xml"); + assert_eq!(unread.into_iter().collect::>(), ["missing.xml"]); + } + + #[test] + fn a_manifest_with_a_dtd_is_not_read() { + let t = tree(&[( + "default.xml", + "\n]>\n\ + \n", + )]); + let (pins, _) = read(&t.0, &["default.xml".to_string()]); + assert!(pins.is_empty()); + } +} diff --git a/compliance-agent/src/pipeline/yocto_pins/mod.rs b/compliance-agent/src/pipeline/yocto_pins/mod.rs new file mode 100644 index 0000000..4bb49b2 --- /dev/null +++ b/compliance-agent/src/pipeline/yocto_pins/mod.rs @@ -0,0 +1,281 @@ +//! Layer pins of a Yocto / OpenEmbedded layer tree and the release they make +//! up (tier 1: nothing is fetched, nothing is built). +//! +//! The layers a build uses are pinned in one of three ways, all read here: +//! +//! - **kas** project files ([`kas`]), with their local includes; +//! - **`repo` manifests** ([`manifest`]), with their local includes; +//! - **git submodules** ([`gitmodules`]), with the commit the tree records. +//! +//! From the pins, or else from `LAYERSERIES_COMPAT`, [`release`] reads the +//! Yocto release and reports when its support has ended or ends soon. The +//! pins are stored on the target, where tier 2 (fetching the upstream layers +//! at their pins, importing the build's SPDX) will start from. + +pub mod gitmodules; +pub mod kas; +pub mod manifest; +pub mod release; + +use std::collections::BTreeSet; +use std::path::{Component, Path, PathBuf}; + +use compliance_core::models::LayerPins; + +use crate::pipeline::recipe_lint; + +/// The stage id an unknown release is recorded under. +pub const STAGE: &str = "yocto_release"; + +/// The largest kas file, manifest or `.gitmodules` that is read. +const MAX_FILE_BYTES: u64 = 1 << 20; + +/// How deep kas files and manifests are looked for. +const MAX_DEPTH: usize = 4; + +/// Directories never searched: version control, build output, downloads. +const SKIPPED_DIRS: &[&str] = &[".git", "build", "downloads", "sstate-cache", "node_modules"]; + +/// The text of the regular file at `path` (not a symlink), when it is at +/// most [`MAX_FILE_BYTES`]. +pub(crate) fn read_small(path: &Path) -> Option { + let meta = std::fs::symlink_metadata(path).ok()?; + if !meta.is_file() || meta.len() > MAX_FILE_BYTES { + return None; + } + std::fs::read_to_string(path).ok() +} + +/// Whether `value` is a full git commit id (SHA-1 or SHA-256). +pub(crate) fn is_commit(value: &str) -> bool { + matches!(value.len(), 40 | 64) && value.bytes().all(|b| b.is_ascii_hexdigit()) +} + +/// A branch or tag as shown: `refs/heads/` and `refs/tags/` dropped, `None` +/// when empty. +pub(crate) fn clean_ref(reference: &str) -> Option { + let trimmed = reference.trim(); + let name = trimmed + .strip_prefix("refs/heads/") + .or_else(|| trimmed.strip_prefix("refs/tags/")) + .unwrap_or(trimmed); + (!name.is_empty()).then(|| name.to_string()) +} + +/// `path` joined to `base` (relative to the tree) without leaving it; +/// `None` when a `..` climbs out. +fn inside(base: &Path, path: &str) -> Option { + let mut out = PathBuf::new(); + for part in base.join(path).components() { + match part { + Component::Normal(p) => out.push(p), + Component::CurDir => {} + Component::ParentDir => { + if !out.pop() { + return None; + } + } + Component::RootDir | Component::Prefix(_) => return None, + } + } + Some(out) +} + +/// The local file an include `path` in `including` (both relative to the +/// tree under `root`) names: relative to the including file's directory, +/// else to the tree. `None` for a URL, a path leaving the tree, a symlink or +/// a missing file. +pub(crate) fn local_include(root: &Path, including: &str, path: &str) -> Option { + if path.contains("://") || path.is_empty() { + return None; + } + let dir = Path::new(including).parent().unwrap_or(Path::new("")); + [dir, Path::new("")] + .into_iter() + .filter_map(|base| inside(base, path)) + .find(|rel| std::fs::symlink_metadata(root.join(rel)).is_ok_and(|m| m.is_file())) + .map(|rel| rel.to_string_lossy().replace('\\', "/")) +} + +/// The layer pins of the tree under `root` and the release they make up, +/// outside the `excluded` vendor directories. A submodule's own kas files +/// and manifests are its repository's, not the tree's, and are not read. +pub fn read(root: &Path, excluded: &[String]) -> LayerPins { + let (submodule_pins, submodule_paths) = gitmodules::pins(root); + let mut kas_files = Vec::new(); + let mut xml_files = Vec::new(); + let walk = walkdir::WalkDir::new(root) + .min_depth(1) + .max_depth(MAX_DEPTH) + .sort_by_file_name() + .into_iter() + .filter_entry(|e| { + let rel = recipe_lint::rel_path(root, e.path()); + !(e.file_type().is_dir() + && (SKIPPED_DIRS.contains(&e.file_name().to_string_lossy().as_ref()) + || excluded.contains(&rel) + || submodule_paths.contains(&rel))) + }) + .filter_map(Result::ok) + .filter(|e| e.file_type().is_file()); + for entry in walk { + let rel = recipe_lint::rel_path(root, entry.path()); + if kas::is_kas_file(&rel) { + kas_files.push(rel); + } else if rel.ends_with(".xml") { + xml_files.push(rel); + } + } + let kas = kas::read(root, &kas_files); + let (manifest_pins, manifest_unread) = manifest::read(root, &xml_files); + let pins: Vec<_> = kas + .pins + .into_iter() + .chain(manifest_pins) + .chain(submodule_pins) + .collect(); + let layers = recipe_lint::layers(root, excluded); + let unread: BTreeSet = kas + .unread_includes + .into_iter() + .chain(manifest_unread) + .collect(); + LayerPins { + release: release::derive(&pins, &layers), + pins, + unread_includes: unread.into_iter().collect(), + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + use crate::pipeline::recipe_lint::tests::tree; + use compliance_core::models::{PinSource, ReleaseBasis}; + + #[test] + fn refs_and_commits_are_recognised() { + assert_eq!( + clean_ref("refs/heads/kirkstone").as_deref(), + Some("kirkstone") + ); + assert_eq!( + clean_ref("refs/tags/yocto-5.0.3").as_deref(), + Some("yocto-5.0.3") + ); + assert_eq!(clean_ref(" "), None); + assert!(is_commit("4a2d3b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a")); + assert!(!is_commit("kirkstone")); + assert!(!is_commit("4a2d3b5")); + } + + #[test] + fn includes_resolve_beside_the_file_then_from_the_root_and_never_outside() { + let t = tree(&[("kas/a.yml", ""), ("kas/b.yml", ""), ("common.yml", "")]); + assert_eq!( + local_include(&t.0, "kas/a.yml", "b.yml").as_deref(), + Some("kas/b.yml") + ); + assert_eq!( + local_include(&t.0, "kas/a.yml", "kas/b.yml").as_deref(), + Some("kas/b.yml") + ); + assert_eq!( + local_include(&t.0, "kas/a.yml", "../common.yml").as_deref(), + Some("common.yml") + ); + assert_eq!(local_include(&t.0, "kas/a.yml", "../../x.yml"), None); + assert_eq!(local_include(&t.0, "kas/a.yml", "/etc/passwd"), None); + assert_eq!(local_include(&t.0, "kas/a.yml", "https://x/y.yml"), None); + assert_eq!(local_include(&t.0, "kas/a.yml", "missing.yml"), None); + } + + #[test] + fn a_tree_pins_its_layers_and_the_pins_name_the_release() { + let t = tree(&[ + ( + "kas.yml", + "header:\n version: 14\nrepos:\n poky:\n \ + url: https://git.yoctoproject.org/poky\n branch: dunfell\n \ + commit: 4a2d3b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a\n", + ), + ( + ".gitmodules", + "[submodule \"meta-vendor\"]\n\tpath = layers/meta-vendor\n\t\ + url = https://git.example.com/meta-vendor.git\n", + ), + // A submodule's own kas files are not the tree's. + ( + "layers/meta-vendor/kas.yml", + "header:\n version: 14\nrepos:\n x:\n url: https://x/x\n", + ), + ( + "conf/layer.conf", + "BBFILE_COLLECTIONS += \"pump\"\nLAYERSERIES_COMPAT_pump = \"scarthgap\"\n", + ), + ("recipes-app/pump/pump_1.0.bb", ""), + ]); + let read = read(&t.0, &[]); + let names: Vec<(&str, PinSource)> = read + .pins + .iter() + .map(|p| (p.name.as_str(), p.source)) + .collect(); + assert_eq!( + names, + [ + ("poky", PinSource::Kas), + ("meta-vendor", PinSource::GitSubmodule) + ] + ); + let release = read.release.expect("release"); + // The pin wins over the layer's LAYERSERIES_COMPAT. + assert_eq!(release.codename, "dunfell"); + assert!(matches!(release.basis, ReleaseBasis::Pin { .. })); + } + + #[test] + fn the_nightly_fixture_pins_dunfell_and_is_end_of_life() { + let root = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/nightly/firmware/yocto-layer"); + let read = read(&root, &[]); + let pins: Vec = read + .pins + .iter() + .map(|p| { + format!( + "{:?} {} {}@{}", + p.source, + p.name, + p.branch.as_deref().unwrap_or("-"), + p.commit.as_deref().unwrap_or("-") + ) + }) + .collect(); + assert_eq!( + pins, + [ + // Included files' repositories come first, as kas merges them. + "Kas meta-openembedded dunfell@-", + "Kas poky dunfell@0b1f2c3d4e5f60718293a4b5c6d7e8f901234567", + "GitSubmodule meta-security dunfell@-", + ] + ); + assert_eq!(read.unread_includes, ["meta-vendor:kas/vendor.yml"]); + let release = read.release.expect("release"); + assert_eq!(release.codename, "dunfell"); + let today = chrono::NaiveDate::from_ymd_opt(2026, 10, 9).expect("date"); + let finding = release::finding("t", &release, today).expect("finding"); + assert_eq!(finding.rule_id.as_deref(), Some(release::RULE_EOL)); + assert_eq!(finding.file_path.as_deref(), Some("kas.yml")); + } + + #[test] + fn a_tree_without_pins_or_compat_has_no_release() { + let t = tree(&[("recipes-app/pump/pump_1.0.bb", "")]); + let read = read(&t.0, &[]); + assert!(read.pins.is_empty()); + assert_eq!(read.release, None); + } +} diff --git a/compliance-agent/src/pipeline/yocto_pins/release.rs b/compliance-agent/src/pipeline/yocto_pins/release.rs new file mode 100644 index 0000000..f9a5fe6 --- /dev/null +++ b/compliance-agent/src/pipeline/yocto_pins/release.rs @@ -0,0 +1,536 @@ +//! The Yocto release a layer tree builds, its support period, and a finding +//! when that period is over or ends soon. + +use chrono::{Months, NaiveDate}; +use compliance_core::models::{ + display_codename, Finding, LayerPin, ReleaseBasis, ScanType, Severity, Support, YoctoRelease, +}; + +use crate::pipeline::dedup; +use crate::pipeline::recipe_lint::Layer; + +/// The scanner name of the support-status findings. +pub const SCANNER: &str = "yocto-release"; +/// The rule of a release past its end of life. +pub const RULE_EOL: &str = "yocto-release-eol"; +/// The rule of a release whose end of life is within six months. +pub const RULE_EOL_SOON: &str = "yocto-release-eol-soon"; +/// Where the support periods come from. +pub const SOURCE_URL: &str = "https://wiki.yoctoproject.org/wiki/Releases"; +/// When [`RELEASES`] was checked against its sources. +pub const CHECKED_ON: &str = "2026-10-09"; + +/// How far ahead an end of life counts as soon (as [`YoctoRelease::support`] +/// counts it): the current LTS is one supported for longer. +const SOON: Months = Months::new(6); + +/// One Yocto Project release. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ReleaseInfo { + /// The codename, lower case. + pub codename: &'static str, + /// The Yocto Project version. + pub version: &'static str, + /// A long term support release. + pub lts: bool, + /// Its release day. + pub released: NaiveDate, + /// The day its support ends (or ended). + pub end_of_life: NaiveDate, +} + +/// A day of the table; every date in it is valid, a test checks them. +const fn day(y: i32, m: u32, d: u32) -> NaiveDate { + match NaiveDate::from_ymd_opt(y, m, d) { + Some(date) => date, + None => NaiveDate::MIN, + } +} + +const fn release( + codename: &'static str, + version: &'static str, + lts: bool, + released: NaiveDate, + end_of_life: NaiveDate, +) -> ReleaseInfo { + ReleaseInfo { + codename, + version, + lts, + released, + end_of_life, + } +} + +/// The Yocto Project releases, oldest first. +/// +/// Source: the Yocto Project releases wiki, +/// (page last updated 2026-09-10), checked on 2026-10-09: codename, version, +/// LTS and support status. The wiki gives months only; the exact release and +/// end-of-life days are endoflife.date's (, +/// checked the same day), which agree with the wiki's months except +/// Walnascar (wiki: "EOL since November 2025", endoflife.date: 2025-12-07). +/// For Thud and older, which endoflife.date does not list, the end of life +/// is the last day of the month of the release's last point release (wiki), +/// and the release day the first of its month. Blacksail (6.1, due October +/// 2026) is not released yet and not listed: a newer branch reads as an +/// unknown release. +pub const RELEASES: &[ReleaseInfo] = &[ + release("jethro", "2.0", false, day(2015, 11, 1), day(2017, 1, 31)), + release("krogoth", "2.1", false, day(2016, 4, 1), day(2017, 7, 31)), + release("morty", "2.2", false, day(2016, 11, 1), day(2018, 7, 31)), + release("pyro", "2.3", false, day(2017, 5, 1), day(2018, 7, 31)), + release("rocko", "2.4", false, day(2017, 10, 1), day(2018, 11, 30)), + release("sumo", "2.5", false, day(2018, 4, 1), day(2019, 4, 30)), + release("thud", "2.6", false, day(2018, 11, 1), day(2019, 10, 31)), + release("warrior", "2.7", false, day(2019, 5, 1), day(2020, 6, 1)), + release("zeus", "3.0", false, day(2019, 10, 22), day(2020, 8, 1)), + release("dunfell", "3.1", true, day(2020, 4, 21), day(2024, 4, 30)), + release( + "gatesgarth", + "3.2", + false, + day(2020, 11, 3), + day(2021, 5, 1), + ), + release( + "hardknott", + "3.3", + false, + day(2021, 4, 19), + day(2022, 4, 20), + ), + release("honister", "3.4", false, day(2021, 10, 25), day(2022, 5, 1)), + release("kirkstone", "4.0", true, day(2022, 4, 25), day(2026, 4, 27)), + release( + "langdale", + "4.1", + false, + day(2022, 10, 23), + day(2023, 5, 27), + ), + release( + "mickledore", + "4.2", + false, + day(2023, 5, 3), + day(2023, 11, 5), + ), + release("nanbield", "4.3", false, day(2023, 11, 9), day(2024, 6, 9)), + release("scarthgap", "5.0", true, day(2024, 4, 29), day(2028, 4, 30)), + release("styhead", "5.1", false, day(2024, 10, 16), day(2025, 5, 16)), + release("walnascar", "5.2", false, day(2025, 5, 7), day(2025, 12, 7)), + release( + "whinlatter", + "5.3", + false, + day(2025, 12, 15), + day(2026, 6, 15), + ), + release("wrynose", "6.0", true, day(2026, 5, 13), day(2030, 4, 30)), +]; + +/// The repositories whose branch names the release, most telling first. +const RELEASE_REPOS: &[&str] = &["poky", "openembedded-core", "meta-openembedded"]; + +fn by_codename(codename: &str) -> Option<&'static ReleaseInfo> { + RELEASES.iter().find(|r| r.codename == codename) +} + +/// The release a branch or tag names: a codename as one of its words +/// (`scarthgap`, `scarthgap-5.0.3`, `kirkstone-4.0.15`, `dunfell-23.0.10`), +/// or a `yocto-` tag (`yocto-5.0.3`). `master` names none. +pub(crate) fn from_reference(reference: &str) -> Option<&'static ReleaseInfo> { + let lower = reference.to_ascii_lowercase(); + if let Some(found) = lower + .split(|c: char| !c.is_ascii_alphanumeric()) + .find_map(by_codename) + { + return Some(found); + } + let version = lower.rsplit('/').next()?.strip_prefix("yocto-")?; + let mut parts = version.split('.'); + let major_minor = format!("{}.{}", parts.next()?, parts.next()?); + RELEASES.iter().find(|r| r.version == major_minor) +} + +/// The newest of `codenames` the table knows. +fn newest<'a>(codenames: impl IntoIterator) -> Option<&'static ReleaseInfo> { + codenames + .into_iter() + .filter_map(|c| by_codename(c)) + .max_by_key(|r| r.released) +} + +/// Whether `pin` is the repository `repo` (by its URL's last segment, else +/// its name). +fn pin_is(pin: &LayerPin, repo: &str) -> bool { + let tail = pin.url.as_deref().and_then(|url| { + url.trim_end_matches('/') + .rsplit(['/', ':']) + .next() + .map(|t| t.trim_end_matches(".git")) + }); + tail.unwrap_or(&pin.name) == repo || pin.name == repo +} + +/// The configuration file of `layer`, relative to the tree. +fn conf_of(layer: &Layer) -> String { + if layer.dir == "." { + "conf/layer.conf".to_string() + } else { + format!("{}/conf/layer.conf", layer.dir) + } +} + +/// The release the tree builds, from the first of: +/// +/// 1. the branch or tag of a Poky, OpenEmbedded-Core or meta-openembedded pin +/// (in that order): what the build fetches; +/// 2. `LAYERSERIES_COMPAT_core` of an OpenEmbedded-Core layer in the tree; +/// 3. the newest release every customer layer declares compatible in +/// `LAYERSERIES_COMPAT_*`: the build can use no newer one, and a layer +/// that also names older releases is not built on those for it (the +/// recipe lint reads the oldest instead, for the syntax it must accept). +/// +/// `None` when none of them names a release the table knows. +pub(crate) fn derive(pins: &[LayerPin], layers: &[Layer]) -> Option { + let make = |info: &ReleaseInfo, basis: ReleaseBasis, file: String| YoctoRelease { + codename: info.codename.to_string(), + version: info.version.to_string(), + lts: info.lts, + end_of_life: info.end_of_life, + basis, + file, + }; + for repo in RELEASE_REPOS { + for pin in pins.iter().filter(|p| pin_is(p, repo)) { + let Some(branch) = &pin.branch else { continue }; + if let Some(info) = from_reference(branch) { + let basis = ReleaseBasis::Pin { + name: pin.name.clone(), + branch: branch.clone(), + }; + return Some(make(info, basis, pin.file.clone())); + } + } + } + let core = layers + .iter() + .filter(|l| l.collections.iter().any(|c| c == "core")) + .find_map(|l| newest(&l.compat).map(|info| (info, conf_of(l)))); + if let Some((info, file)) = core { + return Some(make(info, ReleaseBasis::CoreLayer, file)); + } + let own: Vec<&Layer> = layers + .iter() + .filter(|l| !l.upstream && !l.compat.is_empty()) + .collect(); + let first = own.first()?; + let common = first + .compat + .iter() + .filter(|c| own.iter().all(|l| l.compat.contains(c))); + newest(common).map(|info| make(info, ReleaseBasis::LayerCompat, conf_of(first))) +} + +/// The newest LTS release supported for more than [`SOON`] on `today`. +fn current_lts(today: NaiveDate) -> Option<&'static ReleaseInfo> { + let horizon = today.checked_add_months(SOON)?; + RELEASES + .iter() + .filter(|r| r.lts && r.released <= today && r.end_of_life > horizon) + .max_by_key(|r| r.released) +} + +/// What `basis` (in `file`) is, in words. +fn basis_text(basis: &ReleaseBasis, file: &str) -> String { + match basis { + ReleaseBasis::Pin { name, branch } => { + format!("the branch or tag \"{branch}\" that {file} pins {name} to") + } + ReleaseBasis::CoreLayer => { + format!("LAYERSERIES_COMPAT_core of the OpenEmbedded-Core layer ({file})") + } + ReleaseBasis::LayerCompat => format!( + "LAYERSERIES_COMPAT of your layers ({file}): the newest release they all declare" + ), + } +} + +/// The support-status finding of `repo_id` for `release` on `today`; +/// `None` while it is supported for more than six months. +pub(crate) fn finding(repo_id: &str, release: &YoctoRelease, today: NaiveDate) -> Option { + let (rule, severity, title, status) = match release.support(today) { + Support::Supported => return None, + Support::Ended => ( + RULE_EOL, + Severity::High, + "is end of life since", + "ended its support on", + ), + Support::EndsSoon => ( + RULE_EOL_SOON, + Severity::Medium, + "reaches end of life on", + "ends its support on", + ), + }; + let name = display_codename(&release.codename); + let lts = if release.lts { " LTS" } else { "" }; + let eol = release.end_of_life; + let description = format!( + "The layers build Yocto {name} ({version}{lts}), read from {basis}. The Yocto Project \ + {status} {eol} (source: {SOURCE_URL}, checked {CHECKED_ON}). After that, no security \ + fixes are published for its recipes, so vulnerabilities in the image's components \ + stay open unless every fix is backported by hand.\n\nCRA Annex I Part I (2)(c): \ + vulnerabilities can be addressed through security updates; Annex I Part II (2): \ + vulnerabilities are remediated without delay, including by security updates, over \ + the product's support period.", + version = release.version, + basis = basis_text(&release.basis, &release.file), + ); + let remediation = match current_lts(today) { + Some(lts) if lts.codename != release.codename => format!( + "Move the layers to the current long term support release, Yocto {} ({}), \ + supported until {}: update the pins of Poky / OpenEmbedded-Core and the other \ + layers to its branch, and LAYERSERIES_COMPAT of your layers. Until then, \ + backport the security fixes the product needs and record them (CVE_STATUS, \ + patches).", + display_codename(lts.codename), + lts.version, + lts.end_of_life + ), + _ => "Move the layers to a Yocto release that is supported for the product's support \ + period, and backport security fixes until then." + .to_string(), + }; + let fingerprint = + dedup::compute_fingerprint(&[repo_id, SCANNER, rule, &release.file, &release.codename]); + let mut finding = Finding::new( + repo_id.to_string(), + fingerprint, + SCANNER.to_string(), + ScanType::Sbom, + format!("Yocto {name} ({}) {title} {eol}", release.version), + description, + severity, + ); + finding.rule_id = Some(rule.to_string()); + finding.cwe = Some("CWE-1104".to_string()); + finding.remediation = Some(remediation); + finding.file_path = Some(release.file.clone()); + Some(finding) +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + use compliance_core::models::PinSource; + + fn date(y: i32, m: u32, d: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, d).expect("date") + } + + fn pin(name: &str, url: &str, branch: Option<&str>) -> LayerPin { + LayerPin { + name: name.into(), + source: PinSource::Kas, + file: "kas.yml".into(), + url: Some(url.into()), + branch: branch.map(str::to_string), + commit: None, + } + } + + fn layer(dir: &str, collections: &[&str], compat: &[&str], upstream: bool) -> Layer { + Layer { + dir: dir.into(), + release: None, + upstream, + collections: collections.iter().map(|c| c.to_string()).collect(), + compat: compat.iter().map(|c| c.to_string()).collect(), + files: Vec::new(), + } + } + + #[test] + fn the_table_is_ordered_and_names_the_required_releases() { + assert!(RELEASES.iter().all(|r| r.released != NaiveDate::MIN + && r.end_of_life != NaiveDate::MIN + && r.released < r.end_of_life)); + assert!(RELEASES.windows(2).all(|w| w[0].released < w[1].released)); + for codename in [ + "dunfell", + "kirkstone", + "mickledore", + "nanbield", + "scarthgap", + "styhead", + "walnascar", + "whinlatter", + "wrynose", + ] { + assert!(by_codename(codename).is_some(), "{codename}"); + } + assert_eq!(date(2026, 10, 9).to_string(), CHECKED_ON); + } + + #[test] + fn branches_and_tags_name_their_release() { + let codename = |r: &str| from_reference(r).map(|i| i.codename); + assert_eq!(codename("scarthgap"), Some("scarthgap")); + assert_eq!(codename("scarthgap-5.0.3"), Some("scarthgap")); + assert_eq!(codename("yocto-5.0.3"), Some("scarthgap")); + assert_eq!(codename("refs/tags/yocto-4.0.15"), Some("kirkstone")); + assert_eq!(codename("kirkstone-4.0.15"), Some("kirkstone")); + assert_eq!(codename("dunfell-23.0.10"), Some("dunfell")); + assert_eq!(codename("Mickledore"), Some("mickledore")); + assert_eq!(codename("master"), None); + assert_eq!(codename("main"), None); + assert_eq!(codename("yocto-9.9"), None); + assert_eq!(codename("blacksail"), None); + } + + #[test] + fn poky_pins_win_over_meta_openembedded_and_layer_compat() { + let pins = [ + pin( + "meta-oe", + "https://github.com/openembedded/meta-openembedded.git", + Some("scarthgap"), + ), + pin("poky", "https://git.yoctoproject.org/poky", Some("dunfell")), + ]; + let layers = [layer(".", &["pump"], &["scarthgap"], false)]; + let release = derive(&pins, &layers).expect("release"); + assert_eq!(release.codename, "dunfell"); + assert_eq!( + release.basis, + ReleaseBasis::Pin { + name: "poky".into(), + branch: "dunfell".into() + } + ); + assert_eq!(release.file, "kas.yml"); + // meta-openembedded speaks when poky names no release. + let pins = [ + pin("poky", "https://git.yoctoproject.org/poky", None), + pin( + "meta-oe", + "git@github.com:openembedded/meta-openembedded.git", + Some("kirkstone"), + ), + ]; + assert_eq!( + derive(&pins, &layers).expect("release").codename, + "kirkstone" + ); + } + + #[test] + fn without_pins_the_core_layer_then_the_customer_layers_decide() { + let core = layer("poky/meta", &["core"], &["nanbield"], true); + let own = layer("meta-pump", &["pump"], &["kirkstone", "scarthgap"], false); + let release = derive(&[], &[core, own.clone()]).expect("release"); + assert_eq!(release.codename, "nanbield"); + assert_eq!(release.basis, ReleaseBasis::CoreLayer); + assert_eq!(release.file, "poky/meta/conf/layer.conf"); + // The newest release every own layer declares. + let other = layer( + "meta-ui", + &["ui"], + &["kirkstone", "scarthgap", "wrynose"], + false, + ); + let release = derive(&[], &[own.clone(), other]).expect("release"); + assert_eq!(release.codename, "scarthgap"); + assert_eq!(release.basis, ReleaseBasis::LayerCompat); + assert_eq!(release.file, "meta-pump/conf/layer.conf"); + // Layers with nothing in common, or no compat at all: unknown. + let apart = layer("meta-ui", &["ui"], &["wrynose"], false); + assert_eq!(derive(&[], &[own, apart]), None); + assert_eq!(derive(&[], &[layer(".", &["x"], &[], false)]), None); + } + + fn release_of(codename: &str) -> YoctoRelease { + let info = by_codename(codename).expect("known"); + YoctoRelease { + codename: codename.into(), + version: info.version.into(), + lts: info.lts, + end_of_life: info.end_of_life, + basis: ReleaseBasis::Pin { + name: "poky".into(), + branch: codename.into(), + }, + file: "kas.yml".into(), + } + } + + #[test] + fn an_ended_release_is_a_high_finding_naming_the_date_source_and_current_lts() { + let today = date(2026, 10, 9); + let f = finding("t1", &release_of("dunfell"), today).expect("finding"); + assert_eq!(f.scanner, SCANNER); + assert_eq!(f.rule_id.as_deref(), Some(RULE_EOL)); + assert_eq!(f.severity, Severity::High); + assert_eq!(f.scan_type, ScanType::Sbom); + assert_eq!( + f.title, + "Yocto Dunfell (3.1) is end of life since 2024-04-30" + ); + assert!(f.description.contains("Yocto Dunfell (3.1 LTS)")); + assert!(f + .description + .contains("\"dunfell\" that kas.yml pins poky to")); + assert!(f.description.contains(SOURCE_URL)); + assert!(f.description.contains("Annex I Part I (2)(c)")); + assert!(f.description.contains("Part II")); + assert_eq!(f.file_path.as_deref(), Some("kas.yml")); + assert_eq!(f.cwe.as_deref(), Some("CWE-1104")); + // Wrynose is the newest LTS released by then. + assert!(f + .remediation + .as_deref() + .expect("remediation") + .contains("Yocto Wrynose (6.0), supported until 2030-04-30")); + } + + #[test] + fn a_release_ending_soon_is_medium_and_a_supported_one_none() { + let today = date(2026, 3, 1); + let f = finding("t1", &release_of("kirkstone"), today).expect("finding"); + assert_eq!(f.rule_id.as_deref(), Some(RULE_EOL_SOON)); + assert_eq!(f.severity, Severity::Medium); + assert_eq!( + f.title, + "Yocto Kirkstone (4.0) reaches end of life on 2026-04-27" + ); + // Wrynose is not out yet: Scarthgap is the current LTS. + assert!(f + .remediation + .as_deref() + .expect("r") + .contains("Yocto Scarthgap (5.0)")); + assert!(finding("t1", &release_of("scarthgap"), today).is_none()); + // A different release is a different finding. + let other = finding("t1", &release_of("mickledore"), today).expect("finding"); + assert_ne!(other.fingerprint, f.fingerprint); + } + + #[test] + fn the_rules_are_bound_in_the_control_map() { + let map = control_map::ControlMap::cra().expect("map"); + for rule in [RULE_EOL, RULE_EOL_SOON] { + let controls: Vec = map + .controls_for_finding(SCANNER, Some("CWE-1104"), Some(rule)) + .into_iter() + .map(|c| c.control.clone()) + .collect(); + assert_eq!(controls, ["cra-ai-22"], "{rule}"); + } + } +} diff --git a/compliance-agent/tests/nightly.rs b/compliance-agent/tests/nightly.rs index cc76619..9f23f9e 100644 --- a/compliance-agent/tests/nightly.rs +++ b/compliance-agent/tests/nightly.rs @@ -337,6 +337,13 @@ struct Snapshot { findings: BTreeSet, /// CVE and advisory ids; the run must contain at least these. cves: BTreeSet, + /// A Yocto target's layer pins as `source name branch@commit` (`-` for + /// what is not pinned), compared exactly. + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + layer_pins: BTreeSet, + /// The Yocto release read from them, compared exactly. + #[serde(default, skip_serializing_if = "String::is_empty")] + yocto_release: String, } impl Snapshot { @@ -379,6 +386,13 @@ impl Snapshot { out.extend(exact("SBOM component", &self.sbom, &baseline.sbom)); out.extend(exact("finding", &self.findings, &baseline.findings)); out.extend(at_least("CVE", &self.cves, &baseline.cves)); + out.extend(exact("layer pin", &self.layer_pins, &baseline.layer_pins)); + if self.yocto_release != baseline.yocto_release { + out.push(format!( + "Yocto release \"{}\", blessed \"{}\"", + self.yocto_release, baseline.yocto_release + )); + } out } } @@ -488,6 +502,19 @@ async fn collect(agent: &Agent, target_id: &str, run: &Value) -> Collected { } } + let pins = &target["layer_pins"]; + for pin in pins["pins"].as_array().into_iter().flatten() { + let or_dash = |key: &str| pin[key].as_str().unwrap_or("-").to_string(); + snapshot.layer_pins.insert(format!( + "{} {} {}@{}", + text(pin, "source"), + text(pin, "name"), + or_dash("branch"), + or_dash("commit") + )); + } + snapshot.yocto_release = text(&pins["release"], "codename"); + let facts = target["classification"]["facts"] .as_array() .into_iter() @@ -733,6 +760,7 @@ mod unit { sbom: set(&["cargo:itoa@1.0.15"]), findings: set(&["gitleaks:aws-key a.py:3"]), cves: set(&["CVE-2020-1", "GHSA-xxxx-yyyy-zzzz"]), + ..Default::default() }; let mut run = blessed.clone(); assert!(run.diff(&blessed).is_empty()); @@ -741,8 +769,10 @@ mod unit { // A new CVE is fine, a lost one is not. run.cves = set(&["CVE-2020-1", "CVE-2026-9"]); run.scan_status = "failed".into(); + run.layer_pins = set(&["kas poky dunfell@-"]); let diff = run.diff(&blessed); for needle in [ + "unexpected layer pin: kas poky dunfell@-", "scan status failed, blessed completed", "missing SBOM component: cargo:itoa@1.0.15", "unexpected SBOM component: cargo:itoa@1.0.16", diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index 974082e..395c322 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -23,6 +23,7 @@ pub(crate) mod serde_helpers; pub mod vex; pub mod webhook_delivery; pub mod werkbank; +pub mod yocto; pub use auth::{AuthInfo, SupportTenant}; pub use chat::{ChatMessage, ChatRequest, ChatResponse, SourceReference}; @@ -77,3 +78,6 @@ pub use werkbank::{ InputRef, Job, JobCollect, JobRecord, JobResult, JobRuntime, JobStatus, JobType, LeaseRequest, LeasedJob, }; +pub use yocto::{ + display_codename, LayerPin, LayerPins, PinSource, ReleaseBasis, Support, YoctoRelease, +}; diff --git a/compliance-core/src/models/onboarding.rs b/compliance-core/src/models/onboarding.rs index 08ec072..1b9c7ea 100644 --- a/compliance-core/src/models/onboarding.rs +++ b/compliance-core/src/models/onboarding.rs @@ -643,6 +643,10 @@ pub struct OnboardedTarget { /// target can be skipped (#465). #[serde(default, skip_serializing_if = "Option::is_none")] pub last_scan: Option, + /// The layers a Yocto layer tree pins and the release they make up, from + /// its last scan; `None` for every other target. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub layer_pins: Option, /// Creation timestamp. #[serde( default = "chrono::Utc::now", @@ -682,6 +686,7 @@ impl OnboardedTarget { type_chosen: false, archived_at: None, last_scan: None, + layer_pins: 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..e5d50be 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, + /// The Yocto release a layer tree builds could not be read from its + /// layer pins or `LAYERSERIES_COMPAT`, so its support period was not + /// checked. + ReleaseUnknown, } /// Why a scan run failed, stable for the dashboard to word. diff --git a/compliance-core/src/models/yocto.rs b/compliance-core/src/models/yocto.rs new file mode 100644 index 0000000..53c12b2 --- /dev/null +++ b/compliance-core/src/models/yocto.rs @@ -0,0 +1,193 @@ +//! What a Yocto / OpenEmbedded layer tree pins: the layers it builds from +//! (kas files, `repo` manifests, git submodules) and the Yocto release they +//! make up. Read without fetching anything and without a build (tier 1). + +use chrono::{Months, NaiveDate}; +use serde::{Deserialize, Serialize}; + +/// Where a layer pin is declared. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum PinSource { + /// A kas project file (`repos:`), with its local includes. + Kas, + /// A `repo` tool manifest (``). + RepoManifest, + /// A git submodule (`.gitmodules`, and the commit the tree records). + GitSubmodule, +} + +/// One layer repository the tree builds from, as its configuration pins it. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct LayerPin { + /// The repository's name in the file (kas repo key, manifest project + /// name, submodule name). + pub name: String, + /// Where it is declared. + pub source: PinSource, + /// The declaring file, relative to the tree. + pub file: String, + /// The repository URL; `None` for the tree's own repository (a kas repo + /// without `url`). + #[serde(default)] + pub url: Option, + /// The branch, tag or refspec named, as written (`refs/heads/` dropped). + #[serde(default)] + pub branch: Option, + /// The commit it is pinned to. + #[serde(default)] + pub commit: Option, +} + +/// What the Yocto release of the tree was read from. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum ReleaseBasis { + /// The branch or tag a pin of Poky, OpenEmbedded-Core or + /// meta-openembedded names. + Pin { + /// The pin's name. + name: String, + /// The branch or tag it names. + branch: String, + }, + /// `LAYERSERIES_COMPAT_core` of the OpenEmbedded-Core layer in the tree. + CoreLayer, + /// The newest release every one of the customer's layers declares in + /// `LAYERSERIES_COMPAT_*`. + LayerCompat, +} + +/// The Yocto release a tree builds and its support period. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct YoctoRelease { + /// The codename, lower case (`scarthgap`). + pub codename: String, + /// The Yocto Project version (`5.0`). + pub version: String, + /// A long term support release. + pub lts: bool, + /// The day its support ends (or ended). + pub end_of_life: NaiveDate, + /// What it was read from. + pub basis: ReleaseBasis, + /// The file it was read from, relative to the tree. + pub file: String, +} + +/// A codename as written in prose: `dunfell` -> `Dunfell`. +pub fn display_codename(codename: &str) -> String { + let mut chars = codename.chars(); + chars + .next() + .map(|c| c.to_uppercase().chain(chars).collect()) + .unwrap_or_default() +} + +/// How far ahead an end of life counts as soon. +const SOON: Months = Months::new(6); + +/// Where a release's support stands on a day. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Support { + /// Supported for more than six months. + Supported, + /// Its support ends within six months. + EndsSoon, + /// Its support has ended (after its last day). + Ended, +} + +impl YoctoRelease { + /// Where its support stands on `today`. + pub fn support(&self, today: NaiveDate) -> Support { + if self.end_of_life < today { + Support::Ended + } else if today + .checked_add_months(SOON) + .is_none_or(|horizon| self.end_of_life <= horizon) + { + Support::EndsSoon + } else { + Support::Supported + } + } +} + +/// The layer pins of a Yocto target and the release they make up, from its +/// last scan. +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +pub struct LayerPins { + /// Every pin, in the order the files declare them. + #[serde(default)] + pub pins: Vec, + /// The release, when one could be read. + #[serde(default)] + pub release: Option, + /// Includes that were not read: remote ones (another repository, a URL) + /// and local ones that are missing or leave the tree. + #[serde(default)] + pub unread_includes: Vec, +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + + fn release(end_of_life: NaiveDate) -> YoctoRelease { + YoctoRelease { + codename: "scarthgap".into(), + version: "5.0".into(), + lts: true, + end_of_life, + basis: ReleaseBasis::CoreLayer, + file: "conf/layer.conf".into(), + } + } + + #[test] + fn codenames_are_capitalised() { + assert_eq!(display_codename("dunfell"), "Dunfell"); + assert_eq!(display_codename(""), ""); + } + + #[test] + fn support_ends_soon_within_six_months_and_ends_after_its_last_day() { + let date = |y, m, d| NaiveDate::from_ymd_opt(y, m, d).expect("date"); + let scarthgap = release(date(2028, 4, 30)); + assert_eq!(scarthgap.support(date(2026, 10, 9)), Support::Supported); + assert_eq!(scarthgap.support(date(2027, 10, 29)), Support::Supported); + assert_eq!(scarthgap.support(date(2027, 10, 30)), Support::EndsSoon); + assert_eq!(scarthgap.support(date(2028, 4, 30)), Support::EndsSoon); + assert_eq!(scarthgap.support(date(2028, 5, 1)), Support::Ended); + } + + #[test] + fn layer_pins_round_trip_through_bson() { + let pins = LayerPins { + pins: vec![LayerPin { + name: "poky".into(), + source: PinSource::Kas, + file: "kas.yml".into(), + url: Some("https://git.yoctoproject.org/poky".into()), + branch: Some("dunfell".into()), + commit: Some("a".repeat(40)), + }], + release: Some(YoctoRelease { + codename: "dunfell".into(), + version: "3.1".into(), + lts: true, + end_of_life: NaiveDate::from_ymd_opt(2024, 4, 30).expect("date"), + basis: ReleaseBasis::Pin { + name: "poky".into(), + branch: "dunfell".into(), + }, + file: "kas.yml".into(), + }), + unread_includes: vec!["https://x/y.yml".into()], + }; + let b = bson::to_bson(&pins).expect("serialize"); + assert_eq!(bson::from_bson::(b).expect("deserialize"), pins); + } +} diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index f475403..a06c010 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -4932,11 +4932,52 @@ tbody tr:last-child td { } .target-open, +.target-pins, .target-vex, .target-manual { margin-bottom: 20px; } +.target-pins-release { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 6px; + margin-bottom: 12px; + font-size: 13px; +} + +/* Wide tables scroll inside the card, never the page. */ +.target-pins-table { + display: block; + overflow-x: auto; + width: 100%; + border-collapse: collapse; + font-size: 12.5px; +} + +.target-pins-table th, +.target-pins-table td { + padding: 4px 12px 4px 0; + text-align: left; + white-space: nowrap; + border-bottom: 1px solid var(--border); +} + +.target-pins-table th { + font-family: var(--font-mono); + font-size: 11px; + font-weight: 500; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--text-tertiary); +} + +.target-pins-table code { + font-family: var(--font-mono); + color: var(--text-secondary); +} + .target-findings { list-style: none; } diff --git a/compliance-dashboard/src/components/layer_pins.rs b/compliance-dashboard/src/components/layer_pins.rs new file mode 100644 index 0000000..3b4778a --- /dev/null +++ b/compliance-dashboard/src/components/layer_pins.rs @@ -0,0 +1,147 @@ +//! On a Yocto target: the layers its kas files, `repo` manifests and git +//! submodules pin, and the Yocto release they make up with its support end. + +use dioxus::prelude::*; + +use compliance_core::models::{ + display_codename, LayerPins, PinSource, ReleaseBasis, Support, YoctoRelease, +}; + +use crate::i18n::texts::layer_pins as tx; +use crate::i18n::{use_lang, Lang}; + +/// How many characters of a commit id are shown (the whole id on hover). +const SHORT_COMMIT: usize = 12; + +/// Where a pin is declared, in words. +fn source_label(source: PinSource) -> &'static str { + match source { + PinSource::Kas => "kas", + PinSource::RepoManifest => "repo", + PinSource::GitSubmodule => "git submodule", + } +} + +/// The badge class and words of a release's support on `today`. +fn support_badge( + release: &YoctoRelease, + today: chrono::NaiveDate, + lang: Lang, +) -> (&'static str, &'static str) { + match release.support(today) { + Support::Ended => ("badge badge-high", tx::ENDED.get(lang)), + Support::EndsSoon => ("badge badge-medium", tx::ENDS_SOON.get(lang)), + Support::Supported => ("badge badge-success", tx::SUPPORTED.get(lang)), + } +} + +/// What the release was read from, in words. +fn basis_label(basis: &ReleaseBasis, lang: Lang) -> String { + match basis { + ReleaseBasis::Pin { name, branch } => { + format!("{} {name} ({branch})", tx::FROM_PIN.get(lang)) + } + ReleaseBasis::CoreLayer => tx::FROM_CORE.get(lang).to_string(), + ReleaseBasis::LayerCompat => tx::FROM_COMPAT.get(lang).to_string(), + } +} + +/// The "Layer pins" card of a Yocto target. +#[component] +pub fn LayerPinsCard(pins: LayerPins) -> Element { + let lang = use_lang()(); + let today = chrono::Utc::now().date_naive(); + rsx! { + section { class: "card target-pins", + div { class: "target-card-head", h3 { {tx::TITLE.get(lang)} } } + div { class: "target-card-body", + p { class: "target-pins-release", + strong { "{tx::RELEASE.get(lang)}: " } + match &pins.release { + Some(release) => { + let (class, words) = support_badge(release, today, lang); + let name = display_codename(&release.codename); + let lts = if release.lts { " LTS" } else { "" }; + rsx! { + "{name} {release.version}{lts} " + span { class: "{class}", "{words}" } + span { class: "target-muted", + " {tx::SUPPORT_UNTIL.get(lang)} {release.end_of_life} · {basis_label(&release.basis, lang)}, " + code { "{release.file}" } + } + } + } + None => rsx! { span { class: "target-muted", {tx::RELEASE_UNKNOWN.get(lang)} } }, + } + } + if pins.pins.is_empty() { + p { class: "target-muted", {tx::NO_PINS.get(lang)} } + } else { + table { class: "target-pins-table", + thead { + tr { + th { {tx::LAYER.get(lang)} } + th { {tx::BRANCH.get(lang)} } + th { {tx::COMMIT.get(lang)} } + th { {tx::SOURCE.get(lang)} } + } + } + tbody { + for pin in pins.pins.iter() { + tr { + td { title: pin.url.clone().unwrap_or_default(), "{pin.name}" } + td { code { {pin.branch.clone().unwrap_or_else(|| "–".into())} } } + td { + title: pin.commit.clone().unwrap_or_default(), + code { {pin.commit.as_deref().map_or_else(|| "–".into(), short_commit)} } + } + td { "{source_label(pin.source)} · " code { "{pin.file}" } } + } + } + } + } + } + if !pins.unread_includes.is_empty() { + h4 { class: "target-subhead", {tx::UNREAD_INCLUDES.get(lang)} } + ul { class: "target-facts", + for include in pins.unread_includes.iter() { + li { code { "{include}" } } + } + } + } + } + } + } +} + +/// The first [`SHORT_COMMIT`] characters of a commit id. +fn short_commit(commit: &str) -> String { + commit.chars().take(SHORT_COMMIT).collect() +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + + #[test] + fn commits_are_shortened() { + assert_eq!(short_commit("4a2d3b5c6d7e8f9a0b1c"), "4a2d3b5c6d7e"); + } + + #[test] + fn the_release_basis_reads_in_both_languages() { + let pin = ReleaseBasis::Pin { + name: "poky".into(), + branch: "dunfell".into(), + }; + assert_eq!( + basis_label(&pin, Lang::De), + "aus dem Stand von poky (dunfell)" + ); + assert_eq!( + basis_label(&pin, Lang::En), + "from the pin of poky (dunfell)" + ); + } +} diff --git a/compliance-dashboard/src/components/mod.rs b/compliance-dashboard/src/components/mod.rs index 6a9d9b6..3bd88e1 100644 --- a/compliance-dashboard/src/components/mod.rs +++ b/compliance-dashboard/src/components/mod.rs @@ -10,6 +10,7 @@ pub mod evidence_button; pub mod file_tree; pub mod help_chat; pub mod lang_toggle; +pub mod layer_pins; pub mod manual_findings; pub mod markdown; pub mod no_access; diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index ff80892..2008977 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", }, + "yocto_release" => Text { + de: "Yocto-Release (Support-Status)", + en: "Yocto release (support status)", + }, "recipe_lint_upstream" => Text { de: "Upstream-Layer (Poky, OpenEmbedded, BSP)", en: "Upstream layers (Poky, OpenEmbedded, BSP)", @@ -673,6 +677,17 @@ pub mod scans { "{subject} findings are suppressed by comments in the recipes (# nooelint) and \ are not shown." ), + (SkipCode::ReleaseUnknown, Lang::De) => { + "Das Yocto-Release ist weder aus den Layer-Ständen (kas, repo-Manifest, \ + Submodule) noch aus LAYERSERIES_COMPAT ablesbar, daher ist sein \ + Support-Zeitraum nicht geprüft." + .into() + } + (SkipCode::ReleaseUnknown, Lang::En) => { + "The Yocto release cannot be read from the layer pins (kas, repo manifest, \ + submodules) or LAYERSERIES_COMPAT, so its support period was not checked." + .into() + } (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 \ @@ -1046,6 +1061,77 @@ pub mod targets { } } +/// The layer pins of a Yocto target and its release, on the target page. +pub mod layer_pins { + use super::Text; + + pub const TITLE: Text = Text { + de: "Layer-Stände", + en: "Layer pins", + }; + pub const RELEASE: Text = Text { + de: "Yocto-Release", + en: "Yocto release", + }; + pub const RELEASE_UNKNOWN: Text = Text { + de: "Nicht erkannt: weder die Layer-Stände noch LAYERSERIES_COMPAT nennen ein bekanntes \ + Release.", + en: "Not recognised: neither the layer pins nor LAYERSERIES_COMPAT name a known release.", + }; + pub const SUPPORT_UNTIL: Text = Text { + de: "Support bis", + en: "Supported until", + }; + pub const ENDED: Text = Text { + de: "Support beendet", + en: "End of life", + }; + pub const ENDS_SOON: Text = Text { + de: "Support endet bald", + en: "End of life soon", + }; + pub const SUPPORTED: Text = Text { + de: "unterstützt", + en: "supported", + }; + pub const FROM_CORE: Text = Text { + de: "aus LAYERSERIES_COMPAT_core des OpenEmbedded-Core-Layers", + en: "from LAYERSERIES_COMPAT_core of the OpenEmbedded-Core layer", + }; + pub const FROM_COMPAT: Text = Text { + de: "aus LAYERSERIES_COMPAT Ihrer Layer (das neueste, das alle nennen)", + en: "from LAYERSERIES_COMPAT of your layers (the newest they all name)", + }; + pub const FROM_PIN: Text = Text { + de: "aus dem Stand von", + en: "from the pin of", + }; + pub const LAYER: Text = Text { + de: "Layer", + en: "Layer", + }; + pub const BRANCH: Text = Text { + de: "Branch / Tag", + en: "Branch / tag", + }; + pub const COMMIT: Text = Text { + de: "Commit", + en: "Commit", + }; + pub const SOURCE: Text = Text { + de: "Quelle", + en: "Source", + }; + pub const NO_PINS: Text = Text { + de: "Keine Layer-Stände gefunden (kas, repo-Manifest, Git-Submodule).", + en: "No layer pins found (kas, repo manifest, git submodules).", + }; + pub const UNREAD_INCLUDES: Text = Text { + de: "Nicht gelesene Includes (andere Repositories, URLs, fehlende Dateien)", + en: "Includes not read (other repositories, URLs, missing files)", + }; +} + /// Target types and artifact kinds, keyed by their API value. pub mod kinds { use super::Text; @@ -1942,6 +2028,10 @@ pub mod findings { de: "Yocto-Konfiguration", en: "Yocto configuration", }, + "yocto-release" => Text { + de: "Yocto-Release ohne Support", + en: "Yocto release out of support", + }, "gdpr-patterns" => Text { de: "Datenschutz-Muster", en: "Privacy patterns", @@ -2881,6 +2971,10 @@ pub mod compliance { crate::i18n::texts::findings::tool_name("yocto-config", Lang::En), "Yocto configuration" ); + assert_eq!( + crate::i18n::texts::findings::tool_name("yocto-release", Lang::De), + "Yocto-Release ohne Support" + ); assert_eq!( crate::i18n::texts::findings::tool_name("clippy", Lang::De), "clippy" @@ -3526,6 +3620,9 @@ mod skipped_reason_tests { "2 findings suppressed by recipe comments (# nooelint)", ) .about("2"); + let release = SkippedStage::new("yocto_release", SkipCode::ReleaseUnknown, "unknown"); + assert!(skipped_reason(&release, Lang::De).starts_with("Das Yocto-Release ist weder")); + assert!(skipped_reason(&release, Lang::En).starts_with("The Yocto release cannot")); assert_eq!( skipped_reason(&suppressed, Lang::De), "2 Befunde sind per Kommentar in den Rezepten (# nooelint) unterdrückt und werden \ diff --git a/compliance-dashboard/src/pages/target.rs b/compliance-dashboard/src/pages/target.rs index 179671a..361a2ba 100644 --- a/compliance-dashboard/src/pages/target.rs +++ b/compliance-dashboard/src/pages/target.rs @@ -10,6 +10,7 @@ use crate::app::Route; use crate::components::artifact_upload::ArtifactUpload; use crate::components::cra_bar::CraBar; use crate::components::evidence_button::EvidencePackButton; +use crate::components::layer_pins::LayerPinsCard; use crate::components::manual_findings::ManualFindingsPanel; use crate::components::no_access::use_can_write; use crate::components::projects::{ProjectChips, ProjectPicker}; @@ -126,6 +127,10 @@ pub fn TargetPage(id: String) -> Element { .and_then(|f| f.as_array()) .cloned() .unwrap_or_default(); + // A Yocto target's layer pins and release, from its last scan. + let layer_pins: Option = t + .get("layer_pins") + .and_then(|p| serde_json::from_value(p.clone()).ok()); let status_data = status.read().clone().flatten(); let counts: Option = status_data .as_ref() @@ -275,6 +280,10 @@ pub fn TargetPage(id: String) -> Element { } } + if let Some(pins) = layer_pins { + LayerPinsCard { pins } + } + section { class: "card target-vex", div { class: "target-card-head", h3 { {crate::i18n::texts::vex::TITLE.get(lang)} } } div { class: "target-card-body", VexPanel { target_id: id.clone() } } diff --git a/control-map/data/cra_control_map.json b/control-map/data/cra_control_map.json index f75aee1..5867cba 100644 --- a/control-map/data/cra_control_map.json +++ b/control-map/data/cra_control_map.json @@ -1212,6 +1212,19 @@ "android-min-sdk-end-of-support" ], "check": "The platform a product is built for, and the tools it is built with, must still receive security updates; an Android API level, a Unity editor release, an iOS deployment target or an Android minimum API level out of support, or a Swift version no supported Xcode builds, violates it." + }, + { + "tool": "yocto-release", + "scan_type": "sbom", + "languages": [ + "bitbake" + ], + "cwe": [], + "rules": [ + "yocto-release-eol", + "yocto-release-eol-soon" + ], + "check": "The Yocto release an embedded Linux image is built from must still receive security updates over the product's support period (CRA Annex I Part I (2)(c) and Part II); layers pinned to a release past, or within six months of, the Yocto Project's end of support violate it." } ], "note": null, diff --git a/control-map/src/lib.rs b/control-map/src/lib.rs index 962c9b6..cb25df3 100644 --- a/control-map/src/lib.rs +++ b/control-map/src/lib.rs @@ -294,6 +294,14 @@ mod tests { controls("dotnet-lifecycle", "dotnet-framework-end-of-support"), ["cra-ai-22"] ); + assert_eq!( + controls("yocto-release", "yocto-release-eol"), + ["cra-ai-22"] + ); + assert_eq!( + controls("yocto-release", "yocto-release-eol-soon"), + ["cra-ai-22"] + ); } #[test] diff --git a/docs/guide/yocto.md b/docs/guide/yocto.md index 2d16c3f..31256d4 100644 --- a/docs/guide/yocto.md +++ b/docs/guide/yocto.md @@ -37,6 +37,7 @@ searched. | SBOM from lockfiles (Syft) | runs, but a layer has no lockfiles, so it is usually empty | | 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 | +| Layer pins and Yocto release | runs: kas files, `repo` manifests and submodules, and a finding when the release is end of life; see [Layer pins and the Yocto release](#layer-pins-and-the-yocto-release) | | Recipe inventory | runs: SBOM components and NVD CVEs from the recipes, `CVE_STATUS` and `CVE:` patches as VEX; see [Recipe inventory](#recipe-inventory) | | Image SBOM / CVE | needs build artefacts (SPDX / manifest), planned (tier 2) | | DAST | opt-in, with an http(s) address of the running device | @@ -101,6 +102,84 @@ layer tree, recipe lint checks it (network access in build tasks, plain-http fetches), so the CRA status assesses it there; for every other target it stays "not code-checkable". +## Layer pins and the Yocto release + +The scan reads which layer repositories the build fetches, and at which +branch and commit, without fetching any of them. The pins are stored on the +target and shown on its page under **Layer-Stände** (*Layer pins*), with the +release they make up. + +| Read from | What | +| --- | --- | +| kas project files (`kas*.yml` anywhere, any YAML file in a `kas/` directory) | every repository under `repos:` with a `url`: `branch`, `tag` or the older `refspec`, and `commit`; `defaults.repos.branch`; a lock file beside it (`kas.lock.yml`, `overrides.repos..commit`). A repository without `url` is the one the kas file is in and is not a pin. | +| kas includes (`header.includes`) | local files, relative to the including file or to the repository root, merged in before the including file's own settings, as kas does; an include cycle ends at the file already being read. An include from another repository (`repo:` / `file:`) or a URL is never fetched: it is listed under "Nicht gelesene Includes", as is a local include that is missing or leaves the repository. | +| `repo` manifests (an XML file whose `` has `` or `` elements) | each ``: URL from its remote's `fetch` and its name, revision from the project, else the remote, else ``; a commit as revision takes the branch from `upstream` / `dest-branch`. ``, `` and `` are followed (locally). A manifest with a DTD is not read. | +| `.gitmodules` | each submodule's URL and `branch`; for a git repository the commit its HEAD records for the submodule (the gitlink). An uploaded archive has no git history, so its submodules have no commit. A submodule's own kas files and manifests are not read as the tree's. | + +Files over 1 MiB, symbolic links and YAML that expands past 100,000 nodes +through aliases are not read; kas files and manifests are looked for up to four +directories deep, not in `build/`, `downloads/` or vendor directories. + +**The release** is read from the first of: + +1. the branch or tag of the Poky, OpenEmbedded-Core or meta-openembedded pin + (in that order): a codename (`scarthgap`, `scarthgap-5.0.3`, + `kirkstone-4.0.15`, `dunfell-23.0.10`) or a `yocto-` tag + (`yocto-5.0.3`); `master` names none; +2. `LAYERSERIES_COMPAT_core` of an OpenEmbedded-Core layer in the tree; +3. `LAYERSERIES_COMPAT_*` of your layers: the **newest** release all of them + declare. A layer compatible with `kirkstone scarthgap` may be built on + Scarthgap, so it is not reported as Kirkstone (the recipe lint reads the + oldest one instead, for the syntax the recipes must accept). + +The pins win over `LAYERSERIES_COMPAT`: they say what the build fetches, the +layer what it claims to support. When none of the three names a release in the +table below, there is no finding and the run lists **Yocto-Release +(Support-Status)** under **Nicht ausgeführt**. + +**Support status.** On the scan's date: + +| Rule (`yocto-release`) | When | Severity | CRA | Control | +| --- | --- | --- | --- | --- | +| `yocto-release-eol` | the release's end of life has passed | high | Annex I Part I (2)(c) security updates, Part II (2) remediation without delay | CRA-AI-22 | +| `yocto-release-eol-soon` | its end of life is within six months | medium | the same | CRA-AI-22 | + +The finding names the release, its end of life, where it was read from (the +kas file, manifest or `layer.conf`) and the source of the date, and recommends +the current long term support release (the newest LTS supported for more than +six months on the scan's date). It is CWE-1104 (unmaintained third-party +components). + +**The release table** (in `compliance-agent/src/pipeline/yocto_pins/release.rs`) +is taken from the [Yocto Project releases wiki](https://wiki.yoctoproject.org/wiki/Releases) +(page last updated 2026-09-10), checked on **2026-10-09**. The wiki gives +months; the exact days are [endoflife.date's](https://endoflife.date/yocto), +which match the wiki except Walnascar (wiki: "EOL since November 2025"). For +Thud and older the end of life is the month of the last point release. + +| Codename | Version | LTS | Released | End of life | +| --- | --- | --- | --- | --- | +| Jethro … Thud | 2.0 – 2.6 | no | 2015 – 2018 | 2017 – 2019 | +| Warrior | 2.7 | no | 2019-05-01 | 2020-06-01 | +| Zeus | 3.0 | no | 2019-10-22 | 2020-08-01 | +| Dunfell | 3.1 | yes | 2020-04-21 | 2024-04-30 | +| Gatesgarth | 3.2 | no | 2020-11-03 | 2021-05-01 | +| Hardknott | 3.3 | no | 2021-04-19 | 2022-04-20 | +| Honister | 3.4 | no | 2021-10-25 | 2022-05-01 | +| Kirkstone | 4.0 | yes | 2022-04-25 | 2026-04-27 | +| Langdale | 4.1 | no | 2022-10-23 | 2023-05-27 | +| Mickledore | 4.2 | no | 2023-05-03 | 2023-11-05 | +| Nanbield | 4.3 | no | 2023-11-09 | 2024-06-09 | +| Scarthgap | 5.0 | yes | 2024-04-29 | 2028-04-30 | +| Styhead | 5.1 | no | 2024-10-16 | 2025-05-16 | +| Walnascar | 5.2 | no | 2025-05-07 | 2025-12-07 | +| Whinlatter | 5.3 | no | 2025-12-15 | 2026-06-15 | +| Wrynose | 6.0 | yes | 2026-05-13 | 2030-04-30 | + +Blacksail (6.1, due October 2026) is not in the table until it is released; a +layer on it reads as an unknown release. The table is updated by hand with +each Yocto release. + ## Recipe inventory A tree detected as a Yocto layer tree (see [Detection](#detection)), and any diff --git a/fixtures/nightly/baselines/fw-yocto-layer.json b/fixtures/nightly/baselines/fw-yocto-layer.json index f8755ea..1d95ad8 100644 --- a/fixtures/nightly/baselines/fw-yocto-layer.json +++ b/fixtures/nightly/baselines/fw-yocto-layer.json @@ -26,6 +26,13 @@ "CVE-2022-0367", "CVE-2022-28391", "CVE-2022-30065", - "CVE-2022-48174" - ] + "CVE-2022-48174", + "yocto-release-eol" + ], + "layer_pins": [ + "git_submodule meta-security dunfell@-", + "kas meta-openembedded dunfell@-", + "kas poky dunfell@0b1f2c3d4e5f60718293a4b5c6d7e8f901234567" + ], + "yocto_release": "dunfell" } diff --git a/fixtures/nightly/firmware/README.md b/fixtures/nightly/firmware/README.md index fd7c95b..41d5728 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) yet; `kas.yml` (with `kas/meta-openembedded.yml` and a remote include) and `.gitmodules` pin the layers to Dunfell, so `yocto-release-eol` reports the release as end of life | `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/.gitmodules b/fixtures/nightly/firmware/yocto-layer/.gitmodules new file mode 100644 index 0000000..d5afd72 --- /dev/null +++ b/fixtures/nightly/firmware/yocto-layer/.gitmodules @@ -0,0 +1,4 @@ +[submodule "meta-security"] + path = layers/meta-security + url = https://git.yoctoproject.org/meta-security + branch = dunfell diff --git a/fixtures/nightly/firmware/yocto-layer/kas.yml b/fixtures/nightly/firmware/yocto-layer/kas.yml new file mode 100644 index 0000000..a4caecc --- /dev/null +++ b/fixtures/nightly/firmware/yocto-layer/kas.yml @@ -0,0 +1,25 @@ +# Nightly fixture: the kas project of the layer. Poky is pinned to Dunfell, +# whose support ended on 2024-04-30, so the release check reports it as end of +# life. The commit is illustrative; nothing is fetched. +header: + version: 14 + includes: + - kas/meta-openembedded.yml + # Another repository's file: named as not read, never fetched. + - repo: meta-vendor + file: kas/vendor.yml + +machine: qemuarm64 +distro: pump-distro + +repos: + # This layer (no url: the repository the kas file is in). + pruefwerk-fixture: + + poky: + url: https://git.yoctoproject.org/poky + branch: dunfell + commit: 0b1f2c3d4e5f60718293a4b5c6d7e8f901234567 + layers: + meta: + meta-poky: diff --git a/fixtures/nightly/firmware/yocto-layer/kas/meta-openembedded.yml b/fixtures/nightly/firmware/yocto-layer/kas/meta-openembedded.yml new file mode 100644 index 0000000..2025466 --- /dev/null +++ b/fixtures/nightly/firmware/yocto-layer/kas/meta-openembedded.yml @@ -0,0 +1,11 @@ +# Included by kas.yml: meta-openembedded on the same release. +header: + version: 14 + +repos: + meta-openembedded: + url: https://git.openembedded.org/meta-openembedded + branch: dunfell + layers: + meta-oe: + meta-networking: diff --git a/fixtures/nightly/targets.json b/fixtures/nightly/targets.json index a8b98d6..2fd4a66 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 firmware SBOM (a build) is recorded as skipped with its reason. A kas file (with a local and a remote include) and a .gitmodules pin Poky and meta-openembedded to Dunfell, so the release check reports Yocto Dunfell as end of life.", "artifacts": [ { "kind": "source_archive",