From f01ccdf89363d1b6442abb8092f6a15336b5f027 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Wed, 4 Nov 2026 09:29:46 +0100 Subject: [PATCH] feat(scan): per-target excluded paths, left out of the whole scan MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A target's settings can now name directories and files to leave out of every scan stage (scan_config.exclude_paths), on top of the test data the scan detects itself (#820): no code findings, no SBOM components, no CVEs. - Paths are relative to the tree, /-separated, without wildcards; a directory is left out with everything in it. normalise_exclude_paths (compliance-core) trims, normalises and refuses absolute paths, .., .git, wildcards, over-long paths and more than 50 entries. The API applies it while reading the PATCH body, so an invalid path is refused with 422 and a message naming it; the dashboard editor uses the same function and shows the reason in German or English. - The scan prunes the configured paths first, then detects test data in what is left. prune now removes files as well as directories, and never a path that passes a symbolic link (src/link/x with src/link pointing elsewhere is left alone). - The run notes what was left out (SkipCode::ExcludedPaths, stage excluded_paths), including configured paths not found in the tree. - Findings an earlier scan stored there close as NowExcluded, with their own issue comment. - Dashboard: "Von der Prüfung ausgenommen" in the target editor, one path per line. Docs: guide/repositories and guide/scanning. Co-Authored-By: Claude Opus 5.5 --- .../src/api/handlers/target_input.rs | 51 ++++- .../src/pipeline/finding_store.rs | 27 ++- compliance-agent/src/pipeline/issue_sync.rs | 4 + compliance-agent/src/pipeline/orchestrator.rs | 113 ++++++++--- compliance-agent/src/pipeline/repo_view.rs | 4 + compliance-agent/src/pipeline/test_data.rs | 106 +++++++--- compliance-agent/tests/resolve_findings.rs | 17 +- compliance-core/src/models/exclude_paths.rs | 186 ++++++++++++++++++ compliance-core/src/models/finding.rs | 3 + compliance-core/src/models/mod.rs | 4 + compliance-core/src/models/onboarding.rs | 4 + compliance-core/src/models/scan.rs | 9 +- compliance-dashboard/src/i18n/texts.rs | 60 ++++++ .../src/infrastructure/onboarding.rs | 11 +- compliance-dashboard/src/pages/target.rs | 43 +++- docs/guide/repositories.md | 23 ++- docs/guide/scanning.md | 5 +- 17 files changed, 596 insertions(+), 74 deletions(-) create mode 100644 compliance-core/src/models/exclude_paths.rs diff --git a/compliance-agent/src/api/handlers/target_input.rs b/compliance-agent/src/api/handlers/target_input.rs index 572ef0c..b5085b4 100644 --- a/compliance-agent/src/api/handlers/target_input.rs +++ b/compliance-agent/src/api/handlers/target_input.rs @@ -7,11 +7,11 @@ //! its token and its uploaded file, and a scan config keeps every field the //! request does not name (#304). -use serde::Deserialize; +use serde::{Deserialize, Deserializer}; use compliance_core::models::{ - Artifact, ArtifactAuth, ArtifactKind, Environment, IssueTrackerConfig, PentestConfig, - PentestStrategy, PlcFormat, ScanType, TargetScanConfig, + normalise_exclude_paths, Artifact, ArtifactAuth, ArtifactKind, Environment, IssueTrackerConfig, + PentestConfig, PentestStrategy, PlcFormat, ScanType, TargetScanConfig, }; use crate::secrets::{SecretBox, SecretError}; @@ -138,6 +138,22 @@ pub struct ScanConfigUpdate { pub strategy: Option, pub pentest: Option, pub issue_tracker: Option, + /// Paths left out of every scan; replaces the stored list. Normalised + /// while the request is read, so an invalid path is refused with its + /// reason (axum answers 422 with the message). + #[serde(default, deserialize_with = "exclude_paths")] + pub exclude_paths: Option>, +} + +/// `exclude_paths` as [`normalise_exclude_paths`] stores them; an invalid +/// entry fails the request with the reason naming it. +fn exclude_paths<'de, D>(deserializer: D) -> Result>, D::Error> +where + D: Deserializer<'de>, +{ + Option::>::deserialize(deserializer)? + .map(|paths| normalise_exclude_paths(&paths).map_err(serde::de::Error::custom)) + .transpose() } impl ScanConfigUpdate { @@ -169,6 +185,9 @@ impl ScanConfigUpdate { if let Some(v) = self.strategy { merged.strategy = Some(v); } + if let Some(v) = self.exclude_paths { + merged.exclude_paths = v; + } if let Some(mut tracker) = self.issue_tracker { let kept = stored.issue_tracker.as_ref().and_then(|t| t.token.as_ref()); secrets.take_update(&mut tracker.token, kept)?; @@ -275,6 +294,32 @@ mod tests { assert!(cleared.auth.is_none()); } + #[test] + fn excluded_paths_are_normalised_or_refused_with_the_reason() { + let update: ScanConfigUpdate = + serde_json::from_str(r#"{"exclude_paths": ["./docs/samples/", "", "tools\\old"]}"#) + .unwrap(); + assert_eq!( + update.exclude_paths.as_deref(), + Some(&["docs/samples".to_string(), "tools/old".to_string()][..]) + ); + let stored = TargetScanConfig { + exclude_paths: vec!["old".into()], + ..Default::default() + }; + let merged = update.apply(&secrets(), &stored).unwrap(); + assert_eq!(merged.exclude_paths, ["docs/samples", "tools/old"]); + + // Left out: the stored list stays. + let untouched: ScanConfigUpdate = serde_json::from_str("{}").unwrap(); + let kept = untouched.apply(&secrets(), &stored).unwrap(); + assert_eq!(kept.exclude_paths, ["old"]); + + let err = serde_json::from_str::(r#"{"exclude_paths": ["../etc"]}"#) + .unwrap_err(); + assert!(err.to_string().contains("../etc"), "{err}"); + } + #[test] fn enabling_a_scan_keeps_the_tracker_and_its_token() { let s = secrets(); diff --git a/compliance-agent/src/pipeline/finding_store.rs b/compliance-agent/src/pipeline/finding_store.rs index 73ec9d4..d8e09d0 100644 --- a/compliance-agent/src/pipeline/finding_store.rs +++ b/compliance-agent/src/pipeline/finding_store.rs @@ -49,6 +49,9 @@ pub struct RunFindings { /// ([`crate::pipeline::test_data`]): a finding stored in one is closed as /// test data, not as fixed. test_data: Vec, + /// The paths the target's settings left out of the scanned tree: a + /// finding stored in one is closed as excluded, not as fixed. + excluded: Vec, } /// One place a group lists: scanner, rule, file, line. @@ -80,9 +83,17 @@ impl RunFindings { variants: AppVariants::default(), tree: None, test_data: Vec::new(), + excluded: Vec::new(), } } + /// Name the paths the target's settings left out of the tree, so the + /// findings an earlier scan stored there close as excluded. + pub fn with_excluded(mut self, paths: Vec) -> Self { + self.excluded = paths; + self + } + /// Name the test-data directories the scan left out of the tree, so the /// findings an earlier scan stored there close as test data. pub fn with_test_data(mut self, dirs: Vec) -> Self { @@ -709,8 +720,8 @@ impl RunFindings { .await? .try_collect() .await?; - let (mut fixed, mut vendored, mut test_data, mut grouped) = - (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let (mut fixed, mut vendored, mut test_data, mut excluded, mut grouped) = + (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new()); for row in &candidates { let (Ok(id), Ok(fingerprint)) = (row.get_object_id("_id"), row.get_str("fingerprint")) else { @@ -724,6 +735,8 @@ impl RunFindings { // The same membership test as for the vendor directories. let in_test_data = file.is_some_and(|f| crate::pipeline::vendor::in_vendor_dir(f, &self.test_data)); + let in_excluded = + file.is_some_and(|f| crate::pipeline::vendor::in_vendor_dir(f, &self.excluded)); let completed = row .get_str("scanner") .is_ok_and(|scanner| self.completed.contains(scanner)); @@ -731,6 +744,8 @@ impl RunFindings { grouped.push(id); } else if !completed { continue; + } else if in_excluded { + excluded.push(id); } else if in_test_data { test_data.push(id); } else if in_vendor { @@ -743,19 +758,23 @@ impl RunFindings { (&fixed, ScanChangeKind::NoLongerFound), (&vendored, ScanChangeKind::NowVendorCode), (&test_data, ScanChangeKind::NowTestData), + (&excluded, ScanChangeKind::NowExcluded), (&grouped, ScanChangeKind::Grouped), ] { self.set_status(db, ids, &UNDECIDED, FindingStatus::Resolved, kind) .await?; } - let closed = u32::try_from(fixed.len() + vendored.len() + test_data.len() + grouped.len()) - .unwrap_or(u32::MAX); + let closed = u32::try_from( + fixed.len() + vendored.len() + test_data.len() + excluded.len() + grouped.len(), + ) + .unwrap_or(u32::MAX); if closed > 0 { tracing::info!( scan_run_id = %self.scan_run_id, fixed = fixed.len(), vendored = vendored.len(), test_data = test_data.len(), + excluded = excluded.len(), grouped = grouped.len(), "resolved findings the scan no longer reports" ); diff --git a/compliance-agent/src/pipeline/issue_sync.rs b/compliance-agent/src/pipeline/issue_sync.rs index 946adc7..c6f2b60 100644 --- a/compliance-agent/src/pipeline/issue_sync.rs +++ b/compliance-agent/src/pipeline/issue_sync.rs @@ -239,6 +239,10 @@ fn comment(status: &FindingStatus, change: Option<&StatusChange>) -> String { "Die Datei liegt in Testdaten (z. B. fixtures/ oder testdata/), die von der Prüfung ausgenommen sind.", "The file lies in test data (such as fixtures/ or testdata/), which is left out of the scan.", ), + (FindingStatus::Resolved, Some(ScanChangeKind::NowExcluded)) => ( + "Die Datei liegt in einem Pfad, den die Einstellungen des Prüfobjekts von der Prüfung ausnehmen.", + "The file lies in a path the target's settings leave out of the scan.", + ), (FindingStatus::Resolved, _) => ( "In Prüfwerk als behoben markiert.", "Marked resolved in Prüfwerk.", diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 9fd05f2..56b40c2 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -37,6 +37,16 @@ pub struct GraphContext { pub impacts: Vec, } +/// What a scan left out of its working copy before the first stage, as +/// paths relative to the tree. +#[derive(Debug, Default)] +struct LeftOut { + /// Removed because the target's settings exclude them. + excluded: Vec, + /// Detected test data ([`crate::pipeline::test_data`]). + test_data: Vec, +} + pub struct PipelineOrchestrator { pub(super) config: AgentConfig, /// The tenant this run belongs to. Carried explicitly because the on-disk @@ -225,10 +235,13 @@ impl PipelineOrchestrator { let repo_id = repo.id.as_ref().map(|id| id.to_hex()).unwrap_or_default(); let repo_path = tree.to_path_buf(); - // Test data (`fixtures/`, `testdata/`) is not what the product ships: - // it leaves the working copy before any stage reads it, so no stage - // reports it — no code findings, no SBOM components, no CVEs. - let test_data = self.prune_test_data(&repo_path, scan_run_id).await; + // What the target's settings exclude, and test data (`fixtures/`, + // `testdata/`), which is not what the product ships, leave the working + // copy before any stage reads it, so no stage reports them — no code + // findings, no SBOM components, no CVEs. + let left_out = self + .prune_left_out(&repo_path, &repo.exclude_paths, scan_run_id) + .await; let mut all_findings: Vec = Vec::new(); // Each scanner stage saves its new findings at once, so they show while @@ -243,7 +256,8 @@ impl PipelineOrchestrator { let mut run_findings = crate::pipeline::finding_store::RunFindings::new(scan_run_id) .with_variants(variants) .with_tree(repo_path.clone()) - .with_test_data(test_data); + .with_excluded(left_out.excluded) + .with_test_data(left_out.test_data); // Stage 1: SAST. Vendor SDK code (HAL, CMSIS, third-party middleware) is // not the customer's to fix, so both analysers skip it and the run says @@ -2281,44 +2295,83 @@ impl PipelineOrchestrator { .await; } - /// Take the test data out of the working copy at `tree` - /// ([`crate::pipeline::test_data`]) and note on the run what was left - /// out. Only a working copy under the clone or artifact directories is - /// touched; the git fetch and the archive unpack restore it next scan. + /// Take what the target's settings exclude (`excluded`, relative paths) + /// and the test data ([`crate::pipeline::test_data`]) out of the working + /// copy at `tree`, and note on the run what was left out. Only a working + /// copy under the clone or artifact directories is touched; the git + /// fetch and the archive unpack restore it next scan. /// /// # Returns /// - /// The directories removed, relative to `tree`; empty when there were - /// none or the tree is not the agent's own. - async fn prune_test_data(&self, tree: &std::path::Path, scan_run_id: &str) -> Vec { + /// The paths removed, relative to `tree`; empty when there were none or + /// the tree is not the agent's own. + async fn prune_left_out( + &self, + tree: &std::path::Path, + excluded: &[String], + scan_run_id: &str, + ) -> LeftOut { let root = tree.to_path_buf(); + let configured = excluded.to_vec(); let clones = std::path::PathBuf::from(&self.config.git_clone_base_path); let artifacts = std::path::PathBuf::from(&self.config.artifact_store_base_path); let pruned = tokio::task::spawn_blocking(move || { - let dirs = crate::pipeline::test_data::test_data_dirs(&root); - if dirs.is_empty() { - return Ok(dirs); - } - crate::pipeline::test_data::prune( - &root, - &dirs, - &[clones.as_path(), artifacts.as_path()], - ) + use crate::pipeline::test_data::{prune, test_data_dirs}; + let owned = [clones.as_path(), artifacts.as_path()]; + // Nothing to remove needs no ownership check (and no warning for + // a tree outside the agent's directories). + let prune_some = |paths: &[String]| { + if paths.is_empty() { + Ok(Vec::new()) + } else { + prune(&root, paths, &owned) + } + }; + // The configured paths first: test data inside them is gone with + // them and not listed twice. + let excluded = prune_some(&configured)?; + let missing: Vec = configured + .into_iter() + .filter(|p| !excluded.contains(p)) + .collect(); + let test_data = prune_some(&test_data_dirs(&root))?; + Ok::<_, crate::pipeline::test_data::PruneError>(( + LeftOut { + excluded, + test_data, + }, + missing, + )) }) .await; - let removed = match pruned { - Ok(Ok(removed)) => removed, + let (left_out, missing) = match pruned { + Ok(Ok(done)) => done, Ok(Err(e)) => { - tracing::warn!(scan_run_id, error = %e, "test data not taken out of the scan"); - return Vec::new(); + tracing::warn!(scan_run_id, error = %e, "nothing taken out of the scan"); + return LeftOut::default(); } Err(e) => { - tracing::warn!(scan_run_id, error = %e, "test-data walk failed"); - return Vec::new(); + tracing::warn!(scan_run_id, error = %e, "left-out walk failed"); + return LeftOut::default(); } }; - if !removed.is_empty() { - let list = removed.join(", "); + if !left_out.excluded.is_empty() || !missing.is_empty() { + let list = left_out.excluded.join(", "); + let mut reason = format!( + "excluded in the target's settings, left out of the whole scan (code findings, \ + SBOM, CVE match): {list}" + ); + if !missing.is_empty() { + reason.push_str(&format!("; not in the tree: {}", missing.join(", "))); + } + self.skip_stage( + scan_run_id, + SkippedStage::new("excluded_paths", SkipCode::ExcludedPaths, reason).about(list), + ) + .await; + } + if !left_out.test_data.is_empty() { + let list = left_out.test_data.join(", "); self.skip_stage( scan_run_id, SkippedStage::new( @@ -2333,7 +2386,7 @@ impl PipelineOrchestrator { ) .await; } - removed + left_out } /// The recipe lint of a tree whose `languages` include BitBake, outside diff --git a/compliance-agent/src/pipeline/repo_view.rs b/compliance-agent/src/pipeline/repo_view.rs index 82477da..cc4594a 100644 --- a/compliance-agent/src/pipeline/repo_view.rs +++ b/compliance-agent/src/pipeline/repo_view.rs @@ -49,6 +49,9 @@ pub struct RepoView { /// was classified as one, or the target is a Yocto target. Set by the /// caller after classification; `false` from [`Self::from_target`]. pub yocto_layers: bool, + /// Directories and files the target's settings leave out of every scan + /// stage (`scan_config.exclude_paths`). + pub exclude_paths: Vec, } impl RepoView { @@ -79,6 +82,7 @@ impl RepoView { managed: target.source_repo.is_some(), uploads_allow_skip: crate::pipeline::change::uploads_allow_git_skip(target), yocto_layers: false, + exclude_paths: target.scan_config.exclude_paths.clone(), }; if let Some(git) = &code.git { view.default_branch = git.default_branch.clone(); diff --git a/compliance-agent/src/pipeline/test_data.rs b/compliance-agent/src/pipeline/test_data.rs index fb87472..ad479c5 100644 --- a/compliance-agent/src/pipeline/test_data.rs +++ b/compliance-agent/src/pipeline/test_data.rs @@ -73,23 +73,26 @@ pub fn test_data_dirs(root: &Path) -> Vec { found } -/// Remove the `dirs` ([`test_data_dirs`]) from the working copy at `root`. +/// Remove the `paths` (the [`test_data_dirs`], or the directories and files +/// a target's settings exclude) from the working copy at `root`. /// /// Only a working copy the agent made may lose files: `root` must lie under /// one of `owned_bases` (the clone base and the artifact store). Anything /// else is refused, so the call can never delete a directory it was pointed -/// at by mistake. +/// at by mistake. A path is only removed when it lies inside `root` without +/// passing a symbolic link: `src/link/x` with `src/link` pointing elsewhere +/// is left alone, and so is a link itself. /// /// # Arguments /// /// * `root` - the scan's working copy -/// * `dirs` - directories relative to `root`, `/`-separated +/// * `paths` - directories or files relative to `root`, `/`-separated /// * `owned_bases` - the directories the agent's working copies live under /// /// # Returns /// -/// The directories that were removed; one that could not be removed is -/// logged and left out. +/// The paths that were removed; one that is not in the tree is left out, and +/// one that could not be removed is logged and left out. /// /// # Errors /// @@ -97,7 +100,7 @@ pub fn test_data_dirs(root: &Path) -> Vec { /// nothing is removed then. pub fn prune( root: &Path, - dirs: &[String], + paths: &[String], owned_bases: &[&Path], ) -> Result, PruneError> { let owned = owned_bases @@ -106,34 +109,52 @@ pub fn prune( if !owned { return Err(PruneError::NotOwned); } - let mut removed = Vec::with_capacity(dirs.len()); - for dir in dirs { - // `dirs` comes from a walk of `root`; a `..` or an absolute path can - // only be a bug, and must not reach `remove_dir_all`. - let rel = Path::new(dir); - if rel.is_absolute() - || rel - .components() - .any(|c| !matches!(c, std::path::Component::Normal(_))) - { - tracing::warn!(dir = %dir, "test-data directory outside the tree; not removed"); + let mut removed = Vec::with_capacity(paths.len()); + for rel in paths { + let Some(path) = inside_without_links(root, rel) else { continue; - } - let path = root.join(rel); - // Never a link: removing it would be harmless, but a link is not what - // the walk reported. - let is_dir = std::fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_dir()); - if !is_dir { + }; + let Ok(meta) = std::fs::symlink_metadata(&path) else { continue; - } - match std::fs::remove_dir_all(&path) { - Ok(()) => removed.push(dir.clone()), - Err(e) => tracing::warn!(dir = %dir, error = %e, "test-data directory not removed"), + }; + let outcome = if meta.is_dir() { + std::fs::remove_dir_all(&path) + } else if meta.is_file() { + std::fs::remove_file(&path) + } else { + continue; + }; + match outcome { + Ok(()) => removed.push(rel.clone()), + Err(e) => tracing::warn!(path = %rel, error = %e, "left-out path not removed"), } } Ok(removed) } +/// `root` joined with `rel` when every component of `rel` is a plain name +/// and none of the directories on the way is a symbolic link; `None` +/// otherwise (also when a part does not exist). +fn inside_without_links(root: &Path, rel: &str) -> Option { + let rel_path = Path::new(rel); + if rel_path.is_absolute() { + return None; + } + let mut path = root.to_path_buf(); + for component in rel_path.components() { + let std::path::Component::Normal(name) = component else { + tracing::warn!(path = %rel, "left-out path outside the tree; not removed"); + return None; + }; + path.push(name); + let meta = std::fs::symlink_metadata(&path).ok()?; + if meta.file_type().is_symlink() { + return None; + } + } + (path != root).then_some(path) +} + /// Why [`prune`] removed nothing. #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] pub enum PruneError { @@ -253,6 +274,37 @@ mod tests { assert!(root.join("fixtures").is_dir()); } + #[test] + fn a_configured_file_or_directory_is_removed_and_a_missing_one_skipped() { + let (base, root) = tree(); + let removed = prune( + &root, + &[ + "src/main.rs".to_string(), + "examples".to_string(), + "not/there".to_string(), + ], + &[base.path()], + ) + .unwrap(); + assert_eq!(removed, ["src/main.rs", "examples"]); + assert!(!root.join("src/main.rs").exists()); + assert!(root.join("src/fixtures.rs").is_file()); + assert!(!root.join("examples").exists()); + } + + #[cfg(unix)] + #[test] + fn a_path_through_a_link_is_never_followed() { + let (base, root) = tree(); + let outside = base.path().join("outside"); + write(&outside, "keep/me.txt"); + std::os::unix::fs::symlink(&outside, root.join("src/link")).unwrap(); + let removed = prune(&root, &["src/link/keep".to_string()], &[base.path()]).unwrap(); + assert!(removed.is_empty()); + assert!(outside.join("keep/me.txt").is_file()); + } + #[test] fn a_path_outside_the_tree_is_never_removed() { let (base, root) = tree(); diff --git a/compliance-agent/tests/resolve_findings.rs b/compliance-agent/tests/resolve_findings.rs index 9bafcc8..0babedc 100644 --- a/compliance-agent/tests/resolve_findings.rs +++ b/compliance-agent/tests/resolve_findings.rs @@ -70,6 +70,7 @@ async fn a_scan_closes_what_it_no_longer_finds_and_reopens_what_returns() { finding("fp-fixed", "semgrep", "src/b.c"), finding("fp-vendor", "semgrep", "Drivers/STM32F4xx_HAL_Driver/x.c"), finding("fp-test-data", "semgrep", "fixtures/dotnet/Program.cs"), + finding("fp-excluded", "semgrep", "docs/samples/app.py"), finding("fp-lint", "clippy", "src/lib.rs"), decided, other_target, @@ -82,16 +83,18 @@ async fn a_scan_closes_what_it_no_longer_finds_and_reopens_what_returns() { assert_eq!(idle.resolve_missing(&db, TARGET, &[]).await.unwrap(), 0); // Act: semgrep completes and reports only fp-kept. - let mut run = RunFindings::new("run-2").with_test_data(vec!["fixtures".to_string()]); + let mut run = RunFindings::new("run-2") + .with_test_data(vec!["fixtures".to_string()]) + .with_excluded(vec!["docs/samples".to_string()]); run.completed("semgrep"); let mut seen = vec![finding("fp-kept", "semgrep", "src/a.c")]; run.write_back(&db, &mut seen).await.unwrap(); let vendor = vec!["Drivers".to_string()]; let closed = run.resolve_missing(&db, TARGET, &vendor).await.unwrap(); - // Assert: fixed, vendored and test data closed, each with its reason; - // the rest kept. - assert_eq!(closed, 3); + // Assert: fixed, vendored, test data and excluded closed, each with its + // reason; the rest kept. + assert_eq!(closed, 4); let fixed = row(&db, "fp-fixed").await; assert_eq!(fixed.status, FindingStatus::Resolved); assert_eq!( @@ -110,6 +113,12 @@ async fn a_scan_closes_what_it_no_longer_finds_and_reopens_what_returns() { last_scan_change(&test_data), Some(ScanChangeKind::NowTestData) ); + let excluded = row(&db, "fp-excluded").await; + assert_eq!(excluded.status, FindingStatus::Resolved); + assert_eq!( + last_scan_change(&excluded), + Some(ScanChangeKind::NowExcluded) + ); assert_eq!(row(&db, "fp-kept").await.status, FindingStatus::Open); assert_eq!( row(&db, "fp-false-positive").await.status, diff --git a/compliance-core/src/models/exclude_paths.rs b/compliance-core/src/models/exclude_paths.rs new file mode 100644 index 0000000..d92f041 --- /dev/null +++ b/compliance-core/src/models/exclude_paths.rs @@ -0,0 +1,186 @@ +//! Paths a target's owner leaves out of its scans (`scan_config.exclude_paths`). +//! +//! Each entry names a directory or a file relative to the root of the scanned +//! tree, such as `docs/samples` or `tools/legacy.py`. Everything under a +//! directory is left out of every stage: code findings, SBOM and CVE match. +//! There are no wildcards: a path is a prefix that ends at a `/`, the same +//! rule as for vendor code and test data. The scan applies them on top of +//! the test data it detects itself (`fixtures/`, `testdata/`). + +/// How many paths one target may exclude. +pub const MAX_EXCLUDE_PATHS: usize = 50; + +/// How long one excluded path may be, in bytes. +pub const MAX_EXCLUDE_PATH_LEN: usize = 256; + +/// Why an excluded path was refused. Every variant names the entry as given. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum ExcludePathError { + /// More than [`MAX_EXCLUDE_PATHS`] entries. + #[error("at most {MAX_EXCLUDE_PATHS} paths can be excluded")] + TooMany, + /// Longer than [`MAX_EXCLUDE_PATH_LEN`]. + #[error("{0}: longer than {MAX_EXCLUDE_PATH_LEN} characters")] + TooLong(String), + /// Starts at the file system root (`/src`, `C:\src`). + #[error("{0}: give the path relative to the repository root, without a leading /")] + Absolute(String), + /// Names `.`, `..` or `.git` as a part, or is the root itself. + #[error("{0}: must name a directory or file inside the repository")] + OutsideTree(String), + /// Holds a wildcard (`*`, `?`, `[`). + #[error("{0}: wildcards are not supported; name the directory or file")] + Wildcard(String), +} + +/// The excluded paths as stored: trimmed, `/`-separated, without a leading +/// `./` or a trailing `/`, blank lines dropped, duplicates removed, in the +/// order given. +/// +/// # Arguments +/// +/// * `paths` - the entries as a person typed them, one path each +/// +/// # Returns +/// +/// The normalised paths. +/// +/// # Errors +/// +/// The first entry that is not a path inside the tree +/// ([`ExcludePathError`]), or [`ExcludePathError::TooMany`]. +/// +/// # Examples +/// +/// ``` +/// use compliance_core::models::normalise_exclude_paths; +/// +/// let paths = vec!["./docs/samples/".to_string(), "".to_string(), "tools\\old".to_string()]; +/// assert_eq!(normalise_exclude_paths(&paths).unwrap(), ["docs/samples", "tools/old"]); +/// assert!(normalise_exclude_paths(&["../etc".to_string()]).is_err()); +/// ``` +pub fn normalise_exclude_paths(paths: &[String]) -> Result, ExcludePathError> { + let mut out: Vec = Vec::with_capacity(paths.len()); + for raw in paths { + let Some(path) = normalise_one(raw)? else { + continue; + }; + if !out.contains(&path) { + out.push(path); + } + } + if out.len() > MAX_EXCLUDE_PATHS { + return Err(ExcludePathError::TooMany); + } + Ok(out) +} + +/// One entry normalised; `None` for a blank one. +fn normalise_one(raw: &str) -> Result, ExcludePathError> { + let given = raw.trim(); + if given.is_empty() { + return Ok(None); + } + if given.len() > MAX_EXCLUDE_PATH_LEN { + return Err(ExcludePathError::TooLong(given.to_string())); + } + if given.contains(['*', '?', '[']) { + return Err(ExcludePathError::Wildcard(given.to_string())); + } + let slashed = given.replace('\\', "/"); + // `/src`, and a Windows drive (`C:/src`). + let drive = slashed.as_bytes().get(1) == Some(&b':'); + if slashed.starts_with('/') || drive { + return Err(ExcludePathError::Absolute(given.to_string())); + } + let parts: Vec<&str> = slashed + .trim_start_matches("./") + .split('/') + .filter(|part| !part.is_empty()) + .collect(); + let outside = parts.is_empty() + || parts + .iter() + .any(|part| matches!(*part, "." | "..") || part.eq_ignore_ascii_case(".git")); + if outside { + return Err(ExcludePathError::OutsideTree(given.to_string())); + } + Ok(Some(parts.join("/"))) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + fn norm(paths: &[&str]) -> Result, ExcludePathError> { + let owned: Vec = paths.iter().map(|p| p.to_string()).collect(); + normalise_exclude_paths(&owned) + } + + #[test] + fn paths_are_stored_relative_and_slash_separated() { + assert_eq!( + norm(&[ + " ./docs/samples/ ", + "", + "tools\\legacy.py", + "docs//samples", + "a/b" + ]) + .unwrap(), + ["docs/samples", "tools/legacy.py", "a/b"] + ); + assert!(norm(&[]).unwrap().is_empty()); + } + + #[test] + fn a_path_outside_the_tree_is_refused() { + for bad in [ + "/etc", + "C:\\src", + "..", + "a/../b", + "./", + ".", + ".git", + "src/.git/hooks", + ] { + let err = norm(&[bad]).unwrap_err(); + assert!( + matches!( + err, + ExcludePathError::Absolute(_) | ExcludePathError::OutsideTree(_) + ), + "{bad}: {err:?}" + ); + } + } + + #[test] + fn wildcards_length_and_count_are_limited() { + assert_eq!( + norm(&["src/*.c"]), + Err(ExcludePathError::Wildcard("src/*.c".into())) + ); + let long = "a".repeat(MAX_EXCLUDE_PATH_LEN + 1); + assert!(matches!( + norm(&[long.as_str()]), + Err(ExcludePathError::TooLong(_)) + )); + let many: Vec = (0..=MAX_EXCLUDE_PATHS).map(|n| format!("d{n}")).collect(); + assert_eq!( + normalise_exclude_paths(&many), + Err(ExcludePathError::TooMany) + ); + // Duplicates count once. + let same: Vec = (0..=MAX_EXCLUDE_PATHS).map(|_| "d".to_string()).collect(); + assert_eq!(normalise_exclude_paths(&same).unwrap(), ["d"]); + } + + #[test] + fn the_error_names_the_entry() { + let err = norm(&["../x"]).unwrap_err(); + assert!(err.to_string().starts_with("../x:"), "{err}"); + } +} diff --git a/compliance-core/src/models/finding.rs b/compliance-core/src/models/finding.rs index d809d2e..a8fe55c 100644 --- a/compliance-core/src/models/finding.rs +++ b/compliance-core/src/models/finding.rs @@ -134,6 +134,9 @@ pub enum ScanChangeKind { /// Its file now lies in test data (`fixtures/`, `testdata/`), which is /// left out of the scan. NowTestData, + /// Its file now lies in a path the target's settings exclude from the + /// scan (`scan_config.exclude_paths`). + NowExcluded, /// A finding marked resolved was reported again. FoundAgain, /// Its rule fired often enough in the repository that its occurrences diff --git a/compliance-core/src/models/mod.rs b/compliance-core/src/models/mod.rs index 7ca036a..49de951 100644 --- a/compliance-core/src/models/mod.rs +++ b/compliance-core/src/models/mod.rs @@ -4,6 +4,7 @@ pub mod credentials; pub mod cve; pub mod dast; pub mod embedding; +pub mod exclude_paths; pub mod finding; pub mod git_source; pub mod graph; @@ -39,6 +40,9 @@ pub use dast::{ DastTarget, DastTargetType, DastVulnType, }; pub use embedding::{CodeEmbedding, EmbeddingBuildRun, EmbeddingBuildStatus}; +pub use exclude_paths::{ + normalise_exclude_paths, ExcludePathError, MAX_EXCLUDE_PATHS, MAX_EXCLUDE_PATH_LEN, +}; pub use finding::{ Finding, FindingStatus, Occurrence, ScanChangeKind, ScanStatusChange, Severity, StatusChange, }; diff --git a/compliance-core/src/models/onboarding.rs b/compliance-core/src/models/onboarding.rs index 1b9c7ea..22c2fe3 100644 --- a/compliance-core/src/models/onboarding.rs +++ b/compliance-core/src/models/onboarding.rs @@ -417,6 +417,10 @@ pub struct TargetScanConfig { pub pentest: Option, /// Issue-tracker linkage. pub issue_tracker: Option, + /// Directories and files left out of every scan stage, relative to the + /// tree's root, as [`super::normalise_exclude_paths`] stores them. + #[serde(default)] + pub exclude_paths: Vec, } /// A sibling product in the company suite that may already hold authoritative diff --git a/compliance-core/src/models/scan.rs b/compliance-core/src/models/scan.rs index df78bf6..e2cab25 100644 --- a/compliance-core/src/models/scan.rs +++ b/compliance-core/src/models/scan.rs @@ -205,6 +205,9 @@ pub enum SkipCode { /// Test-data directories (`fixtures/`, `testdata/`) left out of the whole /// scan: code findings, SBOM and CVE match; `subject` lists them. TestData, + /// Paths the target's settings exclude (`scan_config.exclude_paths`), + /// left out of the whole scan; `subject` lists those that were removed. + ExcludedPaths, /// An analysis tool did not complete; `subject` names it. ToolFailed, /// A package manifest without a lockfile; `subject` is the manifest. @@ -269,7 +272,11 @@ impl SkipCode { pub fn is_informational(self) -> bool { // An exhaustive match, so a new code has to be classified here. match self { - Self::VendorCode | Self::TestData | Self::SuppressedInSource | Self::NotInTree => true, + Self::VendorCode + | Self::TestData + | Self::ExcludedPaths + | Self::SuppressedInSource + | Self::NotInTree => true, Self::FeatureDisabled | Self::SubmodulesNotFetched | Self::ToolFailed diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index d625db3..2f3f2dd 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -479,6 +479,10 @@ pub mod scans { de: "Herstellercode (HAL, CMSIS, Drittanbieter)", en: "Vendor code (HAL, CMSIS, third party)", }, + "excluded_paths" => Text { + de: "Ausgenommene Pfade", + en: "Excluded paths", + }, "test_data" => Text { de: "Testdaten (fixtures, testdata)", en: "Test data (fixtures, testdata)", @@ -598,6 +602,12 @@ pub mod scans { (SkipCode::TestData, Lang::En) => format!( "Test data, left out of the whole scan (code analysis, SBOM, CVEs): {subject}" ), + (SkipCode::ExcludedPaths, Lang::De) => format!( + "In den Einstellungen des Prüfobjekts ausgenommen, von der ganzen Prüfung ausgenommen (Codeanalyse, Stückliste, CVEs): {subject}" + ), + (SkipCode::ExcludedPaths, Lang::En) => format!( + "Excluded in the target's settings, left out of the whole scan (code analysis, SBOM, CVEs): {subject}" + ), (SkipCode::ToolFailed, Lang::De) => format!( "{subject} wurde nicht fertig; was es prüft, gilt als nicht bewertet." ), @@ -1063,6 +1073,52 @@ pub mod targets { de: "Hochladen", en: "Upload", }; + pub const EXCLUDE_TITLE: Text = Text { + de: "Von der Prüfung ausgenommen", + en: "Left out of the scan", + }; + pub const EXCLUDE_HINT: Text = Text { + de: "Ein Verzeichnis oder eine Datei je Zeile, relativ zum Wurzelverzeichnis \ + (z. B. docs/beispiele), ohne Platzhalter. Ausgenommenes erzeugt keine Befunde, \ + keine Stücklisten-Einträge und keine CVEs. Testdaten (fixtures, testdata) nimmt \ + die Prüfung von selbst aus.", + en: "One directory or file per line, relative to the root (e.g. docs/samples), \ + without wildcards. What is left out produces no findings, no SBOM components and \ + no CVEs. Test data (fixtures, testdata) is left out automatically.", + }; + + /// Why an excluded path was refused, naming the entry. + pub fn exclude_error( + error: &compliance_core::models::ExcludePathError, + lang: super::super::Lang, + ) -> String { + use super::super::Lang; + use compliance_core::models::{ExcludePathError as E, MAX_EXCLUDE_PATHS}; + match (error, lang) { + (E::TooMany, Lang::De) => { + format!("Höchstens {MAX_EXCLUDE_PATHS} Pfade können ausgenommen werden.") + } + (E::TooMany, Lang::En) => format!("At most {MAX_EXCLUDE_PATHS} paths can be excluded."), + (E::TooLong(p), Lang::De) => format!("{p}: zu lang."), + (E::TooLong(p), Lang::En) => format!("{p}: too long."), + (E::Absolute(p), Lang::De) => { + format!("{p}: relativ zum Wurzelverzeichnis angeben, ohne führenden /.") + } + (E::Absolute(p), Lang::En) => { + format!("{p}: give it relative to the root, without a leading /.") + } + (E::OutsideTree(p), Lang::De) => { + format!("{p}: muss ein Verzeichnis oder eine Datei im Repository sein.") + } + (E::OutsideTree(p), Lang::En) => { + format!("{p}: must be a directory or file inside the repository.") + } + (E::Wildcard(p), Lang::De) => { + format!("{p}: keine Platzhalter; Verzeichnis oder Datei angeben.") + } + (E::Wildcard(p), Lang::En) => format!("{p}: no wildcards; name the directory or file."), + } + } pub const UPLOADED: Text = Text { de: "Hochgeladen. Starten Sie die Prüfung, um die Datei zu prüfen.", en: "Uploaded. Start a scan to check the file.", @@ -1991,6 +2047,10 @@ pub mod findings { de: "Liegt jetzt in Testdaten, die von der Prüfung ausgenommen sind.", en: "Now lies in test data, which is left out of the scan.", }, + ScanChangeKind::NowExcluded => Text { + de: "Liegt jetzt in einem Pfad, den die Einstellungen des Prüfobjekts von der Prüfung ausnehmen.", + en: "Now lies in a path the target's settings leave out of the scan.", + }, ScanChangeKind::FoundAgain => Text { de: "Bei der Prüfung erneut gefunden.", en: "Found again by the scan.", diff --git a/compliance-dashboard/src/infrastructure/onboarding.rs b/compliance-dashboard/src/infrastructure/onboarding.rs index 4f86282..8b657dc 100644 --- a/compliance-dashboard/src/infrastructure/onboarding.rs +++ b/compliance-dashboard/src/infrastructure/onboarding.rs @@ -472,13 +472,16 @@ pub async fn upload_target_artifact( super::agent_client::json_or_error(resp).await } -/// Update a target's name / type / artifacts (dashboard editor). +/// Update a target's name / type / artifacts / excluded paths (dashboard +/// editor). `exclude_paths` replaces the stored list; the agent normalises +/// and checks it (`normalise_exclude_paths`). #[server] pub async fn update_target( id: String, name: Option, target_type: Option, artifacts: Option>, + exclude_paths: Option>, ) -> Result { let mut body = serde_json::Map::new(); if let Some(n) = name { @@ -493,6 +496,12 @@ pub async fn update_target( serde_json::to_value(a).map_err(|e| ServerFnError::new(e.to_string()))?, ); } + if let Some(paths) = exclude_paths { + body.insert( + "scan_config".to_string(), + serde_json::json!({ "exclude_paths": paths }), + ); + } let resp = super::agent_client::agent_request( reqwest::Method::PATCH, &format!("/api/v1/targets/{id}"), diff --git a/compliance-dashboard/src/pages/target.rs b/compliance-dashboard/src/pages/target.rs index 361a2ba..242ce52 100644 --- a/compliance-dashboard/src/pages/target.rs +++ b/compliance-dashboard/src/pages/target.rs @@ -39,6 +39,21 @@ fn str_at<'a>(v: &'a serde_json::Value, key: &str) -> &'a str { v.get(key).and_then(|x| x.as_str()).unwrap_or("") } +/// The target's excluded paths (`scan_config.exclude_paths`), one per line +/// as the editor shows them. +fn exclude_paths_of(target: &serde_json::Value) -> String { + target["scan_config"]["exclude_paths"] + .as_array() + .map(|paths| { + paths + .iter() + .filter_map(serde_json::Value::as_str) + .collect::>() + .join("\n") + }) + .unwrap_or_default() +} + /// The target's artifacts as the editor edits them. Credentials never come /// back from the agent; only whether one is set. fn editable_artifacts(target: &serde_json::Value) -> Vec { @@ -463,6 +478,7 @@ fn TargetEditor( let mut edit_type = use_signal(|| str_at(&target, "target_type").to_string()); let mut edit_arts = use_signal(|| editable_artifacts(&target)); let mut edit_saving = use_signal(|| false); + let mut edit_excludes = use_signal(|| exclude_paths_of(&target)); // Projects are saved apart from the rest, and only when they changed. let stored_projects = project_ids_of(&target); let edit_projects = use_signal(|| stored_projects.clone()); @@ -475,6 +491,11 @@ fn TargetEditor( { let name_err = validate_target_name(&edit_name()); + // Checked as the agent checks it, so a bad path shows before Save. + let exclude_lines: Vec = edit_excludes().lines().map(String::from).collect(); + let excludes = compliance_core::models::normalise_exclude_paths(&exclude_lines); + let exclude_err = excludes.as_ref().err().map(|e| tx::exclude_error(e, lang)); + let exclude_paths = excludes.clone().unwrap_or_default(); let e_source_err = if e_source().is_empty() { None } else { @@ -643,6 +664,23 @@ fn TargetEditor( on_saved.call(()); }, } + div { class: "form-group", + label { {tx::EXCLUDE_TITLE.get(lang)} } + textarea { + rows: "3", + spellcheck: "false", + placeholder: "docs/samples", + style: "font-family: monospace;", + value: "{edit_excludes}", + oninput: move |e| edit_excludes.set(e.value()), + } + div { style: "font-size: 0.85em; color: var(--text-secondary); margin-top: 4px;", + {tx::EXCLUDE_HINT.get(lang)} + } + if let Some(err) = exclude_err.clone() { + div { style: "color: var(--danger, #d33); font-size: 0.85em;", "{err}" } + } + } match projects.read().clone() { Some(Ok(list)) => rsx! { ProjectPicker { projects: list, selected: edit_projects } }, Some(Err(e)) => rsx! { @@ -658,17 +696,18 @@ fn TargetEditor( } button { class: "btn btn-primary", - disabled: edit_saving() || name_err.is_some(), + disabled: edit_saving() || name_err.is_some() || exclude_err.is_some(), onclick: move |_| { let id = eid.clone(); let nm = edit_name(); let tt = edit_type(); let arts = edit_arts(); + let excluded = exclude_paths.clone(); let chosen = edit_projects(); let projects_changed = chosen != stored_projects; edit_saving.set(true); spawn(async move { - let saved = match update_target(id.clone(), Some(nm), Some(tt), Some(arts)).await { + let saved = match update_target(id.clone(), Some(nm), Some(tt), Some(arts), Some(excluded)).await { Ok(_) if projects_changed => set_target_projects(id, chosen).await, Ok(_) => Ok(()), Err(e) => Err(e), diff --git a/docs/guide/repositories.md b/docs/guide/repositories.md index 28040b2..c9f6f00 100644 --- a/docs/guide/repositories.md +++ b/docs/guide/repositories.md @@ -211,11 +211,32 @@ can: - enter or change the password of a password-protected archive; - upload another file under **Datei hinzufügen**: an archive (zip, tar, tar.gz), a PLC project or a firmware image. It is uploaded at once and checked by the - next scan. + next scan; +- leave directories or files out of every scan under **Von der Prüfung + ausgenommen** (see below). Click **Speichern** (Save) to keep the changes. Changes take effect with the next scan. +### Leaving Paths out of the Scan + +Under **Von der Prüfung ausgenommen**, enter one directory or file per line, +relative to the root of the repository or archive, for example `docs/samples` +or `tools/legacy.py`. A directory is left out with everything in it. Wildcards +are not supported, and a path must stay inside the tree (no leading `/`, no +`..`, not `.git`); at most 50 paths. + +What is left out produces nothing: no code findings, no SBOM components and no +CVEs. The scan run lists it under **Ausgenommene Pfade**, together with any +path that was not found in the tree. Findings an earlier scan reported there +are closed with the reason that the path is now excluded, and so are their +issues. Test data (`fixtures`, `testdata` and similar) is left out +automatically; see [Scanning](/guide/scanning). + +Through the API, send the list as `scan_config.exclude_paths` with +`PATCH /api/v1/targets/{id}`. It replaces the stored list; an invalid path is +refused with 422 and a message naming it. + ## Connecting an Issue Tracker New findings can be created as issues in GitHub, GitLab, Gitea or Jira. The diff --git a/docs/guide/scanning.md b/docs/guide/scanning.md index c9c08cc..f078a89 100644 --- a/docs/guide/scanning.md +++ b/docs/guide/scanning.md @@ -29,7 +29,9 @@ names while the scan runs. `test-fixtures` or `test_fixtures` (at any depth) hold sample projects and lockfiles that are not what the product ships, so they produce no code findings, no SBOM components and no CVEs. `tests/`, `spec/` and - `examples/` are scanned as usual. + `examples/` are scanned as usual. Paths the target's settings exclude are + left out the same way (see + [Leaving Paths out of the Scan](/guide/repositories#leaving-paths-out-of-the-scan)). 3. **Build the SBOM** (*SBOM erstellen*) -- the components from lockfiles (Syft), plus libraries copied into a firmware tree (FreeRTOS, FreeRTOS+TCP, lwIP, Mbed TLS, wolfSSL, FatFs), whose versions are read from their headers. @@ -161,6 +163,7 @@ as a clean result: the CRA requirements it checks show as **Nicht geprüft**. | **Git-Submodule** | Nicht ausgecheckt, daher nicht geprüft: *(names)* | Change SSH submodule URLs to HTTPS; see [Git Submodules](/guide/repositories#git-submodules). | | **Herstellercode (HAL, CMSIS, Drittanbieter)** | Hersteller- und Fremdcode ohne Codeanalyse, in der Stückliste enthalten: *(directories)* | Nothing; for information. | | **Testdaten (fixtures, testdata)** | Testdaten, von der ganzen Prüfung ausgenommen (Codeanalyse, Stückliste, CVEs): *(directories)* | Nothing; for information. Findings an earlier scan reported there are closed as test data. | +| **Ausgenommene Pfade** | In den Einstellungen des Prüfobjekts ausgenommen, von der ganzen Prüfung ausgenommen (Codeanalyse, Stückliste, CVEs): *(paths)* | Nothing; for information. Change the list under **Bearbeiten**. | | e.g. **Statische Codeanalyse (Semgrep)**, **C/C++-Analyse (cppcheck)** | *(tool)* wurde nicht fertig; was es prüft, gilt als nicht bewertet. | Start the scan again; if it recurs, contact support. | | **Abhängigkeiten (SBOM)** | *(manifest)* ohne Lockfile: Die Versionen der Abhängigkeiten und ihre CVEs sind nicht bekannt. | Commit the lockfile (see below). | | e.g. **Firmware-Binäranalyse**, **Container-Analyse**, **Mobile-App-Analyse** | e.g. Firmware-Images werden noch nicht entpackt … | Nothing analyses these files yet; scan the source code instead. |