Files
pruefwerk/compliance-core/src/models/exclude_paths.rs
T
sharang 8ede373353
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Successful in 1m14s
CI / Deploy MCP (push) Successful in 2m53s
CI / Deploy Dashboard (push) Successful in 7m56s
CI / Deploy Agent (push) Successful in 10m50s
feat(scan): per-target excluded paths, left out of the whole scan (#825)
2026-11-04 08:48:40 +00:00

187 lines
6.0 KiB
Rust

//! 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<Vec<String>, ExcludePathError> {
let mut out: Vec<String> = 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<Option<String>, 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<Vec<String>, ExcludePathError> {
let owned: Vec<String> = 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<String> = (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<String> = (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}");
}
}