Skip to content

Find the holes before someone else does. A fast, 100% Rust vulnerability scanner: XSS, SQL injection, leaked secrets, dependency CVEs and AI agent setups.

feat(cli): add --write-baseline and --baseline so CI fails only on new findings (#111)

Onur Ugur9e6e81152c3c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 92fa8d3..68e604a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -66,6 +66,9 @@
- Agent: new rule `agent.mcp-auto-approve` (high) for `"enableAllProjectMcpServers": true` in
`.claude/settings*.json`, which starts every MCP server in the project's `.mcp.json` without asking about
each one.
+- CLI: `--write-baseline <file>` records the current findings (rule, path and a SHA-256 of the line, no code or
+ secrets), and `--baseline <file>` hides them, wherever the line moved to, and says how many it hid, so CI can
+ fail only on new findings. The action has a `baseline` input for it.
- CLI: `--sarif` writes paths from the working directory, not from the scanned folder, so
`safe-anything app --sarif` (or the action's `path: app`) gives `app/src/x.js` and code scanning finds
the file. The terminal and `--json` reports keep paths relative to the scanned folder.
diff --git a/Cargo.lock b/Cargo.lock
index 2601b49..3eaab46 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -649,6 +649,7 @@ dependencies = [
"clap",
"ignore",
"regex",
+ "ring",
"serde",
"serde_json",
"ureq",
diff --git a/Cargo.toml b/Cargo.toml
index 6c3ecd6..fca13b6 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -13,6 +13,7 @@ rust-version = "1.88"
clap = { version = "4", features = ["derive"] }
ignore = "0.4"
regex = "1"
+ring = "0.17"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
ureq = { version = "3", features = ["json"] }
diff --git a/README.md b/README.md
index 86f3c29..0a0b5ab 100644
--- a/README.md
+++ b/README.md
@@ -84,6 +84,19 @@ safe-anything --list-rules
- In tests, specs and fixtures only real provider keys and private keys count, unless you pass
`--include-tests`.
+On a codebase that already has findings, save them once and fail only on new ones:
+
+```bash
+safe-anything . --write-baseline .safe-anything-baseline.json
+safe-anything . --baseline .safe-anything-baseline.json
+```
+
+The baseline holds each finding's rule, path and a SHA-256 of its line, not the line itself, so it
+can be committed. A finding counts as known when all three match, wherever the line moved to. Paths
+are relative to the scanned folder, so scan the same folder you saved it from. Only files written by
+`--write-baseline` are read, not `--json` reports. Review changes to it like code: an entry added to
+it hides that finding.
+
## What it finds
90 rules, each with a CWE id, an OWASP category and a link to the OWASP page that explains it.
@@ -130,6 +143,7 @@ Tools: `scan` (path, offline, severity, include_tests) and `list_rules`. The ski
- uses: erkamyaman/[email protected]
with:
fail-on: high
+ # baseline: .safe-anything-baseline.json # fail only on findings not in it
- uses: github/codeql-action/upload-sarif@v4
if: always()
with:
diff --git a/action.yml b/action.yml
index fe22d22..fab6dd0 100644
--- a/action.yml
+++ b/action.yml
@@ -22,6 +22,9 @@ inputs:
sarif:
description: Path of the SARIF file to write, for github/codeql-action/upload-sarif
default: safe-anything.sarif
+ baseline:
+ description: A file from `safe-anything --write-baseline`; findings already in it do not fail the job (the SARIF file still lists them)
+ default: ""
outputs:
sarif:
description: Path of the SARIF file
@@ -62,8 +65,10 @@ runs:
FAIL_ON: ${{ inputs.fail-on }}
OFFLINE: ${{ inputs.offline }}
SARIF: ${{ inputs.sarif }}
+ BASELINE: ${{ inputs.baseline }}
run: |
args=("$SCAN_PATH" --severity "$SEVERITY")
[ "$OFFLINE" = true ] && args+=(--offline)
safe-anything "${args[@]}" --sarif --fail-on never > "$SARIF"
+ [ -n "$BASELINE" ] && args+=(--baseline "$BASELINE")
safe-anything "${args[@]}" --fail-on "$FAIL_ON"
diff --git a/src/main.rs b/src/main.rs
index d6f2b8b..33d291a 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,9 +1,11 @@
+use std::collections::HashMap;
use std::io::IsTerminal;
use std::path::{Component, Path, PathBuf};
use std::process::ExitCode;
use clap::Parser;
-use safe_anything::{Options, Severity, report};
+use safe_anything::{Family, Finding, Options, Severity, report};
+use serde::{Deserialize, Serialize};
#[derive(Parser)]
#[command(
@@ -35,6 +37,102 @@ struct Cli {
/// List every rule and exit
#[arg(long)]
list_rules: bool,
+ /// Hide the findings recorded in this file by --write-baseline
+ #[arg(long, value_name = "FILE")]
+ baseline: Option<PathBuf>,
+ /// Record the current findings in this file for --baseline and exit (rule, path and a hash of
+ /// the line; no code or secrets)
+ #[arg(long, value_name = "FILE", conflicts_with_all = ["baseline", "json", "sarif"])]
+ write_baseline: Option<PathBuf>,
+}
+
+/// The file `--write-baseline` writes and `--baseline` reads.
+#[derive(Serialize, Deserialize)]
+struct Baseline {
+ version: u32,
+ findings: Vec<Known>,
+}
+
+/// What a baseline keeps of a finding. Not the line itself: a snippet can hold a secret the scan
+/// does not mask, and the file is meant to be committed.
+#[derive(Serialize, Deserialize, PartialEq, Eq, Hash, PartialOrd, Ord)]
+struct Known {
+ path: String,
+ rule: String,
+ sha256: String,
+}
+
+impl Known {
+ /// Line numbers are left out, so moving code does not bring an old finding back. A
+ /// dependency's snippet is only `name@version (ecosystem)`, so its hash also takes the message,
+ /// which names the advisories: a new advisory for the same version is a new finding.
+ fn of(f: &Finding) -> Self {
+ let line = f.snippet.trim();
+ let text = if f.family == Family::Dependency {
+ format!("{line}\n{}", f.message)
+ } else {
+ line.to_string()
+ };
+ let digest = ring::digest::digest(&ring::digest::SHA256, text.as_bytes());
+ Self {
+ path: f.path.clone(),
+ rule: f.rule.clone(),
+ sha256: digest.as_ref().iter().map(|b| format!("{b:02x}")).collect(),
+ }
+ }
+}
+
+fn write_baseline(file: &Path, findings: &[Finding]) -> Result<(), String> {
+ let mut findings: Vec<Known> = findings.iter().map(Known::of).collect();
+ findings.sort();
+ let json = serde_json::to_string_pretty(&Baseline {
+ version: 1,
+ findings,
+ })
+ .unwrap();
+ std::fs::write(file, json + "\n").map_err(|e| format!("{}: {e}", file.display()))
+}
+
+/// Reads a `--write-baseline` file into a count per finding.
+fn load_baseline(file: &Path) -> Result<HashMap<Known, usize>, String> {
+ let text = std::fs::read_to_string(file).map_err(|e| format!("{}: {e}", file.display()))?;
+ let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
+ let baseline: Baseline = serde_json::from_str(text)
+ .ok()
+ .filter(|b: &Baseline| b.version == 1)
+ .ok_or_else(|| {
+ format!(
+ "{} is not a baseline written by --write-baseline",
+ file.display()
+ )
+ })?;
+ let mut known = HashMap::new();
+ for k in baseline.findings {
+ *known.entry(k).or_default() += 1;
+ }
+ Ok(known)
+}
+
+/// Drops the findings in the baseline and returns how many. Each entry hides one finding, so a
+/// second copy of a known line still counts as new.
+fn apply_baseline(known: &mut HashMap<Known, usize>, findings: &mut Vec<Finding>) -> usize {
+ let before = findings.len();
+ findings.retain(|f| match known.get_mut(&Known::of(f)) {
+ Some(n) if *n > 0 => {
+ *n -= 1;
+ false
+ }
+ _ => true,
+ });
+ before - findings.len()
+}
+
+fn findings(n: usize) -> String {
+ if n == 1 {
+ "1 finding".into()
+ } else {
+ format!("{n} findings")
+ }
}
fn parse_severity(s: &str) -> Result<Severity, String> {
@@ -113,6 +211,13 @@ fn main() -> ExitCode {
}
},
};
+ let mut baseline = match cli.baseline.as_deref().map(load_baseline).transpose() {
+ Ok(b) => b,
+ Err(e) => {
+ eprintln!("error: {e}");
+ return ExitCode::from(2);
+ }
+ };
let mut options = if cli.offline {
Options::offline()
} else {
@@ -127,6 +232,24 @@ fn main() -> ExitCode {
}
};
report.findings.retain(|f| f.severity >= cli.severity);
+ if let Some(file) = &cli.write_baseline {
+ return match write_baseline(file, &report.findings) {
+ Ok(()) => {
+ let n = findings(report.findings.len());
+ eprintln!("Wrote {n} to {}.", file.display());
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::from(2)
+ }
+ };
+ }
+ if let Some(known) = &mut baseline {
+ let n = apply_baseline(known, &mut report.findings);
+ let verb = if n == 1 { "is" } else { "are" };
+ eprintln!("{} {verb} in the baseline and not shown.", findings(n));
+ }
if cli.sarif {
let prefix = sarif_prefix(&cli.path);
for f in &mut report.findings {
@@ -149,3 +272,49 @@ fn main() -> ExitCode {
ExitCode::SUCCESS
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn finding(family: Family, line: usize, message: &str, snippet: &str) -> Finding {
+ Finding {
+ rule: "r".into(),
+ family,
+ severity: Severity::High,
+ path: "p".into(),
+ line,
+ message: message.into(),
+ fix: String::new(),
+ snippet: snippet.into(),
+ cwe: String::new(),
+ owasp: String::new(),
+ learn_more: String::new(),
+ }
+ }
+
+ #[test]
+ fn baseline_entry_ignores_the_line_but_not_a_new_advisory() {
+ let code =
+ |line, message, snippet| Known::of(&finding(Family::Code, line, message, snippet));
+ assert!(code(1, "a", "x = 1") == code(9, "b", " x = 1 "));
+ assert!(code(1, "a", "x = 1") != code(1, "a", "x = 2"));
+ assert_eq!(code(1, "a", "").sha256.len(), 64);
+ let dep = |message| {
+ Known::of(&finding(
+ Family::Dependency,
+ 1,
+ message,
+ ))
+ };
+ assert!(
+ dep("lodash 4.17.20 has known vulnerabilities: GHSA-1")
+ == dep("lodash 4.17.20 has known vulnerabilities: GHSA-1")
+ );
+ assert!(
+ dep("lodash 4.17.20 has known vulnerabilities: GHSA-1")
+ != dep("lodash 4.17.20 has known vulnerabilities: GHSA-1; GHSA-2")
+ );
+ }
+}
diff --git a/tests/cli.rs b/tests/cli.rs
index 7e390a8..e9ab053 100644
--- a/tests/cli.rs
+++ b/tests/cli.rs
@@ -199,6 +199,125 @@ fn sarif_paths_are_relative_to_the_working_directory() {
std::fs::remove_dir_all(&dir).unwrap();
}
+#[test]
+fn baseline_hides_known_findings_only() {
+ let dir = std::env::temp_dir().join(format!("safe-anything-baseline-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let app = dir.join("app.js");
+ let baseline = dir.join(".safe-anything-baseline.json");
+ let scan = |extra: &[&str]| {
+ let out = Command::new(env!("CARGO_BIN_EXE_safe-anything"))
+ .arg(&dir)
+ .arg("--offline")
+ .args(extra)
+ .output()
+ .unwrap();
+ (
+ out.status.code().unwrap_or(-1),
+ String::from_utf8_lossy(&out.stdout).into_owned(),
+ String::from_utf8_lossy(&out.stderr).into_owned(),
+ )
+ };
+ let found = |out: &str| -> Vec<(String, String, u64)> {
+ let report: serde_json::Value = serde_json::from_str(out).unwrap();
+ report["findings"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|f| {
+ (
+ f["path"].as_str().unwrap().into(),
+ f["rule"].as_str().unwrap().into(),
+ f["line"].as_u64().unwrap(),
+ )
+ })
+ .collect()
+ };
+ let eval = "const f = eval(req.body.code);\n";
+ let public = "const k = process.env.NEXT_PUBLIC_API_SECRET;\n";
+ std::fs::write(&app, [eval, public].concat()).unwrap();
+ let (code, _, err) = scan(&["--write-baseline", baseline.to_str().unwrap()]);
+ assert_eq!(code, 0, "{err}");
+ assert!(err.contains("Wrote 2 findings"), "{err}");
+ let written = std::fs::read_to_string(&baseline).unwrap();
+ assert!(
+ !written.contains("eval(req") && !written.contains("NEXT_PUBLIC"),
+ "{written}"
+ );
+
+ // The baseline sits in the scanned folder and gives no finding of its own.
+ let (code, out, _) = scan(&["--json"]);
+ assert_eq!(code, 1);
+ assert_eq!(found(&out).len(), 2, "{out}");
+
+ let with_baseline = ["--json", "--baseline", baseline.to_str().unwrap()];
+ let (code, out, err) = scan(&with_baseline);
+ assert_eq!((code, found(&out)), (0, vec![]), "{out}");
+ assert!(err.contains("2 findings are in the baseline"), "{err}");
+
+ // Moved code is still known; a new finding and a second copy of a known line are not.
+ std::fs::write(&app, ["\n\n", public, eval].concat()).unwrap();
+ assert_eq!(scan(&with_baseline).0, 0);
+ let new = "const g = eval(req.query.x);\n";
+ std::fs::write(&app, [eval, public, new, eval].concat()).unwrap();
+ let (code, out, err) = scan(&with_baseline);
+ assert_eq!(code, 1);
+ let eval_at = |line| ("app.js".to_string(), "code.eval".to_string(), line);
+ assert_eq!(found(&out), vec![eval_at(3), eval_at(4)], "{out}");
+ assert!(err.contains("2 findings are in the baseline"), "{err}");
+
+ // Only the --write-baseline format is read: a --json report is refused.
+ let (_, report, _) = scan(&["--json"]);
+ std::fs::write(&baseline, report).unwrap();
+ assert_eq!(scan(&with_baseline).0, 2);
+ std::fs::write(&baseline, "{\"findings\": []}").unwrap();
+ assert_eq!(scan(&with_baseline).0, 2);
+ std::fs::remove_file(&baseline).unwrap();
+ assert_eq!(scan(&with_baseline).0, 2);
+ std::fs::remove_dir_all(&dir).unwrap();
+}
+
+#[test]
+fn baseline_file_holds_no_line_text() {
+ let file = std::env::temp_dir().join(format!(
+ "safe-anything-baseline-text-{}.json",
+ std::process::id()
+ ));
+ for name in ["secrets", "config", "agent", "code"] {
+ let (_, out) = run(&[&fixture(name), "--offline", "--json"]);
+ let report: serde_json::Value = serde_json::from_str(&out).unwrap();
+ let (code, _) = run(&[
+ &fixture(name),
+ "--offline",
+ "--include-tests",
+ "--write-baseline",
+ file.to_str().unwrap(),
+ ]);
+ assert_eq!(code, 0);
+ let written = std::fs::read_to_string(&file).unwrap();
+ for f in report["findings"].as_array().unwrap() {
+ let snippet = f["snippet"].as_str().unwrap();
+ assert!(
+ snippet.len() < 8 || !written.contains(snippet),
+ "{name}: {snippet}"
+ );
+ }
+ for word in ["snippet", "message", "line", "fix"] {
+ assert!(!written.contains(&format!("\"{word}\"")), "{name}: {word}");
+ }
+ for value in [
+ common::fake("password"),
+ common::fake("db-password"),
+ common::fake("github"),
+ "supersecret123".to_string(),
+ ] {
+ assert!(!written.contains(&value), "{name}: {value}");
+ }
+ }
+ std::fs::remove_file(&file).unwrap();
+}
+
#[test]
fn mcp_server_scans_over_stdio() {
use std::io::{BufRead, BufReader, Write};