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): let safe-anything:ignore name the rules it silences (#116)

Onur Ugur4c6930d3eb76
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c5b53a4..07a037e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -78,6 +78,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: `safe-anything:ignore` takes an optional list of rule ids (`// safe-anything:ignore code.weak-hash, code.eval`)
+ and then silences only those rules on that line and the next. An unknown id silences nothing. A bare marker
+ still silences every rule.
- 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.
diff --git a/README.md b/README.md
index b6234d9..f2861f6 100644
--- a/README.md
+++ b/README.md
@@ -83,7 +83,9 @@ safe-anything --list-rules
`.zip`, `.mp4`, `.class`, ...), and any other file with a zero byte in its first 8 KB. A text file
saved under one of those extensions is not scanned either.
- `*.lock` files get the dependency check but no code rules
-- `safe-anything:ignore` in a comment silences that line (or the next one).
+- `safe-anything:ignore` in a comment silences that line (or the next one). Follow it with rule ids,
+ `// safe-anything:ignore code.weak-hash, code.eval`, to silence only those rules. An id that is no
+ rule (a typo) silences nothing, so the finding stays in the report.
- In tests, specs and fixtures only real provider keys and private keys count, unless you pass
`--include-tests`.
diff --git a/src/rules.rs b/src/rules.rs
index ee6cd83..58dcb68 100644
--- a/src/rules.rs
+++ b/src/rules.rs
@@ -1,3 +1,5 @@
+use std::cell::RefCell;
+use std::collections::HashMap;
use std::sync::LazyLock;
use regex::Regex;
@@ -106,13 +108,20 @@ pub fn all() -> impl Iterator<Item = &'static Rule> {
pub struct Text<'a> {
pub src: &'a str,
starts: Vec<usize>,
+ /// What the `safe-anything:ignore` markers on each line cover, read once per line: a long
+ /// line can hold many findings.
+ marks: RefCell<HashMap<usize, Cover>>,
}
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 }
+ Self {
+ src,
+ starts,
+ marks: RefCell::default(),
+ }
}
pub fn line_of(&self, offset: usize) -> usize {
@@ -129,12 +138,129 @@ impl<'a> Text<'a> {
self.src[start..end].trim_end_matches('\r')
}
- pub fn suppressed(&self, n: usize) -> bool {
+ /// Whether a `safe-anything:ignore` marker on line `n` or the line above covers `rule`.
+ pub fn suppressed(&self, n: usize, rule: &str) -> bool {
+ self.ignores(n, rule) || (n > 1 && self.ignores(n - 1, rule))
+ }
+
+ fn ignores(&self, n: usize, rule: &str) -> bool {
+ self.marks
+ .borrow_mut()
+ .entry(n)
+ .or_insert_with(|| Cover::of(self.line(n)))
+ .covers(rule)
+ }
+}
+
+/// The rules the `safe-anything:ignore` markers on a line cover.
+///
+/// A bare marker covers every rule. A marker followed by rule ids
+/// (`safe-anything:ignore code.weak-hash, code.eval`) covers only the known ones among them, so a
+/// typo like `code.weak-hashh` covers nothing and the finding stays in the report.
+#[derive(Default)]
+struct Cover {
+ all: bool,
+ ids: Vec<&'static str>,
+}
+
+impl Cover {
+ fn of(line: &str) -> Self {
const MARK: &str = "safe-anything:ignore";
- self.line(n).contains(MARK) || (n > 1 && self.line(n - 1).contains(MARK))
+ let mut cover = Self::default();
+ // Splitting at the markers reads each part of the line once, however many it holds.
+ for after in line.split(MARK).skip(1) {
+ match marker_ids(after) {
+ None => {
+ cover.all = true;
+ break;
+ }
+ Some(ids) => {
+ for id in ids {
+ if !cover.ids.contains(&id) {
+ cover.ids.push(id);
+ }
+ }
+ }
+ }
+ }
+ cover
+ }
+
+ fn covers(&self, rule: &str) -> bool {
+ self.all || self.ids.contains(&rule)
}
}
+/// The known rule ids a marker lists, or `None` when it lists none and so is bare. `after` is the
+/// text after the marker, up to the next one.
+///
+/// The list ends at `*/` or `-->` (the rest of the comment is not part of it). It must be set
+/// apart from the marker by whitespace or `:`; `safe-anything:ignore,` is bare. Words are split at
+/// whitespace and commas and read from the start while they look like rule ids (`family.name`);
+/// one trailing `.`, `;` or `:` is dropped and ends the list.
+fn marker_ids(after: &str) -> Option<Vec<&'static str>> {
+ static KNOWN: LazyLock<std::collections::HashSet<&'static str>> =
+ LazyLock::new(|| crate::rules().into_iter().map(|r| r.id).collect());
+ let end = ["*/", "-->", "%>", "*@"]
+ .iter()
+ .filter_map(|closer| after.find(closer))
+ .min()
+ .unwrap_or(after.len());
+ let list = &after[..end];
+ let list = match list.strip_prefix(':') {
+ Some(rest) => rest,
+ None if list.is_empty() || list.starts_with(char::is_whitespace) => list,
+ None => return None,
+ };
+ let mut ids = Vec::new();
+ let mut listed = false;
+ for word in list
+ .split(|c: char| c.is_whitespace() || c == ',')
+ .filter(|w| !w.is_empty())
+ {
+ let (id, last) = match word.strip_suffix(['.', ';', ':']) {
+ Some(id) => (id, true),
+ None => (word, false),
+ };
+ if !looks_like_id(id) {
+ break;
+ }
+ listed = true;
+ if let Some(&known) = KNOWN.get(id) {
+ ids.push(known);
+ }
+ if last {
+ break;
+ }
+ }
+ listed.then_some(ids)
+}
+
+/// `family.name` for one of the rule families, the name starting with a letter or digit and going
+/// on with letters, digits, `_` or `-`. Case and a plural family (`Code.Eval`, `secrets.x`) still
+/// look like an id, so such a typo covers nothing instead of silencing every rule.
+fn looks_like_id(word: &str) -> bool {
+ const FAMILIES: [Family; 6] = [
+ Family::Code,
+ Family::Secret,
+ Family::Agent,
+ Family::Mobile,
+ Family::Config,
+ Family::Dependency,
+ ];
+ let Some((family, name)) = word.split_once('.') else {
+ return false;
+ };
+ let family = family.to_ascii_lowercase();
+ let alnum = |c: char| c.is_ascii_alphanumeric();
+ (family == "dependencies"
+ || FAMILIES
+ .iter()
+ .any(|f| family == f.as_str() || family == format!("{}s", f.as_str())))
+ && name.starts_with(alnum)
+ && name.chars().all(|c| alnum(c) || c == '_' || c == '-')
+}
+
pub struct Meta<'a> {
pub id: &'a str,
pub family: Family,
@@ -236,7 +362,7 @@ pub fn check(file: &FileInfo, src: &str, include_tests: bool) -> Vec<Finding> {
)
};
let line = text.line_of(m.start());
- if text.suppressed(line) {
+ if text.suppressed(line, c.rule.id) {
continue;
}
if c.rule.family == Family::Code
@@ -276,7 +402,7 @@ pub fn check(file: &FileInfo, src: &str, include_tests: bool) -> Vec<Finding> {
.into_iter()
.filter(|_| !test_file)
{
- if !text.suppressed(f.line) && seen.insert((f.rule.clone(), f.line)) {
+ if !text.suppressed(f.line, &f.rule) && seen.insert((f.rule.clone(), f.line)) {
out.push(f);
}
}
@@ -294,3 +420,282 @@ fn is_comment(line: &str) -> bool {
fn is_prose(line: &str) -> bool {
line.contains("**") || line.contains('⚠') || line.contains("\\b")
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn ignore_marker_with_rule_ids() {
+ let cases = [
+ ("x // safe-anything:ignore", "code.eval", true),
+ ("x <!-- safe-anything:ignore -->", "code.eval", true),
+ ("x /* safe-anything:ignore*/", "code.eval", true),
+ (
+ "x /* safe-anything:ignore */ // see code.eval",
+ "code.weak-hash",
+ true,
+ ),
+ (
+ "x // safe-anything:ignore false positive, reviewed",
+ "code.eval",
+ true,
+ ),
+ (
+ "x // safe-anything:ignore not code.eval",
+ "code.weak-hash",
+ true,
+ ),
+ (
+ "x // safe-anything:ignore - code.eval",
+ "code.weak-hash",
+ true,
+ ),
+ // A case or plural typo still looks like an id, so it covers nothing.
+ ("x // safe-anything:ignore Code.Eval", "code.eval", false),
+ (
+ "x // safe-anything:ignore code.weakHash",
+ "code.eval",
+ false,
+ ),
+ (
+ "x // safe-anything:ignore secrets.hardcoded-password",
+ "secret.hardcoded-password",
+ false,
+ ),
+ // ERB and Razor comment closers end the list.
+ (
+ "<%# safe-anything:ignore code.eval%><% eval(x) %>",
+ "code.eval",
+ true,
+ ),
+ (
+ "<%# safe-anything:ignore code.eval%><% eval(x) %>",
+ "code.weak-hash",
+ false,
+ ),
+ ("@* safe-anything:ignore code.eval*@", "code.eval", true),
+ (
+ "x // uses safe-anything:ignore, code.eval is fine",
+ "code.weak-hash",
+ true,
+ ),
+ (
+ "x // safe-anything:ignored code.eval",
+ "code.weak-hash",
+ true,
+ ),
+ ("x // safe-anything:ignorefoo", "code.eval", true),
+ ("x // safe-anything:ignore code.eval", "code.eval", true),
+ (
+ "x // safe-anything:ignore code.eval",
+ "code.weak-hash",
+ false,
+ ),
+ (
+ "x // safe-anything:ignore\tcode.eval",
+ "code.weak-hash",
+ false,
+ ),
+ (
+ "x // safe-anything:ignore code.weak-hash,code.eval",
+ "code.eval",
+ true,
+ ),
+ (
+ "x // safe-anything:ignore code.weak-hash, code.eval",
+ "code.eval",
+ true,
+ ),
+ (
+ "x // safe-anything:ignore code.weak-hash code.eval",
+ "code.weak-hash",
+ true,
+ ),
+ (
+ "x // safe-anything:ignore code.weak-hash code.eval",
+ "secret.aws-access-key",
+ false,
+ ),
+ ("x // safe-anything:ignore: code.eval", "code.eval", true),
+ (
+ "x // safe-anything:ignore: code.eval",
+ "code.weak-hash",
+ false,
+ ),
+ (
+ "x // safe-anything:ignore:code.eval",
+ "code.weak-hash",
+ false,
+ ),
+ (
+ "x // safe-anything:ignore code.weak-hash: checksum",
+ "code.weak-hash",
+ true,
+ ),
+ (
+ "x // safe-anything:ignore code.weak-hash: checksum",
+ "code.eval",
+ false,
+ ),
+ (
+ "x // safe-anything:ignore code.eval.",
+ "code.weak-hash",
+ false,
+ ),
+ (
+ "x // safe-anything:ignore code.eval; code.weak-hash",
+ "code.weak-hash",
+ false,
+ ),
+ (
+ "x // safe-anything:ignore code.eval - unlike secret.hardcoded-password this is safe",
+ "code.eval",
+ true,
+ ),
+ (
+ "x // safe-anything:ignore code.eval - unlike secret.hardcoded-password this is safe",
+ "secret.hardcoded-password",
+ false,
+ ),
+ (
+ "x // safe-anything:ignore code.eval reviewed by ü",
+ "code.weak-hash",
+ false,
+ ),
+ (
+ "x // safe-anything:ignore code.eval — geprüft",
+ "code.weak-hash",
+ false,
+ ),
+ (
+ "x // safe-anything:ignore secret.aws_access_key, code.eval",
+ "code.eval",
+ true,
+ ),
+ (
+ "x // safe-anything:ignore secret.aws_access_key, code.eval",
+ "code.weak-hash",
+ false,
+ ),
+ (
+ "x // safe-anything:ignore code.eval, secret.aws_access_key, code.weak-hash",
+ "code.weak-hash",
+ true,
+ ),
+ ("x /* safe-anything:ignore code.eval*/", "code.eval", true),
+ (
+ "x /* safe-anything:ignore code.eval*/",
+ "code.weak-hash",
+ false,
+ ),
+ (
+ "x /* safe-anything:ignore code.eval */",
+ "code.weak-hash",
+ false,
+ ),
+ (
+ "x /* safe-anything:ignore code.eval*/eval(y)",
+ "code.eval",
+ true,
+ ),
+ (
+ "x /* safe-anything:ignore code.eval*/eval(y)",
+ "code.weak-hash",
+ false,
+ ),
+ (
+ "x /* safe-anything:ignore code.eval*/ code.weak-hash",
+ "code.weak-hash",
+ false,
+ ),
+ (
+ "x <!-- safe-anything:ignore code.xss-v-html--><div>",
+ "code.xss-v-html",
+ true,
+ ),
+ (
+ "x <!-- safe-anything:ignore code.xss-v-html--><div>",
+ "code.eval",
+ false,
+ ),
+ (
+ "x <!-- safe-anything:ignore code.xss-v-html -->",
+ "code.eval",
+ false,
+ ),
+ (
+ "x // safe-anything:ignore code.weak-hashh",
+ "code.weak-hash",
+ false,
+ ),
+ (
+ "x // safe-anything:ignore code.weak-hashh",
+ "code.eval",
+ false,
+ ),
+ ("x {/* safe-anything:ignore code.x*/}", "code.eval", false),
+ (
+ "x // safe-anything:ignore code.js is generated",
+ "code.eval",
+ false,
+ ),
+ (
+ "x # safe-anything:ignore code.eval # safe-anything:ignore",
+ "code.weak-hash",
+ true,
+ ),
+ (
+ "x # safe-anything:ignore code.eval safe-anything:ignore code.weak-hash",
+ "code.weak-hash",
+ true,
+ ),
+ (
+ "x # safe-anything:ignore code.eval safe-anything:ignore code.weak-hash",
+ "code.eval",
+ true,
+ ),
+ (
+ "x # safe-anything:ignore code.eval safe-anything:ignore code.weak-hash",
+ "secret.aws-access-key",
+ false,
+ ),
+ ("x // nothing to see", "code.eval", false),
+ ];
+ let wrong: Vec<_> = cases
+ .iter()
+ .filter(|&&(line, rule, want)| Cover::of(line).covers(rule) != want)
+ .collect();
+ assert!(wrong.is_empty(), "{wrong:#?}");
+ }
+
+ #[test]
+ fn ignore_marker_on_the_line_above_with_rule_ids() {
+ let text = Text::new("// safe-anything:ignore code.eval\nx\ny\n");
+ assert!(!text.suppressed(1, "code.weak-hash"));
+ assert!(text.suppressed(2, "code.eval"));
+ assert!(!text.suppressed(2, "code.weak-hash"));
+ assert!(!text.suppressed(3, "code.eval"));
+ }
+
+ #[test]
+ fn ignore_rule_ids_in_an_mcp_config() {
+ let src = r#"{
+ "mcp": {
+ "x": {
+ "type": "local",
+ // safe-anything:ignore agent.mcp-unpinned
+ "command": ["npx", "-y", "some-mcp"],
+ // safe-anything:ignore agent.mcp-unpinned
+ "environment": { "API_TOKEN": "example-plaintext-value" }
+ }
+ }
+}"#;
+ let found: Vec<(usize, String)> = check(&FileInfo::new("opencode.jsonc"), src, false)
+ .into_iter()
+ .filter(|f| f.family == Family::Agent)
+ .map(|f| (f.line, f.rule))
+ .collect();
+ assert_eq!(found, vec![(8, "agent.mcp-plaintext-secret".to_string())]);
+ }
+}
diff --git a/src/rules/secrets.rs b/src/rules/secrets.rs
index a71d7ba..2b60cee 100644
--- a/src/rules/secrets.rs
+++ b/src/rules/secrets.rs
@@ -37,7 +37,7 @@ pub fn env_not_ignored(root: &Path, env_files: &[String]) -> Option<Finding> {
),
};
let text = Text::new(&src);
- if text.suppressed(1) {
+ if text.suppressed(1, ENV_NOT_IGNORED.0) {
return None;
}
// `.env` contents are only needed to honor suppression directives; never
diff --git a/tests/fixtures/code/EXPECTED b/tests/fixtures/code/EXPECTED
index aa5f3c7..335be60 100644
--- a/tests/fixtures/code/EXPECTED
+++ b/tests/fixtures/code/EXPECTED
@@ -71,6 +71,15 @@ web/app.js:4 code.xss-inner-html
web/app.js:5 code.xss-document-write
web/app.js:6 code.eval
web/app.js:7 code.eval
+web/ignore.js:14 code.weak-hash
+web/ignore.js:16 code.eval
+web/ignore.js:20 secret.hardcoded-password
+web/ignore.js:22 secret.hardcoded-password
+web/ignore.js:28 code.weak-hash
+web/ignore.js:30 code.weak-hash
+web/ignore.js:34 code.eval
+web/ignore.js:3 code.eval
+web/ignore.js:8 code.eval
web/login.spec.ts:3 secret.aws-access-key
web/page.vue:1 code.xss-v-html
web/app.js:34 code.open-redirect
diff --git a/tests/fixtures/code/web/ignore.js b/tests/fixtures/code/web/ignore.js
new file mode 100644
index 0000000..d6e82f8
--- /dev/null
+++ b/tests/fixtures/code/web/ignore.js
@@ -0,0 +1,36 @@
+const a = crypto.createHash('md5').update(body); // safe-anything:ignore code.weak-hash
+
+const b = eval(crypto.createHash('md5').update(x).digest('hex')); // safe-anything:ignore code.weak-hash
+
+// safe-anything:ignore code.eval, code.weak-hash
+const c = eval(crypto.createHash('md5').update(y).digest('hex'));
+// safe-anything:ignore code.weak-hash
+const d = eval(req.body.code);
+
+const e = eval(req.body.code); // safe-anything:ignore
+
+const f = eval(req.body.code); // safe-anything:ignore false positive, reviewed
+
+const g = eval(crypto.createHash('md5').update(z).digest('hex')); // safe-anything:ignore code.eval, secret.aws_access_key
+
+const h = eval(req.body.code); // safe-anything:ignore code.js is generated
+
+const i = eval(req.body.code); // safe-anything:ignore code.weak-hash code.eval
+
+const j = crypto.createHash('md5').update(pw); const password = "{{fake:password}}"; // safe-anything:ignore code.weak-hash
+
+const k = eval(req.body.code); const password = "{{fake:password}}"; // safe-anything:ignore code.eval - unlike secret.hardcoded-password this is safe
+
+const l = crypto.createHash('md5').update(pw); // safe-anything:ignore not code.eval
+
+const m = crypto.createHash('md5').update(pw); /* safe-anything:ignore */ // see code.eval
+
+const n = eval(crypto.createHash('md5').update(q).digest('hex')); /* safe-anything:ignore code.eval*/
+
+const o = crypto.createHash('md5').update(pw); // safe-anything:ignore code.weak-hashh
+
+const p = crypto.createHash('md5').update(pw); // uses safe-anything:ignore, code.eval is fine
+
+const q = eval(req.body.code); /* safe-anything:ignore code.x*/
+
+const r = crypto.createHash('md5').update(pw); // safe-anything:ignore code.weak-hash: checksum
diff --git a/tests/scan.rs b/tests/scan.rs
index 7202b07..d2be4f0 100644
--- a/tests/scan.rs
+++ b/tests/scan.rs
@@ -82,6 +82,30 @@ fn env_example_without_gitignore() {
);
}
+#[test]
+fn env_not_ignored_marker_with_rule_ids() {
+ let root =
+ std::env::temp_dir().join(format!("safe-anything-ignore-ids-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&root);
+ std::fs::create_dir_all(&root).unwrap();
+ std::fs::write(root.join(".env"), "SETTING=example-value\n").unwrap();
+ let reported = |gitignore: &str| {
+ std::fs::write(root.join(".gitignore"), gitignore).unwrap();
+ let report = safe_anything::scan(&root, &safe_anything::Options::offline()).unwrap();
+ report
+ .findings
+ .iter()
+ .any(|f| f.rule == "secret.env-not-ignored")
+ };
+ let other = reported("# safe-anything:ignore code.eval\nnode_modules\n");
+ let this = reported("# safe-anything:ignore secret.env-not-ignored\nnode_modules\n");
+ let bare = reported("# safe-anything:ignore\nnode_modules\n");
+ let _ = std::fs::remove_dir_all(&root);
+ assert!(other, "a marker for another rule keeps the finding");
+ assert!(!this, "a marker for this rule drops it");
+ assert!(!bare, "a bare marker drops it");
+}
+
#[test]
fn file_kinds_scanned_and_skipped() {
let root =