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.

perf(scan): skip files by name before reading them (#114)

Onur Ugurfad23e0079b3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b74d684..7c63c42 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,9 @@
`$POSTGRES_PASSWORD`) is skipped.
- Agent: an MCP config whose `npx` (or `pnpm dlx`) argument is empty or starts with a non-ASCII
character no longer crashes the scan.
+- Scan: minified bundles, source maps, `.jsonl` and `.log` files, and images, fonts, archives, media and
+ compiled files (`png`, `woff2`, `zip`, `mp4`, `class`, ...) are skipped by name without being opened.
+ Other binary files are left after their first 8 KB instead of being read in full.
- Agent: `agent.mcp-plaintext-secret` no longer takes an env key for a secret when its credential word is
only part of an ordinary word, so `PATH`, `PYTHONPATH`, `NODE_PATH`, `DISPATCH_MODE`, `AUTHOR`,
`MONKEY_PATCH` and `KEYCHAIN_PROFILE` are not reported. `GITHUB_PAT`, `githubPat`, `OPENAI_APIKEY`,
diff --git a/README.md b/README.md
index 54e0c86..b6234d9 100644
--- a/README.md
+++ b/README.md
@@ -79,7 +79,9 @@ safe-anything --list-rules
not checked
- any file over 2 MB, lockfiles included, so a lockfile that large gets no dependency check
- `*.min.js`, `*.map`, `*.jsonl` and `*.log`
- - binary files (a zero byte in the first 8 KB)
+ - binary files: images, fonts, archives, media and compiled files by their extension (`.png`, `.woff2`,
+ `.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).
- In tests, specs and fixtures only real provider keys and private keys count, unless you pass
diff --git a/src/engine.rs b/src/engine.rs
index 3071fb5..96b0433 100644
--- a/src/engine.rs
+++ b/src/engine.rs
@@ -1,3 +1,5 @@
+use std::fs::File;
+use std::io::Read;
use std::path::Path;
use std::sync::Mutex;
@@ -23,6 +25,50 @@ const SKIP_DIRS: &[&str] = &[
".gradle",
];
+/// Extensions of binary formats that are skipped without opening the file.
+/// Real files of each kind have a zero byte in their first 8 KB, so
+/// `read_text` would skip them anyway. Formats that can be plain text are
+/// left out: `pdf` and `svg` often have no zero byte, and a `.so` can be a
+/// linker script.
+const BINARY_EXTS: &[&str] = &[
+ "png", "jpg", "jpeg", "gif", "webp", "ico", "icns", "bmp", "tif", "tiff", "avif", "heic",
+ "psd", "woff", "woff2", "ttf", "otf", "ttc", "zip", "jar", "gz", "tgz", "bz2", "xz", "zst",
+ "7z", "rar", "mp3", "mp4", "m4a", "mov", "wav", "flac", "exe", "dll", "class", "wasm", "pyc",
+];
+
+/// Minified bundles, source maps, logs, JSONL data and known binary formats,
+/// decided from the name alone.
+fn skipped_by_name(info: &FileInfo) -> bool {
+ info.name.ends_with(".min.js")
+ || info.ext_in(&["map", "jsonl", "log"])
+ || info.ext_in(BINARY_EXTS)
+}
+
+/// Reads a file whose first 8 KB hold no zero byte. A binary file is left
+/// after those 8 KB instead of being read in full. `len` is the size from the
+/// file's metadata; a file that has grown past `MAX_BYTES` since is skipped.
+fn read_text(path: &Path, len: u64) -> Option<Vec<u8>> {
+ const HEAD: u64 = 8192;
+ let mut file = File::open(path).ok()?;
+ let mut bytes = Vec::with_capacity(usize::try_from(len.min(HEAD)).ok()?);
+ (&mut file).take(HEAD).read_to_end(&mut bytes).ok()?;
+ if bytes.contains(&0) {
+ return None;
+ }
+ // Fewer than 8 KB means the end of the file was reached already.
+ if bytes.len() as u64 == HEAD {
+ let rest = usize::try_from(len.min(MAX_BYTES).saturating_sub(HEAD)).ok()?;
+ bytes.reserve(rest);
+ file.take(MAX_BYTES + 1 - HEAD)
+ .read_to_end(&mut bytes)
+ .ok()?;
+ if bytes.len() as u64 > MAX_BYTES {
+ return None;
+ }
+ }
+ Some(bytes)
+}
+
pub struct Scanned {
pub files: usize,
pub findings: Vec<Finding>,
@@ -73,25 +119,23 @@ pub fn scan_files(root: &Path, include_tests: bool) -> Scanned {
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"]) {
+ if skipped_by_name(&info) {
return WalkState::Continue;
}
+ let len = entry.metadata().map(|m| m.len()).unwrap_or(0);
+ if len > MAX_BYTES {
+ return WalkState::Continue;
+ }
+ let Some(bytes) = read_text(path, len) else {
+ return WalkState::Continue;
+ };
+ let text = String::from_utf8_lossy(&bytes);
let findings = if info.ext == "lock" {
Vec::new()
} else {
@@ -113,3 +157,25 @@ pub fn scan_files(root: &Path, include_tests: bool) -> Scanned {
scanned.packages.dedup();
scanned
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn read_text_stops_at_the_size_limit() {
+ let dir =
+ std::env::temp_dir().join(format!("safe-anything-read-text-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("grown.txt");
+ let max = usize::try_from(MAX_BYTES).unwrap();
+ // The metadata said 100 bytes, but the file is now over the limit.
+ std::fs::write(&path, "x".repeat(max + 1)).unwrap();
+ assert!(read_text(&path, 100).is_none());
+ std::fs::write(&path, "x".repeat(max)).unwrap();
+ assert_eq!(read_text(&path, 100).map(|b| b.len()), Some(max));
+ std::fs::write(&path, "x".repeat(10)).unwrap();
+ assert_eq!(read_text(&path, MAX_BYTES).map(|b| b.len()), Some(10));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/tests/scan.rs b/tests/scan.rs
index 3a60f6c..7202b07 100644
--- a/tests/scan.rs
+++ b/tests/scan.rs
@@ -82,6 +82,61 @@ fn env_example_without_gitignore() {
);
}
+#[test]
+fn file_kinds_scanned_and_skipped() {
+ let root =
+ std::env::temp_dir().join(format!("safe-anything-file-kinds-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&root);
+ std::fs::create_dir_all(&root).unwrap();
+ let line = format!("aws_access_key_id = {}\n", common::fake("aws"));
+ let filler = "x".repeat(10_000);
+ let files: &[(&str, Vec<u8>)] = &[
+ // Scanned: text, whatever the extension, and the key may come after 8 KB.
+ ("notes.weird", line.clone().into_bytes()),
+ ("long.txt", format!("{filler}\n{line}").into_bytes()),
+ ("late-zero.weird", format!("{line}{filler}\0").into_bytes()),
+ (
+ "exact-8k.txt",
+ format!("{}\n{line}", "x".repeat(8191 - line.len())).into_bytes(),
+ ),
+ ("report.pdf", line.clone().into_bytes()),
+ // Skipped: a zero byte in the first 8 KB means binary.
+ ("blob.weird", format!("\0{line}").into_bytes()),
+ (
+ "zero-at-8191.weird",
+ format!("{line}{}\0", "x".repeat(8191 - line.len())).into_bytes(),
+ ),
+ // Skipped by name, without being read.
+ ("app.min.js", line.clone().into_bytes()),
+ ("app.js.map", line.clone().into_bytes()),
+ ("server.log", line.clone().into_bytes()),
+ ("rows.jsonl", line.clone().into_bytes()),
+ ("logo.png", line.clone().into_bytes()),
+ ("font.woff2", line.clone().into_bytes()),
+ ("bundle.zip", line.clone().into_bytes()),
+ ];
+ for (name, bytes) in files {
+ std::fs::write(root.join(name), bytes).unwrap();
+ }
+ let report = safe_anything::scan(&root, &safe_anything::Options::offline()).unwrap();
+ let _ = std::fs::remove_dir_all(&root);
+ let found: BTreeSet<&str> = report
+ .findings
+ .iter()
+ .filter(|f| f.rule == "secret.aws-access-key")
+ .map(|f| f.path.as_str())
+ .collect();
+ let expected = BTreeSet::from([
+ "exact-8k.txt",
+ "late-zero.weird",
+ "long.txt",
+ "notes.weird",
+ "report.pdf",
+ ]);
+ assert_eq!(found, expected);
+ assert_eq!(report.files_scanned, 5);
+}
+
#[test]
fn gitignore_must_really_match_env() {
// (.gitignore contents, env file in the project, expect the finding)