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: terminal, JSON and SARIF output

Kam708d0e0e1793
diff --git a/src/main.rs b/src/main.rs
new file mode 100644
index 0000000..e851efa
--- /dev/null
+++ b/src/main.rs
@@ -0,0 +1,114 @@
+use std::io::IsTerminal;
+use std::path::PathBuf;
+use std::process::ExitCode;
+
+use clap::Parser;
+use safe_anything::{Options, Severity, report};
+
+#[derive(Parser)]
+#[command(
+ version,
+ about = "Find vulnerabilities in any app, and in the AI agent setup that builds it."
+)]
+struct Cli {
+ /// Folder or file to scan
+ #[arg(default_value = ".")]
+ path: PathBuf,
+ /// Print the report as JSON
+ #[arg(long, conflicts_with = "sarif")]
+ json: bool,
+ /// Print the report as SARIF 2.1.0 (GitHub code scanning)
+ #[arg(long)]
+ sarif: bool,
+ /// Skip the dependency check (no network)
+ #[arg(long)]
+ offline: bool,
+ /// Lowest severity to report: low, medium, high, critical
+ #[arg(long, default_value = "low", value_parser = parse_severity)]
+ severity: Severity,
+ /// Exit with 1 when a finding is at least this severe: low, medium, high, critical, never
+ #[arg(long, default_value = "high")]
+ fail_on: String,
+ /// Also report findings in test, spec and fixture files (by default only real tokens and keys count there)
+ #[arg(long)]
+ include_tests: bool,
+ /// List every rule and exit
+ #[arg(long)]
+ list_rules: bool,
+}
+
+fn parse_severity(s: &str) -> Result<Severity, String> {
+ Severity::parse(s)
+ .ok_or_else(|| format!("unknown severity `{s}` (low, medium, high, critical)"))
+}
+
+fn main() -> ExitCode {
+ if std::env::args().nth(1).as_deref() == Some("mcp") {
+ return match safe_anything::mcp::serve() {
+ Ok(()) => ExitCode::SUCCESS,
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::from(2)
+ }
+ };
+ }
+ let cli = Cli::parse();
+ if cli.list_rules {
+ let rules = safe_anything::rules();
+ if cli.json {
+ println!("{}", serde_json::to_string_pretty(&rules).unwrap());
+ } else {
+ for r in rules {
+ println!(
+ "{:<36} {:<9} {:<9} {}",
+ r.id,
+ r.severity.as_str(),
+ r.cwe,
+ r.message
+ );
+ }
+ }
+ return ExitCode::SUCCESS;
+ }
+ let fail_on = match cli.fail_on.as_str() {
+ "never" => None,
+ s => match Severity::parse(s) {
+ Some(s) => Some(s),
+ None => {
+ eprintln!("error: unknown --fail-on `{s}` (low, medium, high, critical, never)");
+ return ExitCode::from(2);
+ }
+ },
+ };
+ let mut options = if cli.offline {
+ Options::offline()
+ } else {
+ Options::online()
+ };
+ options.include_tests = cli.include_tests;
+ let mut report = match safe_anything::scan(&cli.path, &options) {
+ Ok(r) => r,
+ Err(e) => {
+ eprintln!("error: {e}");
+ return ExitCode::from(2);
+ }
+ };
+ report.findings.retain(|f| f.severity >= cli.severity);
+ if cli.sarif {
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&safe_anything::sarif::render(&report)).unwrap()
+ );
+ } else if cli.json {
+ println!("{}", serde_json::to_string_pretty(&report).unwrap());
+ } else {
+ let color = std::io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none();
+ print!("{}", report::terminal(&report, &report::Style { color }));
+ }
+ let failed = fail_on.is_some_and(|t| report.findings.iter().any(|f| f.severity >= t));
+ if failed {
+ ExitCode::from(1)
+ } else {
+ ExitCode::SUCCESS
+ }
+}
diff --git a/src/report.rs b/src/report.rs
new file mode 100644
index 0000000..64dd77f
--- /dev/null
+++ b/src/report.rs
@@ -0,0 +1,116 @@
+use std::fmt::Write;
+
+use crate::{DependencyCheck, Report, Severity};
+
+pub struct Style {
+ pub color: bool,
+}
+
+impl Style {
+ fn paint(&self, code: &str, s: &str) -> String {
+ if self.color {
+ format!("\x1b[{code}m{s}\x1b[0m")
+ } else {
+ s.to_string()
+ }
+ }
+
+ fn severity(&self, s: Severity) -> String {
+ let label = format!("{:<8}", s.as_str().to_uppercase());
+ match s {
+ Severity::Critical => self.paint("1;35", &label),
+ Severity::High => self.paint("1;31", &label),
+ Severity::Medium => self.paint("33", &label),
+ Severity::Low => self.paint("36", &label),
+ }
+ }
+}
+
+pub fn terminal(report: &Report, style: &Style) -> String {
+ let mut out = String::new();
+ let mut findings: Vec<_> = report.findings.iter().collect();
+ findings.sort_by(|a, b| {
+ b.severity
+ .cmp(&a.severity)
+ .then((&a.path, a.line).cmp(&(&b.path, b.line)))
+ });
+ for f in &findings {
+ let _ = writeln!(
+ out,
+ "{} {} {}",
+ style.severity(f.severity),
+ style.paint("1", &format!("{}:{}", f.path, f.line)),
+ style.paint("2", &f.rule)
+ );
+ let _ = writeln!(out, " {}", f.message);
+ if !f.snippet.is_empty() {
+ let _ = writeln!(
+ out,
+ " {}",
+ style.paint("2", &format!("> {}", f.snippet))
+ );
+ }
+ let _ = writeln!(out, " {} {}\n", style.paint("32", "Fix:"), f.fix);
+ }
+ let count = |s: Severity| findings.iter().filter(|f| f.severity == s).count();
+ if findings.is_empty() {
+ let _ = writeln!(out, "{}", style.paint("1;32", "No problems found."));
+ } else {
+ let parts: Vec<String> = [
+ Severity::Critical,
+ Severity::High,
+ Severity::Medium,
+ Severity::Low,
+ ]
+ .into_iter()
+ .filter(|&s| count(s) > 0)
+ .map(|s| format!("{} {}", count(s), s.as_str()))
+ .collect();
+ let _ = writeln!(
+ out,
+ "{} {}",
+ style.paint(
+ "1",
+ &format!(
+ "{} finding{}:",
+ findings.len(),
+ if findings.len() == 1 { "" } else { "s" }
+ )
+ ),
+ parts.join(", ")
+ );
+ }
+ let deps = match &report.dependency_check {
+ DependencyCheck::Skipped => "skipped (offline)".to_string(),
+ DependencyCheck::Done => format!(
+ "{} packages checked against OSV.dev",
+ report.packages_checked
+ ),
+ DependencyCheck::Failed(e) => format!("failed: {e}"),
+ };
+ let _ = writeln!(
+ out,
+ "{}",
+ style.paint(
+ "2",
+ &format!(
+ "Scanned {} files in {:.2} s. Dependencies: {deps}.",
+ thousands(report.files_scanned),
+ report.elapsed_ms as f64 / 1000.0
+ )
+ )
+ );
+ out
+}
+
+fn thousands(n: usize) -> String {
+ let s = n.to_string();
+ let mut out = String::new();
+ for (i, c) in s.chars().enumerate() {
+ if i > 0 && (s.len() - i) % 3 == 0 {
+ out.push(',');
+ }
+ out.push(c);
+ }
+ out
+}
diff --git a/src/sarif.rs b/src/sarif.rs
new file mode 100644
index 0000000..a8bcfa5
--- /dev/null
+++ b/src/sarif.rs
@@ -0,0 +1,74 @@
+use std::collections::BTreeSet;
+
+use serde_json::{Value, json};
+
+use crate::{Report, Severity};
+
+fn level(s: Severity) -> &'static str {
+ match s {
+ Severity::Critical | Severity::High => "error",
+ Severity::Medium => "warning",
+ Severity::Low => "note",
+ }
+}
+
+fn score(s: Severity) -> &'static str {
+ match s {
+ Severity::Critical => "9.5",
+ Severity::High => "8.0",
+ Severity::Medium => "5.5",
+ Severity::Low => "3.0",
+ }
+}
+
+pub fn render(report: &Report) -> Value {
+ let used: BTreeSet<&str> = report.findings.iter().map(|f| f.rule.as_str()).collect();
+ let rules: Vec<Value> = crate::rules()
+ .into_iter()
+ .filter(|r| used.contains(r.id))
+ .map(|r| {
+ json!({
+ "id": r.id,
+ "name": r.id,
+ "shortDescription": { "text": r.message },
+ "helpUri": r.learn_more,
+ "defaultConfiguration": { "level": level(r.severity) },
+ "properties": {
+ "tags": ["security", r.family.as_str(), r.cwe, r.owasp],
+ "security-severity": score(r.severity),
+ },
+ })
+ })
+ .collect();
+ let results: Vec<Value> = report
+ .findings
+ .iter()
+ .map(|f| {
+ json!({
+ "ruleId": f.rule,
+ "level": level(f.severity),
+ "message": { "text": format!("{} Fix: {}", f.message, f.fix) },
+ "locations": [{
+ "physicalLocation": {
+ "artifactLocation": { "uri": f.path },
+ "region": { "startLine": f.line },
+ },
+ }],
+ "properties": { "security-severity": score(f.severity) },
+ })
+ })
+ .collect();
+ json!({
+ "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
+ "version": "2.1.0",
+ "runs": [{
+ "tool": { "driver": {
+ "name": "safe-anything",
+ "version": env!("CARGO_PKG_VERSION"),
+ "informationUri": "https://github.com/erkamyaman/safe-anything",
+ "rules": rules,
+ }},
+ "results": results,
+ }],
+ })
+}