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: scan engine with parallel walker and suppression

Kamc256977dce5d
diff --git a/src/engine.rs b/src/engine.rs
new file mode 100644
index 0000000..af333fc
--- /dev/null
+++ b/src/engine.rs
@@ -0,0 +1,110 @@
+use std::path::Path;
+use std::sync::Mutex;
+
+use ignore::{WalkBuilder, WalkState};
+
+use crate::Finding;
+use crate::deps::{self, Package};
+use crate::rules::{self, FileInfo};
+
+const MAX_BYTES: u64 = 2 * 1024 * 1024;
+const SKIP_DIRS: &[&str] = &[
+ ".git",
+ "node_modules",
+ "target",
+ "vendor",
+ "dist",
+ "build",
+ ".next",
+ ".venv",
+ "venv",
+ "__pycache__",
+ "Pods",
+ ".gradle",
+];
+
+pub struct Scanned {
+ pub files: usize,
+ pub findings: Vec<Finding>,
+ pub packages: Vec<Package>,
+}
+
+pub fn scan_files(root: &Path, include_tests: bool) -> Scanned {
+ let out = Mutex::new(Scanned {
+ files: 0,
+ findings: Vec::new(),
+ packages: Vec::new(),
+ });
+ let single_file = root.is_file();
+ let base = if single_file {
+ root.parent().unwrap_or(Path::new(".")).to_path_buf()
+ } else {
+ root.to_path_buf()
+ };
+ WalkBuilder::new(root)
+ .hidden(false)
+ .git_ignore(true)
+ .git_global(false)
+ .require_git(false)
+ .add_custom_ignore_filename(".safe-anything-ignore")
+ .filter_entry(|e| {
+ if !e.file_type().is_some_and(|t| t.is_dir()) {
+ return true;
+ }
+ let name = e.file_name().to_string_lossy();
+ let agent_copy = name == "worktrees"
+ && e.path()
+ .parent()
+ .and_then(|p| p.file_name())
+ .is_some_and(|p| p == ".claude");
+ !(SKIP_DIRS.contains(&name.as_ref()) || agent_copy)
+ })
+ .build_parallel()
+ .run(|| {
+ let out = &out;
+ let base = &base;
+ Box::new(move |entry| {
+ let Ok(entry) = entry else {
+ return WalkState::Continue;
+ };
+ if !entry.file_type().is_some_and(|t| t.is_file()) {
+ return WalkState::Continue;
+ }
+ let path = entry.path();
+ if entry.metadata().map(|m| m.len()).unwrap_or(0) > MAX_BYTES {
+ return WalkState::Continue;
+ }
+ let Ok(bytes) = std::fs::read(path) else {
+ return WalkState::Continue;
+ };
+ if bytes[..bytes.len().min(8192)].contains(&0) {
+ return WalkState::Continue;
+ }
+ let text = String::from_utf8_lossy(&bytes);
+ let rel = path
+ .strip_prefix(base)
+ .unwrap_or(path)
+ .to_string_lossy()
+ .replace('\\', "/");
+ let info = FileInfo::new(&rel);
+ if info.name.ends_with(".min.js") || info.ext_in(&["map", "jsonl", "log"]) {
+ return WalkState::Continue;
+ }
+ let findings = if info.ext == "lock" {
+ Vec::new()
+ } else {
+ rules::check(&info, &text, include_tests)
+ };
+ let packages = deps::parse_lockfile(&info, &text);
+ let mut out = out.lock().unwrap();
+ out.files += 1;
+ out.findings.extend(findings);
+ out.packages.extend(packages);
+ WalkState::Continue
+ })
+ });
+ let mut scanned = out.into_inner().unwrap();
+ scanned.packages.sort();
+ scanned.packages.dedup();
+ scanned
+}
diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644
index 0000000..6a680e6
--- /dev/null
+++ b/src/lib.rs
@@ -0,0 +1,234 @@
+pub mod deps;
+mod engine;
+pub mod mcp;
+mod refs;
+pub mod report;
+mod rules;
+pub mod sarif;
+
+use std::path::Path;
+
+use serde::Serialize;
+
+pub use deps::{Advisories, Advisory, OsvClient, Package};
+
+#[derive(Serialize)]
+pub struct RuleInfo {
+ pub id: &'static str,
+ pub family: Family,
+ pub severity: Severity,
+ pub message: &'static str,
+ pub cwe: &'static str,
+ pub owasp: &'static str,
+ pub learn_more: &'static str,
+}
+
+impl RuleInfo {
+ fn new(id: &'static str, family: Family, severity: Severity, message: &'static str) -> Self {
+ let r = refs::of(id);
+ Self {
+ id,
+ family,
+ severity,
+ message,
+ cwe: r.cwe,
+ owasp: r.owasp,
+ learn_more: r.learn_more,
+ }
+ }
+}
+
+pub fn rules() -> Vec<RuleInfo> {
+ let mut seen = std::collections::HashSet::new();
+ rules::all()
+ .filter(|r| seen.insert(r.id))
+ .map(|r| RuleInfo::new(r.id, r.family, r.severity, r.message))
+ .chain(
+ rules::agent::STRUCTURED
+ .iter()
+ .map(|&(id, severity, message)| {
+ RuleInfo::new(id, Family::Agent, severity, message)
+ }),
+ )
+ .chain(std::iter::once(RuleInfo::new(
+ "dependency.known-vulnerability",
+ Family::Dependency,
+ Severity::High,
+ "A locked dependency version has a published advisory (OSV.dev).",
+ )))
+ .collect()
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Severity {
+ Low,
+ Medium,
+ High,
+ Critical,
+}
+
+impl Severity {
+ pub fn parse(s: &str) -> Option<Self> {
+ match s.to_ascii_lowercase().as_str() {
+ "low" => Some(Self::Low),
+ "medium" => Some(Self::Medium),
+ "high" => Some(Self::High),
+ "critical" => Some(Self::Critical),
+ _ => None,
+ }
+ }
+
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Low => "low",
+ Self::Medium => "medium",
+ Self::High => "high",
+ Self::Critical => "critical",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Family {
+ Code,
+ Secret,
+ Agent,
+ Mobile,
+ Config,
+ Dependency,
+}
+
+impl Family {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Code => "code",
+ Self::Secret => "secret",
+ Self::Agent => "agent",
+ Self::Mobile => "mobile",
+ Self::Config => "config",
+ Self::Dependency => "dependency",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct Finding {
+ pub rule: String,
+ pub family: Family,
+ pub severity: Severity,
+ pub path: String,
+ pub line: usize,
+ pub message: String,
+ pub fix: String,
+ pub snippet: String,
+ pub cwe: String,
+ pub owasp: String,
+ pub learn_more: String,
+}
+
+impl Finding {
+ #[allow(clippy::too_many_arguments)]
+ pub(crate) fn new(
+ rule: &str,
+ family: Family,
+ severity: Severity,
+ path: String,
+ line: usize,
+ message: String,
+ fix: String,
+ snippet: String,
+ ) -> Self {
+ let r = refs::of(rule);
+ Self {
+ rule: rule.to_string(),
+ family,
+ severity,
+ path,
+ line,
+ message,
+ fix,
+ snippet,
+ cwe: r.cwe.to_string(),
+ owasp: r.owasp.to_string(),
+ learn_more: r.learn_more.to_string(),
+ }
+ }
+}
+
+#[derive(Debug, Default, Serialize)]
+pub struct Report {
+ pub findings: Vec<Finding>,
+ pub files_scanned: usize,
+ pub packages_checked: usize,
+ pub elapsed_ms: u64,
+ pub dependency_check: DependencyCheck,
+}
+
+#[derive(Debug, Default, Clone, Serialize)]
+#[serde(rename_all = "snake_case", tag = "status", content = "detail")]
+pub enum DependencyCheck {
+ #[default]
+ Skipped,
+ Done,
+ Failed(String),
+}
+
+pub struct Options {
+ pub advisories: Option<Box<dyn Advisories>>,
+ pub include_tests: bool,
+}
+
+impl Options {
+ pub fn offline() -> Self {
+ Self {
+ advisories: None,
+ include_tests: false,
+ }
+ }
+
+ pub fn online() -> Self {
+ Self {
+ advisories: Some(Box::new(OsvClient::default())),
+ include_tests: false,
+ }
+ }
+}
+
+pub fn scan(root: &Path, options: &Options) -> std::io::Result<Report> {
+ if !root.exists() {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::NotFound,
+ format!("{} does not exist", root.display()),
+ ));
+ }
+ let started = std::time::Instant::now();
+ let scanned = engine::scan_files(root, options.include_tests);
+ let mut report = Report {
+ files_scanned: scanned.files,
+ packages_checked: scanned.packages.len(),
+ findings: scanned.findings,
+ ..Report::default()
+ };
+ if let Some(source) = &options.advisories {
+ if scanned.packages.is_empty() {
+ report.dependency_check = DependencyCheck::Done;
+ } else {
+ match source.lookup(&scanned.packages) {
+ Ok(found) => {
+ report
+ .findings
+ .extend(deps::findings(&scanned.packages, found));
+ report.dependency_check = DependencyCheck::Done;
+ }
+ Err(e) => report.dependency_check = DependencyCheck::Failed(e),
+ }
+ }
+ }
+ report.elapsed_ms = started.elapsed().as_millis() as u64;
+ report
+ .findings
+ .sort_by(|a, b| (&a.path, a.line, &a.rule).cmp(&(&b.path, b.line, &b.rule)));
+ Ok(report)
+}
diff --git a/src/refs.rs b/src/refs.rs
new file mode 100644
index 0000000..2d8dc5e
--- /dev/null
+++ b/src/refs.rs
@@ -0,0 +1,240 @@
+pub struct Refs {
+ pub cwe: &'static str,
+ pub owasp: &'static str,
+ pub learn_more: &'static str,
+}
+
+macro_rules! r {
+ ($cwe:literal, $owasp:literal, $sheet:literal) => {
+ Refs {
+ cwe: $cwe,
+ owasp: $owasp,
+ learn_more: concat!(
+ "https://cheatsheetseries.owasp.org/cheatsheets/",
+ $sheet,
+ ".html"
+ ),
+ }
+ };
+ ($cwe:literal, $owasp:literal, url $url:literal) => {
+ Refs {
+ cwe: $cwe,
+ owasp: $owasp,
+ learn_more: $url,
+ }
+ };
+}
+
+pub fn of(id: &str) -> Refs {
+ match id {
+ "code.xss-inner-html"
+ | "code.xss-document-write"
+ | "code.xss-dangerously-set-inner-html"
+ | "code.xss-v-html"
+ | "code.xss-reflected"
+ | "code.xss-raw-html" => {
+ r!(
+ "CWE-79",
+ "A03:2021 Injection",
+ "Cross_Site_Scripting_Prevention_Cheat_Sheet"
+ )
+ }
+ "code.eval" => r!(
+ "CWE-95",
+ "A03:2021 Injection",
+ "Injection_Prevention_Cheat_Sheet"
+ ),
+ "code.command-injection" => r!(
+ "CWE-78",
+ "A03:2021 Injection",
+ "OS_Command_Injection_Defense_Cheat_Sheet"
+ ),
+ "code.sql-injection" => r!(
+ "CWE-89",
+ "A03:2021 Injection",
+ "SQL_Injection_Prevention_Cheat_Sheet"
+ ),
+ "code.path-traversal" | "code.file-inclusion" => r!(
+ "CWE-22",
+ "A01:2021 Broken Access Control",
+ "File_Upload_Cheat_Sheet"
+ ),
+ "code.ssrf" => r!(
+ "CWE-918",
+ "A10:2021 Server-Side Request Forgery",
+ "Server_Side_Request_Forgery_Prevention_Cheat_Sheet"
+ ),
+ "code.tls-verify-off" => r!(
+ "CWE-295",
+ "A02:2021 Cryptographic Failures",
+ "Transport_Layer_Security_Cheat_Sheet"
+ ),
+ "code.weak-hash" => r!(
+ "CWE-328",
+ "A02:2021 Cryptographic Failures",
+ "Password_Storage_Cheat_Sheet"
+ ),
+ "code.weak-cipher" => r!(
+ "CWE-327",
+ "A02:2021 Cryptographic Failures",
+ "Cryptographic_Storage_Cheat_Sheet"
+ ),
+ "code.insecure-cookie" => r!(
+ "CWE-614",
+ "A05:2021 Security Misconfiguration",
+ "Session_Management_Cheat_Sheet"
+ ),
+ "code.jwt-none" => r!(
+ "CWE-347",
+ "A07:2021 Identification and Authentication Failures",
+ "JSON_Web_Token_Cheat_Sheet"
+ ),
+ "code.cors-wildcard" => r!(
+ "CWE-942",
+ "A05:2021 Security Misconfiguration",
+ "HTML5_Security_Cheat_Sheet"
+ ),
+ "code.insecure-random" => r!(
+ "CWE-338",
+ "A02:2021 Cryptographic Failures",
+ "Cryptographic_Storage_Cheat_Sheet"
+ ),
+ "code.debug-enabled" => r!(
+ "CWE-489",
+ "A05:2021 Security Misconfiguration",
+ "Error_Handling_Cheat_Sheet"
+ ),
+ "code.template-injection" => r!(
+ "CWE-1336",
+ "A03:2021 Injection",
+ "Injection_Prevention_Cheat_Sheet"
+ ),
+ "code.unsafe-deserialization" => r!(
+ "CWE-502",
+ "A08:2021 Software and Data Integrity Failures",
+ "Deserialization_Cheat_Sheet"
+ ),
+ "code.sql-grant-all" => r!(
+ "CWE-250",
+ "A01:2021 Broken Access Control",
+ "Database_Security_Cheat_Sheet"
+ ),
+ "code.sql-plaintext-password" => r!(
+ "CWE-798",
+ "A07:2021 Identification and Authentication Failures",
+ "Database_Security_Cheat_Sheet"
+ ),
+ "secret.env-file" | "secret.hardcoded-password" | "secret.url-credentials" => {
+ r!(
+ "CWE-798",
+ "A07:2021 Identification and Authentication Failures",
+ "Secrets_Management_Cheat_Sheet"
+ )
+ }
+ "secret.private-key" => r!(
+ "CWE-321",
+ "A02:2021 Cryptographic Failures",
+ "Key_Management_Cheat_Sheet"
+ ),
+ s if s.starts_with("secret.") => r!(
+ "CWE-798",
+ "A07:2021 Identification and Authentication Failures",
+ "Secrets_Management_Cheat_Sheet"
+ ),
+ "agent.bypass-permissions" | "agent.unrestricted-shell" => {
+ r!("CWE-250", "LLM06:2025 Excessive Agency", url "https://genai.owasp.org/llmrisk/llm062025-excessive-agency/")
+ }
+ "agent.remote-script" => {
+ r!("CWE-494", "LLM03:2025 Supply Chain", url "https://genai.owasp.org/llmrisk/llm032025-supply-chain/")
+ }
+ "agent.mcp-unpinned" => {
+ r!("CWE-1357", "LLM03:2025 Supply Chain", url "https://genai.owasp.org/llmrisk/llm032025-supply-chain/")
+ }
+ "agent.prompt-injection" | "agent.hidden-unicode" => {
+ r!("CWE-1427", "LLM01:2025 Prompt Injection", url "https://genai.owasp.org/llmrisk/llm01-prompt-injection/")
+ }
+ "agent.sensitive-file-access" => {
+ r!("CWE-200", "LLM02:2025 Sensitive Information Disclosure", url "https://genai.owasp.org/llmrisk/llm022025-sensitive-information-disclosure/")
+ }
+ "agent.mcp-plaintext-secret" => r!(
+ "CWE-798",
+ "LLM02:2025 Sensitive Information Disclosure",
+ "Secrets_Management_Cheat_Sheet"
+ ),
+ "agent.mcp-insecure-url" => r!(
+ "CWE-319",
+ "A02:2021 Cryptographic Failures",
+ "Transport_Layer_Security_Cheat_Sheet"
+ ),
+ "mobile.android-debuggable" => {
+ r!("CWE-489", "MASVS-RESILIENCE", url "https://mas.owasp.org/MASVS/11-MASVS-RESILIENCE/")
+ }
+ "mobile.android-allow-backup" | "mobile.insecure-storage" | "mobile.world-readable" => {
+ r!("CWE-922", "MASVS-STORAGE", url "https://mas.owasp.org/MASVS/05-MASVS-STORAGE/")
+ }
+ "mobile.android-cleartext" | "mobile.ios-ats-disabled" => {
+ r!("CWE-319", "MASVS-NETWORK", url "https://mas.owasp.org/MASVS/08-MASVS-NETWORK/")
+ }
+ "mobile.android-exported-provider" => {
+ r!("CWE-926", "MASVS-PLATFORM", url "https://mas.owasp.org/MASVS/09-MASVS-PLATFORM/")
+ }
+ "mobile.webview-js-bridge" | "mobile.webview-file-access" => {
+ r!("CWE-749", "MASVS-PLATFORM", url "https://mas.owasp.org/MASVS/09-MASVS-PLATFORM/")
+ }
+ "config.remote-script" | "config.docker-add-url" => r!(
+ "CWE-494",
+ "A08:2021 Software and Data Integrity Failures",
+ "Software_Supply_Chain_Security_Cheat_Sheet"
+ ),
+ "config.docker-unpinned-image" => r!(
+ "CWE-1357",
+ "A06:2021 Vulnerable and Outdated Components",
+ "Docker_Security_Cheat_Sheet"
+ ),
+ "config.docker-secret-env" => r!(
+ "CWE-798",
+ "A05:2021 Security Misconfiguration",
+ "Docker_Security_Cheat_Sheet"
+ ),
+ "config.docker-root-user" | "config.privileged-container" | "config.k8s-host-access" => {
+ r!(
+ "CWE-250",
+ "A05:2021 Security Misconfiguration",
+ "Kubernetes_Security_Cheat_Sheet"
+ )
+ }
+ "config.gha-pull-request-target"
+ | "config.gha-write-all"
+ | "config.gha-unpinned-action" => {
+ r!(
+ "CWE-829",
+ "A08:2021 Software and Data Integrity Failures",
+ "CI_CD_Security_Cheat_Sheet"
+ )
+ }
+ "config.gha-script-injection" => {
+ r!("CWE-78", "A03:2021 Injection", "CI_CD_Security_Cheat_Sheet")
+ }
+ "config.tf-open-ingress" | "config.tf-public-bucket" => r!(
+ "CWE-284",
+ "A01:2021 Broken Access Control",
+ "Infrastructure_as_Code_Security_Cheat_Sheet"
+ ),
+ "config.nginx-autoindex" => r!(
+ "CWE-548",
+ "A05:2021 Security Misconfiguration",
+ "Attack_Surface_Analysis_Cheat_Sheet"
+ ),
+ "config.weak-tls-version" => r!(
+ "CWE-326",
+ "A02:2021 Cryptographic Failures",
+ "Transport_Layer_Security_Cheat_Sheet"
+ ),
+ "dependency.known-vulnerability" => r!(
+ "CWE-1395",
+ "A06:2021 Vulnerable and Outdated Components",
+ "Vulnerable_Dependency_Management_Cheat_Sheet"
+ ),
+ _ => r!("CWE-710", "", url "https://cwe.mitre.org/"),
+ }
+}
diff --git a/src/rules.rs b/src/rules.rs
new file mode 100644
index 0000000..2118721
--- /dev/null
+++ b/src/rules.rs
@@ -0,0 +1,253 @@
+use std::sync::LazyLock;
+
+use regex::Regex;
+
+use crate::{Family, Finding, Severity};
+
+pub mod agent;
+mod code;
+mod config;
+mod mobile;
+mod secrets;
+
+pub struct FileInfo {
+ pub rel: String,
+ pub name: String,
+ pub ext: String,
+}
+
+impl FileInfo {
+ pub fn new(rel: &str) -> Self {
+ let name = rel.rsplit('/').next().unwrap_or(rel).to_ascii_lowercase();
+ let ext = name
+ .rsplit_once('.')
+ .map(|(_, e)| e.to_string())
+ .unwrap_or_default();
+ Self {
+ rel: rel.to_string(),
+ name,
+ ext,
+ }
+ }
+
+ pub fn ext_in(&self, exts: &[&str]) -> bool {
+ exts.contains(&self.ext.as_str())
+ }
+
+ pub fn is_test(&self) -> bool {
+ const DIRS: &[&str] = &[
+ "test",
+ "tests",
+ "__tests__",
+ "spec",
+ "specs",
+ "cypress",
+ "e2e",
+ "fixtures",
+ "__mocks__",
+ "testdata",
+ "mocks",
+ ];
+ let mut parts = self.rel.split('/');
+ parts.next_back();
+ parts.any(|p| DIRS.contains(&p.to_ascii_lowercase().as_str()))
+ || [".spec.", ".test.", "_test.", "_spec.", ".cy."]
+ .iter()
+ .any(|m| self.name.contains(m))
+ || self.name.starts_with("test_")
+ }
+
+ pub fn under(&self, dir: &str) -> bool {
+ self.rel.starts_with(dir) || self.rel.contains(&format!("/{dir}"))
+ }
+}
+
+pub struct Rule {
+ pub id: &'static str,
+ pub family: Family,
+ pub severity: Severity,
+ pub files: fn(&FileInfo) -> bool,
+ pub pattern: &'static str,
+ pub unless: Option<&'static str>,
+ pub message: &'static str,
+ pub fix: &'static str,
+}
+
+struct Compiled {
+ rule: &'static Rule,
+ re: Regex,
+ unless: Option<Regex>,
+}
+
+static RULES: LazyLock<Vec<Compiled>> = LazyLock::new(|| {
+ [
+ code::RULES,
+ secrets::RULES,
+ agent::RULES,
+ mobile::RULES,
+ config::RULES,
+ ]
+ .into_iter()
+ .flatten()
+ .map(|rule| Compiled {
+ rule,
+ re: Regex::new(rule.pattern).unwrap_or_else(|e| panic!("{}: {e}", rule.id)),
+ unless: rule
+ .unless
+ .map(|u| Regex::new(u).unwrap_or_else(|e| panic!("{} unless: {e}", rule.id))),
+ })
+ .collect()
+});
+
+pub fn all() -> impl Iterator<Item = &'static Rule> {
+ RULES.iter().map(|c| c.rule)
+}
+
+pub struct Text<'a> {
+ pub src: &'a str,
+ starts: Vec<usize>,
+}
+
+impl<'a> Text<'a> {
+ pub fn new(src: &'a str) -> Self {
+ let mut starts = vec![0];
+ starts.extend(src.match_indices('\n').map(|(i, _)| i + 1));
+ Self { src, starts }
+ }
+
+ pub fn line_of(&self, offset: usize) -> usize {
+ self.starts.partition_point(|&s| s <= offset)
+ }
+
+ pub fn line(&self, n: usize) -> &'a str {
+ let start = self.starts[n - 1];
+ let end = self.starts.get(n).map(|e| e - 1).unwrap_or(self.src.len());
+ self.src[start..end].trim_end_matches('\r')
+ }
+
+ pub fn suppressed(&self, n: usize) -> bool {
+ const MARK: &str = "safe-anything:ignore";
+ self.line(n).contains(MARK) || (n > 1 && self.line(n - 1).contains(MARK))
+ }
+}
+
+pub struct Meta<'a> {
+ pub id: &'a str,
+ pub family: Family,
+ pub severity: Severity,
+ pub message: &'a str,
+ pub fix: &'a str,
+ pub secret: Option<&'a str>,
+}
+
+pub fn finding(file: &FileInfo, text: &Text, line: usize, meta: Meta) -> Finding {
+ let raw = text.line(line).trim();
+ let snippet = match meta.secret {
+ Some(secret) if !secret.is_empty() => shorten(&raw.replace(secret, &mask(secret))),
+ _ => shorten(raw),
+ };
+ Finding::new(
+ meta.id,
+ meta.family,
+ meta.severity,
+ file.rel.clone(),
+ line,
+ meta.message.to_string(),
+ meta.fix.to_string(),
+ snippet,
+ )
+}
+
+fn shorten(s: &str) -> String {
+ if s.chars().count() > 160 {
+ format!("{}…", s.chars().take(160).collect::<String>())
+ } else {
+ s.to_string()
+ }
+}
+
+fn mask(secret: &str) -> String {
+ let keep: String = secret.chars().take(4).collect();
+ format!("{keep}****")
+}
+
+pub fn check(file: &FileInfo, src: &str, include_tests: bool) -> Vec<Finding> {
+ let text = Text::new(src);
+ let test_file = !include_tests && file.is_test();
+ let mut out = Vec::new();
+ let mut seen = std::collections::HashSet::new();
+ for c in RULES.iter() {
+ if !(c.rule.files)(file) {
+ continue;
+ }
+ if test_file && !(c.rule.family == Family::Secret && c.rule.severity == Severity::Critical)
+ {
+ continue;
+ }
+ for caps in c.re.captures_iter(src) {
+ let m = caps.get(0).expect("whole match");
+ let secret = (c.rule.family == Family::Secret).then(|| {
+ caps.iter()
+ .skip(1)
+ .flatten()
+ .last()
+ .unwrap_or(m)
+ .as_str()
+ .lines()
+ .next()
+ .unwrap_or("")
+ });
+ let line = text.line_of(m.start());
+ if text.suppressed(line) {
+ continue;
+ }
+ if c.rule.family == Family::Code
+ && (is_comment(text.line(line)) || is_prose(text.line(line)))
+ {
+ continue;
+ }
+ if let Some(unless) = &c.unless {
+ if unless.is_match(text.line(line)) {
+ continue;
+ }
+ }
+ if seen.insert((c.rule.id.to_string(), line)) {
+ out.push(finding(
+ file,
+ &text,
+ line,
+ Meta {
+ id: c.rule.id,
+ family: c.rule.family,
+ severity: c.rule.severity,
+ message: c.rule.message,
+ fix: c.rule.fix,
+ secret,
+ },
+ ));
+ }
+ }
+ }
+ out.retain(|f| config::keep(file, &text, f));
+ for f in agent::structured(file, &text)
+ .into_iter()
+ .filter(|_| !test_file)
+ {
+ if !text.suppressed(f.line) && seen.insert((f.rule.clone(), f.line)) {
+ out.push(f);
+ }
+ }
+ out
+}
+
+fn is_comment(line: &str) -> bool {
+ let t = line.trim_start();
+ ["//", "#", "/*", "* ", "--", "<!--"]
+ .iter()
+ .any(|p| t.starts_with(p))
+ || t == "*"
+}
+
+fn is_prose(line: &str) -> bool {
+ line.contains("**") || line.contains('⚠') || line.contains("\\b")
+}