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
fix(deps): read lockfiles over 2 MB for the dependency check (#128)
Pure Tech2c60e2162a2f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9d6689c..3b4b626 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,10 @@`github.event.workflow_run.head_branch`, `.display_title`, `.head_commit.message` and the head commit'sauthor and committer name and email pasted into a `run:` step are reported. Fields the triggering runcan't set, like `workflow_run.id`, `.conclusion` or `.repository.name`, are not.+- Dependencies: a lockfile over 2 MB is read again (up to 64 MB) instead of being skipped with "0 packages+ checked". A larger one is named in the report (`lockfiles_too_large` in JSON). npm, Composer and Pipfile+ lockfiles are also read in one pass, whatever their key order: 0.12 s instead of 4.3 s for a 3 MB+ package-lock.json, 0.5 s for 60 MB.## 1.1.0 (2026-11-25)diff --git a/README.md b/README.mdindex ff1c91b..0cf6597 100644--- a/README.md+++ b/README.md@@ -77,7 +77,8 @@ safe-anything --list-rules- folders `.git`, `node_modules`, `target`, `vendor`, `dist`, `build`, `.next`, `.venv`, `venv`,`__pycache__`, `Pods`, `.gradle` and `.claude/worktrees`, so generated code in `build/` isnot checked- - any file over 2 MB, lockfiles included, so a lockfile that large gets no dependency check+ - any file over 2 MB. Lockfiles are read up to 64 MB, for the dependency check only (no code rules+ past 2 MB); a larger one is named in the report as not checked- `*.min.js`, `*.map`, `*.jsonl` and `*.log`- 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 filediff --git a/src/deps.rs b/src/deps.rsindex c7fde87..ed2a355 100644--- a/src/deps.rs+++ b/src/deps.rs@@ -1,10 +1,10 @@use std::collections::{HashMap, HashSet};use std::time::Duration;-use serde::Serialize;+use serde::{Deserialize, Serialize};use serde_json::{Value, json};-use crate::rules::FileInfo;+use crate::rules::{FileInfo, Text};use crate::{Family, Finding, Severity};#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]@@ -38,30 +38,99 @@ fn pkg(eco: &str, name: &str, version: &str, file: &FileInfo, line: usize) -> Pa}}-pub fn parse_lockfile(file: &FileInfo, text: &str) -> Vec<Package> {- match file.name.as_str() {- "package-lock.json" | "npm-shrinkwrap.json" => npm_lock(file, text),- "yarn.lock" => yarn_lock(file, text),- "pnpm-lock.yaml" => pnpm_lock(file, text),- "cargo.lock" => toml_packages(file, text, "crates.io", true),- "poetry.lock" | "uv.lock" | "pdm.lock" => toml_packages(file, text, "PyPI", false),- "go.mod" => go_mod(file, text),- "gemfile.lock" => gemfile_lock(file, text),- "composer.lock" => composer_lock(file, text),- "pipfile.lock" => pipfile_lock(file, text),- "pubspec.lock" => pubspec_lock(file, text),- n if n.starts_with("requirements") && n.ends_with(".txt") => requirements(file, text),- _ => Vec::new(),+/// A JSON object's entries in the order the file lists them. serde_json's own map+/// iterates in byte order, so looking each key up from it would search back from the+/// top of the file whenever the two orders differ.+struct Ordered(Vec<(String, Value)>);++/// Reads an object member as `Ordered`. Any other value (null, an array, a string, ...)+/// is read past and counts as absent, as `Value::as_object` did.+fn ordered<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Ordered>, D::Error> {+ use serde::de::{IgnoredAny, MapAccess, SeqAccess, Visitor};+ struct Entries;+ impl<'de> Visitor<'de> for Entries {+ type Value = Option<Ordered>;+ fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {+ f.write_str("any JSON value")+ }+ fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {+ let mut out = Vec::with_capacity(map.size_hint().unwrap_or(0));+ while let Some(entry) = map.next_entry()? {+ out.push(entry);+ }+ Ok(Some(Ordered(out)))+ }+ fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {+ while seq.next_element::<IgnoredAny>()?.is_some() {}+ Ok(None)+ }+ fn visit_unit<E>(self) -> Result<Self::Value, E> {+ Ok(None)+ }+ fn visit_bool<E>(self, _: bool) -> Result<Self::Value, E> {+ Ok(None)+ }+ fn visit_i64<E>(self, _: i64) -> Result<Self::Value, E> {+ Ok(None)+ }+ fn visit_u64<E>(self, _: u64) -> Result<Self::Value, E> {+ Ok(None)+ }+ fn visit_f64<E>(self, _: f64) -> Result<Self::Value, E> {+ Ok(None)+ }+ fn visit_str<E>(self, _: &str) -> Result<Self::Value, E> {+ Ok(None)+ }}+ d.deserialize_any(Entries)+}++type Parser = fn(&FileInfo, &str) -> Vec<Package>;++/// The parser for a lockfile name, or `None` when the file is not one.+fn parser(name: &str) -> Option<Parser> {+ Some(match name {+ "package-lock.json" | "npm-shrinkwrap.json" => npm_lock,+ "yarn.lock" => yarn_lock,+ "pnpm-lock.yaml" => pnpm_lock,+ "cargo.lock" => |f, t| toml_packages(f, t, "crates.io", true),+ "poetry.lock" | "uv.lock" | "pdm.lock" => |f, t| toml_packages(f, t, "PyPI", false),+ "go.mod" => go_mod,+ "gemfile.lock" => gemfile_lock,+ "composer.lock" => composer_lock,+ "pipfile.lock" => pipfile_lock,+ "pubspec.lock" => pubspec_lock,+ n if n.starts_with("requirements") && n.ends_with(".txt") => requirements,+ _ => return None,+ })+}++/// True for the files `parse_lockfile` reads packages from.+pub fn is_lockfile(file: &FileInfo) -> bool {+ parser(&file.name).is_some()+}++pub fn parse_lockfile(file: &FileInfo, text: &str) -> Vec<Package> {+ parser(&file.name).map_or_else(Vec::new, |parse| parse(file, text))+}++#[derive(Deserialize)]+struct NpmLock {+ #[serde(default, deserialize_with = "ordered")]+ packages: Option<Ordered>,+ #[serde(default, deserialize_with = "ordered")]+ dependencies: Option<Ordered>,}fn npm_lock(file: &FileInfo, text: &str) -> Vec<Package> {- let Ok(json) = serde_json::from_str::<Value>(text) else {+ let Ok(json) = serde_json::from_str::<NpmLock>(text) else {return Vec::new();};+ let lines = Text::new(text);let mut out = Vec::new();let mut cursor = 0;- if let Some(packages) = json.get("packages").and_then(Value::as_object) {+ if let Some(Ordered(packages)) = &json.packages {for (key, p) in packages {let Some(name) = key.rsplit_once("node_modules/").map(|(_, n)| n) else {continue;@@ -73,14 +142,14 @@ fn npm_lock(file: &FileInfo, text: &str) -> Vec<Package> {continue;};let at = find_from(text, &mut cursor, &format!("\"{key}\""));- let line = line_of(text, find_after(text, at, "\"version\""));+ let line = lines.line_of(find_after(text, at, "\"version\""));out.push(pkg("npm", name, version, file, line));}- } else if let Some(deps) = json.get("dependencies").and_then(Value::as_object) {+ } else if let Some(Ordered(deps)) = &json.dependencies {for (name, p) in deps {if let Some(version) = p.get("version").and_then(Value::as_str) {let at = find_from(text, &mut cursor, &format!("\"{name}\""));- out.push(pkg("npm", name, version, file, line_of(text, at)));+ out.push(pkg("npm", name, version, file, lines.line_of(at)));}}}@@ -251,6 +320,7 @@ fn composer_lock(file: &FileInfo, text: &str) -> Vec<Package> {let Ok(json) = serde_json::from_str::<Value>(text) else {return Vec::new();};+ let lines = Text::new(text);let mut out = Vec::new();let mut cursor = 0;for key in ["packages", "packages-dev"] {@@ -270,7 +340,7 @@ fn composer_lock(file: &FileInfo, text: &str) -> Vec<Package> {n,v,file,- line_of(text, find_after(text, at, "\"version\"")),+ lines.line_of(find_after(text, at, "\"version\"")),));}}@@ -278,13 +348,22 @@ fn composer_lock(file: &FileInfo, text: &str) -> Vec<Package> {out}+#[derive(Deserialize)]+struct PipfileLock {+ #[serde(default, deserialize_with = "ordered")]+ default: Option<Ordered>,+ #[serde(default, deserialize_with = "ordered")]+ develop: Option<Ordered>,+}+fn pipfile_lock(file: &FileInfo, text: &str) -> Vec<Package> {- let Ok(json) = serde_json::from_str::<Value>(text) else {+ let Ok(json) = serde_json::from_str::<PipfileLock>(text) else {return Vec::new();};+ let lines = Text::new(text);let mut out = Vec::new();- for key in ["default", "develop"] {- let Some(map) = json.get(key).and_then(Value::as_object) else {+ for (key, section) in [("default", &json.default), ("develop", &json.develop)] {+ let Some(Ordered(map)) = section else {continue;};let mut cursor = text.find(&format!("\"{key}\"")).unwrap_or(0);@@ -300,7 +379,7 @@ fn pipfile_lock(file: &FileInfo, text: &str) -> Vec<Package> {n,v,file,- line_of(text, find_after(text, at, "\"version\"")),+ lines.line_of(find_after(text, at, "\"version\"")),));}}@@ -373,10 +452,6 @@ fn find_after(text: &str, at: usize, needle: &str) -> usize {text[at..].find(needle).map(|i| at + i).unwrap_or(at)}-fn line_of(text: &str, offset: usize) -> usize {- text[..offset].matches('\n').count() + 1-}-pub fn findings(packages: &[Package], found: HashMap<usize, Vec<Advisory>>) -> Vec<Finding> {let mut out = Vec::new();for (i, advisories) in found {@@ -589,3 +664,40 @@ fn advisory(id: &str, d: Option<&Value>, name: &str, current: &str) -> Advisoryfixed,}}++#[cfg(test)]+mod tests {+ use super::*;++ fn npm(text: &str) -> Vec<(String, usize)> {+ parse_lockfile(&FileInfo::new("package-lock.json"), text)+ .into_iter()+ .map(|p| (p.name, p.line))+ .collect()+ }++ #[test]+ fn npm_packages_that_are_not_an_object_fall_back_to_dependencies() {+ for packages in ["null", "[]", "\"x\"", "[1, {\"b\": [2, null]}]"] {+ let text = format!(+ "{{\"packages\": {packages},+\"dependencies\": {{\"left-pad\": {{\"version\": \"1.3.0\"}}}}}}"+ );+ assert_eq!(+ npm(&text),+ [("left-pad".to_string(), 2)],+ "packages: {packages}"+ );+ }+ }++ #[test]+ fn npm_keys_out_of_byte_order_keep_their_lines() {+ let text = "{\"packages\": {+\"node_modules/b\": {+\"version\": \"1.0.0\"},+\"node_modules/a\": {+\"version\": \"2.0.0\"}}}";+ assert_eq!(npm(text), [("b".to_string(), 3), ("a".to_string(), 5)]);+ }+}diff --git a/src/engine.rs b/src/engine.rsindex 96b0433..37c95fb 100644--- a/src/engine.rs+++ b/src/engine.rs@@ -10,6 +10,9 @@ use crate::deps::{self, Package};use crate::rules::{self, FileInfo};const MAX_BYTES: u64 = 2 * 1024 * 1024;+/// Lockfiles get a larger limit: a mid-size monorepo's package-lock.json is+/// several MB, and the dependency check is only as good as the lockfile it reads.+pub(crate) const MAX_LOCK_BYTES: u64 = 64 * 1024 * 1024;const SKIP_DIRS: &[&str] = &[".git","node_modules",@@ -44,10 +47,17 @@ fn skipped_by_name(info: &FileInfo) -> bool {|| info.ext_in(BINARY_EXTS)}+/// A file `read_text` could read. `None` from it means binary or unreadable.+enum Contents {+ Text(Vec<u8>),+ /// The file grew past the limit after its size was checked.+ TooLarge,+}+/// 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>> {+/// file's metadata; a file that has grown past `max` since is reported as `TooLarge`.+fn read_text(path: &Path, len: u64, max: u64) -> Option<Contents> {const HEAD: u64 = 8192;let mut file = File::open(path).ok()?;let mut bytes = Vec::with_capacity(usize::try_from(len.min(HEAD)).ok()?);@@ -57,16 +67,14 @@ fn read_text(path: &Path, len: u64) -> Option<Vec<u8>> {}// 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()?;+ let rest = usize::try_from(len.min(max).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;+ file.take(max + 1 - HEAD).read_to_end(&mut bytes).ok()?;+ if bytes.len() as u64 > max {+ return Some(Contents::TooLarge);}}- Some(bytes)+ Some(Contents::Text(bytes))}pub struct Scanned {@@ -74,6 +82,8 @@ pub struct Scanned {pub findings: Vec<Finding>,pub packages: Vec<Package>,pub env_files: Vec<String>,+ /// Lockfiles left out of the dependency check because they are over `MAX_LOCK_BYTES`.+ pub lockfiles_too_large: Vec<String>,}pub fn scan_files(root: &Path, include_tests: bool) -> Scanned {@@ -82,6 +92,7 @@ pub fn scan_files(root: &Path, include_tests: bool) -> Scanned {findings: Vec::new(),packages: Vec::new(),env_files: Vec::new(),+ lockfiles_too_large: Vec::new(),});let single_file = root.is_file();let base = if single_file {@@ -129,14 +140,28 @@ pub fn scan_files(root: &Path, include_tests: bool) -> Scanned {return WalkState::Continue;}let len = entry.metadata().map(|m| m.len()).unwrap_or(0);- if len > MAX_BYTES {+ let lockfile = deps::is_lockfile(&info);+ let max = if lockfile { MAX_LOCK_BYTES } else { MAX_BYTES };+ if len > max {+ if lockfile {+ out.lock().unwrap().lockfiles_too_large.push(rel);+ }return WalkState::Continue;}- let Some(bytes) = read_text(path, len) else {- return WalkState::Continue;+ let bytes = match read_text(path, len, max) {+ Some(Contents::Text(bytes)) => bytes,+ Some(Contents::TooLarge) => {+ if lockfile {+ out.lock().unwrap().lockfiles_too_large.push(rel);+ }+ return WalkState::Continue;+ }+ None => return WalkState::Continue,};let text = String::from_utf8_lossy(&bytes);- let findings = if info.ext == "lock" {+ // A lockfile over the usual limit is read for its packages only,+ // as no file that size was checked by the rules before.+ let findings = if info.ext == "lock" || bytes.len() as u64 > MAX_BYTES {Vec::new()} else {rules::check(&info, &text, include_tests)@@ -155,6 +180,7 @@ pub fn scan_files(root: &Path, include_tests: bool) -> Scanned {let mut scanned = out.into_inner().unwrap();scanned.packages.sort();scanned.packages.dedup();+ scanned.lockfiles_too_large.sort();scanned}@@ -169,13 +195,23 @@ mod tests {std::fs::create_dir_all(&dir).unwrap();let path = dir.join("grown.txt");let max = usize::try_from(MAX_BYTES).unwrap();+ let text_len = |len: u64| match read_text(&path, len, MAX_BYTES) {+ Some(Contents::Text(bytes)) => Some(bytes.len()),+ _ => None,+ };// 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());+ assert!(matches!(+ read_text(&path, 100, MAX_BYTES),+ Some(Contents::TooLarge)+ ));std::fs::write(&path, "x".repeat(max)).unwrap();- assert_eq!(read_text(&path, 100).map(|b| b.len()), Some(max));+ assert_eq!(text_len(100), Some(max));std::fs::write(&path, "x".repeat(10)).unwrap();- assert_eq!(read_text(&path, MAX_BYTES).map(|b| b.len()), Some(10));+ assert_eq!(text_len(MAX_BYTES), Some(10));+ // A binary file is neither text nor too large.+ std::fs::write(&path, b"x\0y").unwrap();+ assert!(read_text(&path, 3, MAX_BYTES).is_none());let _ = std::fs::remove_dir_all(&dir);}}diff --git a/src/lib.rs b/src/lib.rsindex 90af4d5..4ba3961 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -175,6 +175,9 @@ pub struct Report {pub findings: Vec<Finding>,pub files_scanned: usize,pub packages_checked: usize,+ /// Lockfiles too large to read (over `engine::MAX_LOCK_BYTES`), so their packages were not checked.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub lockfiles_too_large: Vec<String>,pub elapsed_ms: u64,pub dependency_check: DependencyCheck,}@@ -226,6 +229,7 @@ pub fn scan(root: &Path, options: &Options) -> std::io::Result<Report> {let mut report = Report {files_scanned: scanned.files,packages_checked: scanned.packages.len(),+ lockfiles_too_large: scanned.lockfiles_too_large,findings: scanned.findings,..Report::default()};diff --git a/src/report.rs b/src/report.rsindex f0501de..eb7f8a9 100644--- a/src/report.rs+++ b/src/report.rs@@ -100,6 +100,20 @@ pub fn terminal(report: &Report, style: &Style) -> String {)));+ if !report.lockfiles_too_large.is_empty() {+ let _ = writeln!(+ out,+ "{}",+ style.paint(+ "2",+ &format!(+ "Not checked, over {} MB: {}.",+ crate::engine::MAX_LOCK_BYTES / (1024 * 1024),+ report.lockfiles_too_large.join(", ")+ )+ )+ );+ }out}diff --git a/tests/scan.rs b/tests/scan.rsindex 398bd11..7c972ee 100644--- a/tests/scan.rs+++ b/tests/scan.rs@@ -278,3 +278,88 @@ fn deps() {// `GEM` sections count.check_with("deps", options, Some(27));}++/// Writes a package-lock.json listing `n` packages, padded with a long+/// `resolved` URL so a few thousand entries pass the size of an ordinary file.+/// Sorted, the keys are in byte order as npm writes them; otherwise `pkg-{i}`+/// sits in numeric order, and its version is on line `7 + 5 * i`.+fn big_lockfile(dir: &std::path::Path, n: usize, sorted: bool) -> u64 {+ let mut text = String::from(+ "{\n \"name\": \"app\",\n \"lockfileVersion\": 3,\n \"packages\": {\n \"\": { \"name\": \"app\" }",+ );+ let mut ids: Vec<usize> = (0..n).collect();+ if sorted {+ ids.sort_by_key(|i| format!("pkg-{i}"));+ }+ for i in ids {+ text.push_str(&format!(+ ",\n \"node_modules/pkg-{i}\": {{\n \"version\": \"1.0.{i}\",\n \"resolved\": \"https://registry.npmjs.org/pkg-{i}/-/pkg-{i}-1.0.{i}.tgz\",\n \"integrity\": \"sha512-{}\"\n }}",+ "a".repeat(88)+ ));+ }+ text.push_str("\n }\n}\n");+ std::fs::write(dir.join("package-lock.json"), &text).unwrap();+ text.len() as u64+}++#[test]+fn large_lockfile_is_still_read() {+ let root = std::env::temp_dir().join(format!("safe-anything-big-lock-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ std::fs::create_dir_all(&root).unwrap();+ let size = big_lockfile(&root, 12_000, true);+ let report = safe_anything::scan(&root, &safe_anything::Options::offline()).unwrap();+ let _ = std::fs::remove_dir_all(&root);+ assert!(+ size > 2 * 1024 * 1024,+ "the lockfile should be over 2 MB, it is {size} bytes"+ );+ assert_eq!(+ report.packages_checked, 12_000,+ "packages read from a {size}-byte lockfile"+ );+}++#[test]+fn large_lockfile_out_of_byte_order_keeps_its_lines() {+ let root = std::env::temp_dir().join(format!(+ "safe-anything-big-lock-unsorted-{}",+ std::process::id()+ ));+ let _ = std::fs::remove_dir_all(&root);+ std::fs::create_dir_all(&root).unwrap();+ big_lockfile(&root, 12_000, false);+ let options = safe_anything::Options {+ advisories: Some(Box::new(Known(&[+ ("npm", "pkg-9", "1.0.9"),+ ("npm", "pkg-10", "1.0.10"),+ ("npm", "pkg-11999", "1.0.11999"),+ ]))),+ include_tests: false,+ };+ let report = safe_anything::scan(&root, &options).unwrap();+ let _ = std::fs::remove_dir_all(&root);+ let mut lines: Vec<usize> = report.findings.iter().map(|f| f.line).collect();+ lines.sort_unstable();+ assert_eq!(report.packages_checked, 12_000);+ assert_eq!(lines, [7 + 5 * 9, 7 + 5 * 10, 7 + 5 * 11_999]);+}++#[test]+fn lockfile_over_the_limit_is_named() {+ let root = std::env::temp_dir().join(format!("safe-anything-huge-lock-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ std::fs::create_dir_all(root.join("web")).unwrap();+ // Sized from the metadata, so these are never read.+ let over = 64 * 1024 * 1024 + 1;+ for name in ["web/yarn.lock", "notes.txt"] {+ std::fs::File::create(root.join(name))+ .unwrap()+ .set_len(over)+ .unwrap();+ }+ let report = safe_anything::scan(&root, &safe_anything::Options::offline()).unwrap();+ let _ = std::fs::remove_dir_all(&root);+ assert_eq!(report.lockfiles_too_large, ["web/yarn.lock"]);+ assert_eq!(report.packages_checked, 0);+}