Find the holes before someone else does. A fast, 100% Rust vulnerability scanner: XSS, SQL injection, leaked secrets, dependency CVEs and AI agent setups.
Rust ai-agentsclaude-codeclaude-code-pluginclicodexcursordevsecopsmcposvowasprustsastsecret-scanningsecretssecuritysecurity-scannersql-injectionvulnerabilityvulnerability-scannerxss
fix(sarif): write paths from the working directory, not the scanned folder (#106)
Onur Ugure0988aee6cbb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e6dcd20..2042bd2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -62,6 +62,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 abouteach one.+- 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.- CLI: SARIF rules have a `fullDescription` and a `help` text (the fix, the CWE and OWASP category, and thelink), so a GitHub code scanning alert shows the fix in its side panel. `--list-rules --json` and the MCP`list_rules` tool include each rule's `fix`.diff --git a/src/main.rs b/src/main.rsindex e851efa..d6f2b8b 100644--- a/src/main.rs+++ b/src/main.rs@@ -1,5 +1,5 @@use std::io::IsTerminal;-use std::path::PathBuf;+use std::path::{Component, Path, PathBuf};use std::process::ExitCode;use clap::Parser;@@ -42,6 +42,39 @@ fn parse_severity(s: &str) -> Result<Severity, String> {.ok_or_else(|| format!("unknown severity `{s}` (low, medium, high, critical)"))}+/// GitHub code scanning reads SARIF paths from the repository root, so they start at the working+/// directory (where the action runs) instead of the scanned folder. This is that folder as a+/// `dir/` prefix, or nothing when it is the working directory or lies outside it.+fn sarif_prefix(root: &Path) -> String {+ let dir = match root.parent() {+ Some(parent) if root.is_file() => parent,+ _ => root,+ };+ let dir = if dir.as_os_str().is_empty() {+ Path::new(".")+ } else {+ dir+ };+ let Ok(cwd) = std::env::current_dir() else {+ return String::new();+ };+ let plain = std::path::absolute(dir)+ .ok()+ .filter(|p| !p.components().any(|c| c == Component::ParentDir))+ .and_then(|p| p.strip_prefix(&cwd).ok().map(Path::to_path_buf));+ // `..`, or a symlink like macOS's /tmp, needs the real paths.+ let rel = plain.or_else(|| {+ let (dir, cwd) = (dir.canonicalize().ok()?, cwd.canonicalize().ok()?);+ dir.strip_prefix(cwd).ok().map(Path::to_path_buf)+ });+ rel.map(|p| {+ p.components()+ .map(|c| format!("{}/", c.as_os_str().to_string_lossy()))+ .collect()+ })+ .unwrap_or_default()+}+fn main() -> ExitCode {if std::env::args().nth(1).as_deref() == Some("mcp") {return match safe_anything::mcp::serve() {@@ -95,6 +128,10 @@ fn main() -> ExitCode {};report.findings.retain(|f| f.severity >= cli.severity);if cli.sarif {+ let prefix = sarif_prefix(&cli.path);+ for f in &mut report.findings {+ f.path = format!("{prefix}{}", f.path);+ }println!("{}",serde_json::to_string_pretty(&safe_anything::sarif::render(&report)).unwrap()diff --git a/tests/cli.rs b/tests/cli.rsindex 25d9692..7e390a8 100644--- a/tests/cli.rs+++ b/tests/cli.rs@@ -165,6 +165,40 @@ fn sarif_rule_help_has_the_fix() {assert!(markdown.contains("Bash(npm test:\\*)"), "{shell}");}+#[test]+fn sarif_paths_are_relative_to_the_working_directory() {+ let dir = std::env::temp_dir().join(format!("safe-anything-sarif-{}", std::process::id()));+ std::fs::create_dir_all(dir.join("app/src")).unwrap();+ std::fs::write(dir.join("app/src/x.js"), "eval(req.query.code);\n").unwrap();+ let uri = |cwd: &Path, args: &[&str]| {+ let out = Command::new(env!("CARGO_BIN_EXE_safe-anything"))+ .args(args)+ .args(["--sarif", "--offline"])+ .current_dir(cwd)+ .output()+ .unwrap();+ let sarif: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();+ sarif["runs"][0]["results"][0]["locations"][0]["physicalLocation"]["artifactLocation"]+ ["uri"]+ .as_str()+ .unwrap()+ .to_string()+ };+ assert_eq!(uri(&dir, &["app"]), "app/src/x.js");+ assert_eq!(uri(&dir, &["./app/"]), "app/src/x.js");+ assert_eq!(uri(&dir, &["app/src/x.js"]), "app/src/x.js");+ assert_eq!(+ uri(&dir, &[dir.join("app").to_str().unwrap()]),+ "app/src/x.js"+ );+ assert_eq!(uri(&dir.join("app"), &["."]), "src/x.js");+ assert_eq!(uri(&dir.join("app/src"), &["../src"]), "x.js");+ // The terminal report keeps paths relative to the scanned folder.+ let (_, out) = run(&[dir.join("app").to_str().unwrap(), "--offline"]);+ assert!(out.contains(" src/x.js:1 "), "{out}");+ std::fs::remove_dir_all(&dir).unwrap();+}+#[test]fn mcp_server_scans_over_stdio() {use std::io::{BufRead, BufReader, Write};