feat(scan): leave test data (fixtures, testdata) out of the whole scan #820

Merged
sharang merged 2 commits from feat/test-data-scan-exclude into main 2026-11-04 08:28:52 +00:00
11 changed files with 421 additions and 12 deletions

No files matched your search

+25 -6
View File
@@ -45,6 +45,10 @@ pub struct RunFindings {
variants: AppVariants,
/// The scanned tree: the flagged lines fingerprints are made of (#491).
tree: Option<PathBuf>,
/// The test-data directories left out of the scanned tree
/// ([`crate::pipeline::test_data`]): a finding stored in one is closed as
/// test data, not as fixed.
test_data: Vec<String>,
}
/// One place a group lists: scanner, rule, file, line.
@@ -75,9 +79,17 @@ impl RunFindings {
grouped: HashSet::new(),
variants: AppVariants::default(),
tree: None,
test_data: Vec::new(),
}
}
/// 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<String>) -> Self {
self.test_data = dirs;
self
}
/// Key the findings of this run by the content of the code they flag in
/// the tree under `tree`, not by its line number (#491).
pub fn with_tree(mut self, tree: PathBuf) -> Self {
@@ -697,7 +709,8 @@ impl RunFindings {
.await?
.try_collect()
.await?;
let (mut fixed, mut vendored, mut grouped) = (Vec::new(), Vec::new(), Vec::new());
let (mut fixed, mut vendored, mut test_data, mut grouped) =
(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 {
@@ -706,9 +719,11 @@ impl RunFindings {
if self.inserted.contains_key(fingerprint) || self.earlier.contains(fingerprint) {
continue;
}
let in_vendor = row
.get_str("file_path")
.is_ok_and(|file| crate::pipeline::vendor::in_vendor_dir(file, vendor));
let file = row.get_str("file_path").ok();
let in_vendor = file.is_some_and(|f| crate::pipeline::vendor::in_vendor_dir(f, vendor));
// 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 completed = row
.get_str("scanner")
.is_ok_and(|scanner| self.completed.contains(scanner));
@@ -716,6 +731,8 @@ impl RunFindings {
grouped.push(id);
} else if !completed {
continue;
} else if in_test_data {
test_data.push(id);
} else if in_vendor {
vendored.push(id);
} else {
@@ -725,18 +742,20 @@ impl RunFindings {
for (ids, kind) in [
(&fixed, ScanChangeKind::NoLongerFound),
(&vendored, ScanChangeKind::NowVendorCode),
(&test_data, ScanChangeKind::NowTestData),
(&grouped, ScanChangeKind::Grouped),
] {
self.set_status(db, ids, &UNDECIDED, FindingStatus::Resolved, kind)
.await?;
}
let closed =
u32::try_from(fixed.len() + vendored.len() + grouped.len()).unwrap_or(u32::MAX);
let closed = u32::try_from(fixed.len() + vendored.len() + test_data.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(),
grouped = grouped.len(),
"resolved findings the scan no longer reports"
);
+8 -1
View File
@@ -399,7 +399,14 @@ impl GitOps {
let head_name = head_ref.name().unwrap_or("HEAD");
repo.reference(head_name, fetch_commit.id(), true, "fast-forward")?;
repo.checkout_head(Some(git2::build::CheckoutBuilder::default().force()))?;
// `recreate_missing`: a scan takes the test data out of its working
// copy (`pipeline::test_data`); every fetch puts it back, so what is
// left out always follows the current rules.
repo.checkout_head(Some(
git2::build::CheckoutBuilder::default()
.force()
.recreate_missing(true),
))?;
tracing::info!("Fetched and fast-forwarded {}", repo_path.display());
Ok(())
@@ -235,6 +235,10 @@ fn comment(status: &FindingStatus, change: Option<&StatusChange>) -> String {
"Die Datei gilt jetzt als Herstellercode und ist von den Befunden ausgenommen.",
"The file now counts as vendor code, which is left out of the findings.",
),
(FindingStatus::Resolved, Some(ScanChangeKind::NowTestData)) => (
"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, _) => (
"In Prüfwerk als behoben markiert.",
"Marked resolved in Prüfwerk.",
+1
View File
@@ -47,6 +47,7 @@ pub mod sbom;
pub mod sbom_quality;
pub mod semgrep;
pub mod source_text;
pub mod test_data;
pub mod tool_cmd;
mod tracker_dispatch;
pub(crate) mod unity_settings;
+62 -1
View File
@@ -225,6 +225,11 @@ 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;
let mut all_findings: Vec<Finding> = Vec::new();
// Each scanner stage saves its new findings at once, so they show while
// the scan runs (#372); triage updates them at the end.
@@ -237,7 +242,8 @@ impl PipelineOrchestrator {
.unwrap_or_default();
let mut run_findings = crate::pipeline::finding_store::RunFindings::new(scan_run_id)
.with_variants(variants)
.with_tree(repo_path.clone());
.with_tree(repo_path.clone())
.with_test_data(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
@@ -2275,6 +2281,61 @@ 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.
///
/// # 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<String> {
let root = tree.to_path_buf();
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()],
)
})
.await;
let removed = match pruned {
Ok(Ok(removed)) => removed,
Ok(Err(e)) => {
tracing::warn!(scan_run_id, error = %e, "test data not taken out of the scan");
return Vec::new();
}
Err(e) => {
tracing::warn!(scan_run_id, error = %e, "test-data walk failed");
return Vec::new();
}
};
if !removed.is_empty() {
let list = removed.join(", ");
self.skip_stage(
scan_run_id,
SkippedStage::new(
"test_data",
SkipCode::TestData,
format!(
"test data is left out of the whole scan (code findings, SBOM, CVE \
match): {list}"
),
)
.about(list),
)
.await;
}
removed
}
/// The recipe lint of a tree whose `languages` include BitBake, outside
/// the `vendor` directories: the findings, and the scanners that
/// completed. Upstream layers left out and findings suppressed in the
+282
View File
@@ -0,0 +1,282 @@
//! Test data inside a scanned tree: fixtures, sample projects, golden files.
//!
//! A repository's test data is not what it ships. Its sample lockfiles name
//! old, vulnerable dependencies on purpose, its sample code holds the flaws a
//! test expects to find, and none of it is the product's to fix. Scanned as
//! product code, it buries the real findings: the CVE issues of a test
//! fixture's `struts2 2.3.30` read exactly like those of a dependency the
//! product uses.
//!
//! So the directories that hold test data by a common convention are taken
//! out of the scan's working copy before the first stage runs, and every
//! stage — code findings, SBOM, CVE match — sees the tree without them. The
//! working copy is a git clone, restored on every fetch, or an unpacked
//! upload, unpacked again on every scan, so nothing is lost.
//!
//! Matching is by directory name only, and narrow: `tests/` and `spec/`
//! hold test code that can leak a real secret, and `examples/` or `demo/` are
//! often the product's own code, so neither is matched.
use std::path::Path;
/// Directory names that hold test data by convention, compared
/// case-insensitively: `fixtures` (Rails, pytest, Jest's `__fixtures__`),
/// Go's `testdata`, and their spellings.
const TEST_DATA_DIR_NAMES: &[&str] = &[
"fixtures",
"__fixtures__",
"testdata",
"test_data",
"test-data",
"test-fixtures",
"test_fixtures",
];
/// The top-most test-data directories under `root`, relative to it with `/`
/// separators, sorted. A directory inside one that already matched is not
/// listed again, `root` itself is never listed, and a symbolic link is never
/// followed or listed.
///
/// # Arguments
///
/// * `root` - the scanned tree
///
/// # Returns
///
/// The directories to leave out of the scan, e.g. `["fixtures",
/// "pkg/parser/testdata"]`.
pub fn test_data_dirs(root: &Path) -> Vec<String> {
let mut found = Vec::new();
let mut walker = walkdir::WalkDir::new(root).min_depth(1).into_iter();
while let Some(entry) = walker.next() {
let Ok(entry) = entry else {
continue;
};
// `file_type()` does not follow links: a link to a directory is a
// link here, never a directory.
if !entry.file_type().is_dir() {
continue;
}
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
if name == ".git" {
walker.skip_current_dir();
continue;
}
if TEST_DATA_DIR_NAMES.contains(&name.as_str()) {
if let Ok(rel) = entry.path().strip_prefix(root) {
found.push(rel.to_string_lossy().replace('\\', "/"));
}
walker.skip_current_dir();
}
}
found.sort();
found
}
/// Remove the `dirs` ([`test_data_dirs`]) 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.
///
/// # Arguments
///
/// * `root` - the scan's working copy
/// * `dirs` - directories 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.
///
/// # Errors
///
/// [`PruneError::NotOwned`] when `root` lies under none of `owned_bases`;
/// nothing is removed then.
pub fn prune(
root: &Path,
dirs: &[String],
owned_bases: &[&Path],
) -> Result<Vec<String>, PruneError> {
let owned = owned_bases
.iter()
.any(|base| !base.as_os_str().is_empty() && root.starts_with(base) && root != *base);
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");
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 {
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"),
}
}
Ok(removed)
}
/// Why [`prune`] removed nothing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum PruneError {
/// The tree is not a working copy the agent made.
#[error("the tree is not under the agent's clone or artifact directories")]
NotOwned,
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
fn write(root: &Path, rel: &str) {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "x").unwrap();
}
/// A scratch directory, removed on drop.
struct Scratch(std::path::PathBuf);
impl Scratch {
fn new() -> Self {
let dir = std::env::temp_dir().join(format!("cs-testdata-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
Self(dir)
}
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// A working copy under a fake clone base: `(base, tree)`.
fn tree() -> (Scratch, std::path::PathBuf) {
let base = Scratch::new();
let root = base.path().join("tenant").join("repo");
for file in [
"src/main.rs",
"src/fixtures_helper.rs",
"src/fixtures.rs",
"fixtures/nightly/eco/maven/pom.xml",
"fixtures/nightly/eco/maven/fixtures/inner.txt",
"pkg/parser/testdata/input.json",
"web/__fixtures__/user.json",
"Tests/Test-Data/sample.csv",
"tests/integration.rs",
"examples/demo.rs",
".git/fixtures/HEAD",
] {
write(&root, file);
}
(base, root)
}
#[test]
fn test_data_is_found_by_name_and_reported_once() {
let (_base, root) = tree();
assert_eq!(
test_data_dirs(&root),
[
"Tests/Test-Data",
"fixtures",
"pkg/parser/testdata",
"web/__fixtures__",
]
);
}
#[test]
fn the_tree_itself_is_never_test_data() {
let base = Scratch::new();
let root = base.path().join("fixtures");
write(&root, "package-lock.json");
assert!(test_data_dirs(&root).is_empty());
}
#[test]
fn pruning_removes_the_test_data_and_keeps_the_rest() {
let (base, root) = tree();
let dirs = test_data_dirs(&root);
let removed = prune(&root, &dirs, &[base.path()]).unwrap();
assert_eq!(removed, dirs);
assert!(!root.join("fixtures").exists());
assert!(!root.join("pkg/parser/testdata").exists());
assert!(root.join("pkg/parser").is_dir());
for kept in [
"src/main.rs",
"src/fixtures_helper.rs",
"src/fixtures.rs",
"tests/integration.rs",
"examples/demo.rs",
".git/fixtures/HEAD",
] {
assert!(root.join(kept).is_file(), "{kept} must stay");
}
}
#[test]
fn a_tree_the_agent_did_not_make_is_never_pruned() {
let (_base, root) = tree();
let elsewhere = Scratch::new();
let dirs = test_data_dirs(&root);
assert_eq!(
prune(&root, &dirs, &[elsewhere.path()]),
Err(PruneError::NotOwned)
);
// The base itself is not a working copy, and an empty base owns nothing.
assert_eq!(
prune(&root, &dirs, &[root.as_path(), Path::new("")]),
Err(PruneError::NotOwned)
);
assert!(root.join("fixtures").is_dir());
}
#[test]
fn a_path_outside_the_tree_is_never_removed() {
let (base, root) = tree();
let removed = prune(
&root,
&["../repo/src".to_string(), "/etc".to_string()],
&[base.path()],
)
.unwrap();
assert!(removed.is_empty());
assert!(root.join("src/main.rs").is_file());
}
#[cfg(unix)]
#[test]
fn a_link_named_like_test_data_is_left_alone() {
let (base, root) = tree();
let target = base.path().join("outside");
write(&target, "keep.txt");
std::os::unix::fs::symlink(&target, root.join("src/testdata")).unwrap();
let dirs = test_data_dirs(&root);
assert!(!dirs.contains(&"src/testdata".to_string()));
prune(&root, &["src/testdata".to_string()], &[base.path()]).unwrap();
assert!(target.join("keep.txt").is_file());
assert!(root.join("src/testdata").exists());
}
}
+11 -3
View File
@@ -69,6 +69,7 @@ async fn a_scan_closes_what_it_no_longer_finds_and_reopens_what_returns() {
finding("fp-kept", "semgrep", "src/a.c"),
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-lint", "clippy", "src/lib.rs"),
decided,
other_target,
@@ -81,15 +82,16 @@ 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");
let mut run = RunFindings::new("run-2").with_test_data(vec!["fixtures".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 and vendored closed, each with its reason; the rest kept.
assert_eq!(closed, 2);
// Assert: fixed, vendored and test data closed, each with its reason;
// the rest kept.
assert_eq!(closed, 3);
let fixed = row(&db, "fp-fixed").await;
assert_eq!(fixed.status, FindingStatus::Resolved);
assert_eq!(
@@ -102,6 +104,12 @@ async fn a_scan_closes_what_it_no_longer_finds_and_reopens_what_returns() {
last_scan_change(&vendored),
Some(ScanChangeKind::NowVendorCode)
);
let test_data = row(&db, "fp-test-data").await;
assert_eq!(test_data.status, FindingStatus::Resolved);
assert_eq!(
last_scan_change(&test_data),
Some(ScanChangeKind::NowTestData)
);
assert_eq!(row(&db, "fp-kept").await.status, FindingStatus::Open);
assert_eq!(
row(&db, "fp-false-positive").await.status,
+3
View File
@@ -131,6 +131,9 @@ pub enum ScanChangeKind {
NoLongerFound,
/// Its file now lies in vendor code, which is left out of the findings.
NowVendorCode,
/// Its file now lies in test data (`fixtures/`, `testdata/`), which is
/// left out of the scan.
NowTestData,
/// A finding marked resolved was reported again.
FoundAgain,
/// Its rule fired often enough in the repository that its occurrences
+4 -1
View File
@@ -202,6 +202,9 @@ pub enum SkipCode {
/// Vendor and third-party directories left out of SAST; `subject` lists
/// them.
VendorCode,
/// Test-data directories (`fixtures/`, `testdata/`) left out of the whole
/// scan: code findings, SBOM and CVE match; `subject` lists them.
TestData,
/// An analysis tool did not complete; `subject` names it.
ToolFailed,
/// A package manifest without a lockfile; `subject` is the manifest.
@@ -266,7 +269,7 @@ 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::SuppressedInSource | Self::NotInTree => true,
Self::VendorCode | Self::TestData | Self::SuppressedInSource | Self::NotInTree => true,
Self::FeatureDisabled
| Self::SubmodulesNotFetched
| Self::ToolFailed
+14
View File
@@ -479,6 +479,10 @@ pub mod scans {
de: "Herstellercode (HAL, CMSIS, Drittanbieter)",
en: "Vendor code (HAL, CMSIS, third party)",
},
"test_data" => Text {
de: "Testdaten (fixtures, testdata)",
en: "Test data (fixtures, testdata)",
},
"sbom" => Text {
de: "Stückliste (Syft)",
en: "SBOM (Syft)",
@@ -588,6 +592,12 @@ pub mod scans {
(SkipCode::VendorCode, Lang::En) => format!(
"Vendor and third-party code, left out of code analysis but in the SBOM: {subject}"
),
(SkipCode::TestData, Lang::De) => format!(
"Testdaten, von der ganzen Prüfung ausgenommen (Codeanalyse, Stückliste, CVEs): {subject}"
),
(SkipCode::TestData, Lang::En) => format!(
"Test data, 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."
),
@@ -1977,6 +1987,10 @@ pub mod findings {
de: "Liegt jetzt in Herstellercode, der von den Befunden ausgenommen ist.",
en: "Now lies in vendor code, which is left out of the findings.",
},
ScanChangeKind::NowTestData => Text {
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::FoundAgain => Text {
de: "Bei der Prüfung erneut gefunden.",
en: "Found again by the scan.",
+7
View File
@@ -24,6 +24,12 @@ names while the scan runs.
(out-of-bounds writes, uninitialised reads, null dereferences). Vendor and
third-party code (HAL, CMSIS, vendored libraries) is left out of the code
findings and listed under **Nicht ausgeführt**; it stays in the SBOM.
Test data is left out of the whole scan before this step: directories named
`fixtures`, `__fixtures__`, `testdata`, `test_data`, `test-data`,
`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.
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.
@@ -154,6 +160,7 @@ as a clean result: the CRA requirements it checks show as **Nicht geprüft**.
| e.g. **Dynamische Prüfung (DAST)**, **Penetrationstest**, **Industrieprotokolle (ICS)**, **SPS-Laufzeittest** | In dieser Umgebung nicht aktiviert. | Nothing. This deployment does not run the step. |
| **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. |
| 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. |