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
perf(action): scan once, with a new --sarif-file flag (#112)
Onur Ugurdf09ca7053ac
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 68e604a..693c374 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -43,6 +43,8 @@`restrict_public_buckets = false` in an `aws_s3_bucket_public_access_block` or `aws_s3_account_public_access_block`.- Secrets: new rule `secret.groq-key` (critical) for Groq API keys (`gsk_` followed by 52 letters or digits).- Code: new rule `code.open-redirect` (medium) for redirects built straight from request input (`res.redirect(req.query.next)`, `redirect(request.args.get("next"))`); a redirect to a fixed path stays unflagged.+- CLI: `--sarif-file <FILE>` writes SARIF to a file from the same scan that prints the report and sets the+ exit code. The GitHub Action uses it, so it scans (and asks OSV.dev) once instead of twice.- Config: new rules `config.tf-public-database` (high) for `publicly_accessible = true` and `config.tf-unencrypted-storage` (medium)for `storage_encrypted = false` in Terraform files. `publicly_accessible = false`, `storage_encrypted = true` and commented-out lines stay unflagged.- Config: `config.remote-script` also checks GitHub Actions workflows, so a `run:` step (or a line in adiff --git a/README.md b/README.mdindex 0a0b5ab..54e0c86 100644--- a/README.md+++ b/README.md@@ -63,6 +63,7 @@ found, so it works as a pre-commit or CI check as is.```bashsafe-anything . --json # machine-readable reportsafe-anything . --sarif # GitHub code scanning+safe-anything . --sarif-file out # SARIF to the file out, the report on screensafe-anything . --offline # no network (skips the dependency check)safe-anything . --severity medium # hide low findingssafe-anything . --fail-on never # always exit 0 (or low, medium, high, critical)diff --git a/action.yml b/action.ymlindex fab6dd0..a8a2f37 100644--- a/action.yml+++ b/action.yml@@ -23,7 +23,7 @@ inputs:description: Path of the SARIF file to write, for github/codeql-action/upload-sarifdefault: safe-anything.sarifbaseline:- description: A file from `safe-anything --write-baseline`; findings already in it do not fail the job (the SARIF file still lists them)+ description: A file from `safe-anything --write-baseline`; findings already in it are left out of the report and the SARIF file and do not fail the jobdefault: ""outputs:sarif:@@ -69,6 +69,15 @@ runs: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"+ case "$(safe-anything --help)" in+ *--sarif-file*)+ # One scan writes the SARIF file and prints the report.+ safe-anything "${args[@]}" --sarif-file "$SARIF" --fail-on "$FAIL_ON"+ ;;+ *)+ # A release from before --sarif-file (picked with the version input).+ safe-anything "${args[@]}" --sarif --fail-on never > "$SARIF"+ safe-anything "${args[@]}" --fail-on "$FAIL_ON"+ ;;+ esacdiff --git a/docs/STATUS.md b/docs/STATUS.mdindex db96f01..03cff92 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -23,6 +23,7 @@ by this repository's tests (a fixture per family with safe look-alikes that must| Terminal | Tested | `tests/cli.rs` || `--json` | Tested | `tests/cli.rs` || `--sarif` | Tested | shape checked in `tests/cli.rs`; not yet uploaded to GitHub code scanning |+| `--sarif-file` | Tested | `tests/cli.rs`: same SARIF as `--sarif`, written by the run that prints the report and sets the exit code || MCP (`safe-anything mcp`) | Tested | initialize, tools/list, tools/call over stdio in `tests/cli.rs`; not yet run inside an agent || GitHub Action (`action.yml`) | Not run | needs a published release to download |diff --git a/src/main.rs b/src/main.rsindex 33d291a..6f6a0b6 100644--- a/src/main.rs+++ b/src/main.rs@@ -22,6 +22,9 @@ struct Cli {/// Print the report as SARIF 2.1.0 (GitHub code scanning)#[arg(long)]sarif: bool,+ /// Also write the report as SARIF 2.1.0 to this file, from the same scan+ #[arg(long, value_name = "FILE")]+ sarif_file: Option<PathBuf>,/// Skip the dependency check (no network)#[arg(long)]offline: bool,@@ -42,7 +45,7 @@ struct Cli {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"])]+ #[arg(long, value_name = "FILE", conflicts_with_all = ["baseline", "json", "sarif", "sarif_file"])]write_baseline: Option<PathBuf>,}@@ -250,15 +253,33 @@ fn main() -> ExitCode {let verb = if n == 1 { "is" } else { "are" };eprintln!("{} {verb} in the baseline and not shown.", findings(n));}- if cli.sarif {+ let sarif = (cli.sarif || cli.sarif_file.is_some()).then(|| {let prefix = sarif_prefix(&cli.path);- for f in &mut report.findings {- f.path = format!("{prefix}{}", f.path);+ let paths: Vec<String> = report+ .findings+ .iter_mut()+ .map(|f| {+ let path = format!("{prefix}{}", f.path);+ std::mem::replace(&mut f.path, path)+ })+ .collect();+ let out = serde_json::to_string_pretty(&safe_anything::sarif::render(&report)).unwrap();+ for (f, path) in report.findings.iter_mut().zip(paths) {+ f.path = path;}- println!(- "{}",- serde_json::to_string_pretty(&safe_anything::sarif::render(&report)).unwrap()- );+ out+ });+ if let Some(path) = &cli.sarif_file+ && let Some(sarif) = &sarif+ && let Err(e) = std::fs::write(path, format!("{sarif}\n"))+ {+ eprintln!("error: can't write {}: {e}", path.display());+ return ExitCode::from(2);+ }+ if cli.sarif+ && let Some(sarif) = &sarif+ {+ println!("{sarif}");} else if cli.json {println!("{}", serde_json::to_string_pretty(&report).unwrap());} else {diff --git a/tests/cli.rs b/tests/cli.rsindex e9ab053..bf5f88d 100644--- a/tests/cli.rs+++ b/tests/cli.rs@@ -110,6 +110,66 @@ fn every_rule_has_a_cwe_and_a_reference() {}}+#[test]+fn sarif_file_written_by_the_same_run_as_the_report() {+ let dir = std::env::temp_dir().join(format!("safe-anything-sarif-file-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let file = dir.join("out.sarif");+ let file = file.to_str().unwrap();+ let (_, sarif) = run(&[+ &fixture("code"),+ "--offline",+ "--sarif",+ "--fail-on",+ "never",+ ]);+ // The terminal report on stdout, SARIF in the file, and --fail-on applied.+ let (code, out) = run(&[&fixture("code"), "--offline", "--sarif-file", file]);+ assert_eq!(code, 1);+ assert!(out.contains("findings"), "{out}");+ assert_eq!(std::fs::read_to_string(file).unwrap(), sarif);+ // --severity filters both outputs the same way, and --json still works.+ let (_, sarif) = run(&[+ &fixture("code"),+ "--offline",+ "--sarif",+ "--severity",+ "critical",+ ]);+ let (code, out) = run(&[+ &fixture("code"),+ "--offline",+ "--json",+ "--severity",+ "critical",+ "--fail-on",+ "never",+ "--sarif-file",+ file,+ ]);+ assert_eq!(code, 0);+ let report: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");+ let written: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(file).unwrap()).unwrap();+ assert_eq!(+ written["runs"][0]["results"].as_array().unwrap().len(),+ report["findings"].as_array().unwrap().len()+ );+ assert_eq!(std::fs::read_to_string(file).unwrap(), sarif);+ // A file that can't be written is an error, not a silent success.+ let missing = dir.join("no-such-dir").join("out.sarif");+ let (code, _) = run(&[+ &fixture("code"),+ "--offline",+ "--fail-on",+ "never",+ "--sarif-file",+ missing.to_str().unwrap(),+ ]);+ assert_eq!(code, 2);+ std::fs::remove_dir_all(&dir).unwrap();+}+#[test]fn sarif_output_for_code_scanning() {let (_, out) = run(&[&fixture("code"), "--sarif", "--offline"]);@@ -196,6 +256,20 @@ fn sarif_paths_are_relative_to_the_working_directory() {// 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}");+ let file = dir.join("out.sarif");+ let out = Command::new(env!("CARGO_BIN_EXE_safe-anything"))+ .args(["app", "--offline", "--fail-on", "never", "--sarif-file"])+ .arg(&file)+ .current_dir(&dir)+ .output()+ .unwrap();+ assert!(String::from_utf8_lossy(&out.stdout).contains(" src/x.js:1 "));+ let sarif: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();+ assert_eq!(+ sarif["runs"][0]["results"][0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],+ "app/src/x.js"+ );std::fs::remove_dir_all(&dir).unwrap();}