forbidden_strings/lib.rs
1// TODO: deferred perf work. See /home/user/.claude/plans/dapper-coalescing-horizon.md.
2// TODO: - L2: line-start index for `line_and_col` -- only matters on the
3// TODO: violation path; revisit if a single file with many hits ever becomes
4// TODO: a real workload.
5// TODO: - Z1: serialize the regex-bucket combined DFA. Resharp 0.5 has no
6// TODO: serialization API; would require swapping that gate to the `regex`
7// TODO: crate (`regex-automata::dfa::dense::DFA::to_bytes`). Trigger: when
8// TODO: startup-only time goes back over ~100ms after P1+P2 land.
9
10// What: `mod walk;` declares a child module whose source lives in
11// `walk.rs` (sibling to this file). `mod` is Rust's module
12// system: it does NOT import names; it simply tells the
13// compiler "this file/module exists, compile it". Names
14// referenced via `crate::walk::xxx` afterward.
15// Why: We split the binary into four files so each unit is
16// focused: `walk.rs` for the working-tree walker that
17// respects `.gitignore`.
18// TS map: Closer to a tsconfig file's "include" entry than to an
19// `import`. The actual `import` happens via the `use` lines
20// below.
21// Gotcha: `mod foo;` without a body is NOT an import; it's a
22// registration. Forgetting to write `mod` for a sibling file
23// silently excludes it from the build.
24//
25// In TS you'd write (pseudocode):
26// ```ts
27// // No equivalent. Closest: TypeScript automatically picks up files
28// // in `include` paths; Rust requires explicit `mod` declarations.
29// ```
30mod rules;
31mod scan;
32mod scan_format;
33mod walk;
34
35// What: `#[cfg(feature = "fuzzing")] pub mod fuzz_api;` registers
36// the curated re-export module ONLY when the `fuzzing`
37// Cargo feature is on. The bin target leaves the feature
38// off and never sees this module; fuzz targets (in
39// `fuzz/Cargo.toml`) enable the feature and use
40// `forbidden_strings::fuzz_api::*` to import internals.
41// Why: Keep the production public surface unchanged while
42// letting fuzz targets reach the internal helpers they
43// need.
44// TS map: `if (process.env.FUZZING) { export * as fuzzApi from "./fuzz_api"; }`
45// in spirit; no clean 1:1 equivalent because TS has no
46// compile-time feature gates.
47//
48// In TS you'd write (pseudocode):
49// ```ts
50// // No clean equivalent; conditional re-export at build time.
51// ```
52#[cfg(feature = "fuzzing")]
53pub mod fuzz_api;
54
55// What: `use std::env;` imports the std `env` module so we can
56// reference `env::args` / `env::var`.
57// Why: Reading argv and environment variables.
58// TS map: `import { argv, env } from "node:process";`.
59//
60// In TS you'd write (pseudocode):
61// ```ts
62// import { argv, env } from "node:process";
63// ```
64use std::env;
65
66// What: `std::fs::canonicalize` is referenced via the full path at
67// three sites (rules-path skip set, walker skip lookup); no
68// bare `use std::fs;` because the per-file `fs::read` slurp
69// moved into `read_with_binary_check` which uses
70// `std::fs::File` directly.
71// Why: Background on file-reading performance choices: `fs::read`
72// is empirically faster than `mmap`-based access on this
73// workload (many small files; per-file VMA setup cost
74// dominates the saved alloc) -- the E2 mmap experiment
75// regressed wall time by 35% on Mono and 43% on the Linux
76// kernel. See PERF.md "Mmap experiment (rejected)".
77// Thread-local scratch buffers were also tried 2026-05-03;
78// rayon's nested-parallelism work-stealing (scan_content
79// uses inner par_iter via prefix-matched and combined-
80// shard fan-out) re-entered the outer flat_map_iter on
81// the SAME thread while the buffer was borrowed,
82// triggering a `RefCell already borrowed` panic. The
83// per-file alloc cost is dwarfed by the unicode-mode
84// speedup; not worth the re-entrancy hazard.
85// TS map: N/A (no import line; `std::fs::canonicalize` is fully
86// qualified at use sites).
87
88// What: `use std::io::Write;` imports the `Write` TRAIT (interface-
89// like). Methods declared by a trait are only callable when
90// the trait is in scope, even when used via macros like
91// `writeln!`.
92// Why: We use `writeln!(handle, ...)` to emit hits.
93// TS map: No 1:1 equivalent; in TS, methods are always callable.
94//
95// In TS you'd write (pseudocode):
96// ```ts
97// // Unnecessary in TS.
98// ```
99use std::io::Write;
100
101// What: `use rayon::prelude::*;` brings rayon's parallel-iterator
102// extension methods into scope (`par_iter`, `flat_map_iter`,
103// etc.).
104// Why: The two-phase main loop uses `par_iter` for both the
105// parallel-read phase and the parallel-scan phase.
106// TS map: No equivalent.
107//
108// In TS you'd write (pseudocode):
109// ```ts
110// // No equivalent.
111// ```
112use rayon::prelude::*;
113
114// What: `use crate::walk::list_files;` re-exports the named function
115// from the sibling module under a short alias for local use.
116// `crate::` is the absolute root of this crate.
117// Why: We call `list_files(".")` once when `--all` mode is
118// selected to enumerate every scannable file.
119// TS map: `import { listFiles } from "./walk";`.
120//
121// In TS you'd write (pseudocode):
122// ```ts
123// import { listFiles } from "./walk";
124// ```
125use crate::rules::load_ruleset;
126use crate::scan::scan_content;
127use crate::walk::list_files;
128
129// What: `fn build_skip_set(rules_path: &str) -> HashSet<PathBuf>`
130// returns the set of CANONICAL absolute paths to skip when
131// walking the tree in `--all` mode. Pre-fix this logic was a
132// basename check (`is_skipped_file`) that matched anywhere in
133// the tree, so an unrelated `sub/forbidden-strings.local.txt`
134// was silently dropped along with the actual rule file. Path-
135// anchored matching pins each skip to its specific filesystem
136// location.
137// Why: Closes BUG 6 (basename skip applies to arbitrary explicit
138// args) and BUG 11 (Windows path basename via rsplit('/')) in
139// one shape change. Path-anchoring removes both failure modes:
140// the basename collision cannot trigger because we compare
141// full canonical paths, and the Windows backslash separator
142// is handled inside `std::fs::canonicalize` / `PathBuf::eq`.
143//
144// Skip set composition:
145// - The actual rules file (whatever the user passed via
146// `--rules` or `FORBIDDEN_STRINGS_RULES`; falls back to
147// the default `forbidden-strings.local.txt` in cwd).
148// - Three canonical generated-source paths at their
149// expected locations relative to repo root. If running
150// from a different cwd they fail to canonicalize and are
151// silently dropped from the set; matching is still
152// correct for the rules file alone.
153//
154// The caller separately decides WHEN to apply the skip:
155// explicit positional args are NEVER skipped (the user asked
156// for them); only walker output in --all mode is filtered.
157// TS map: `function buildSkipSet(rulesPath: string): Set<string>`.
158//
159// In TS you'd write (pseudocode):
160// ```ts
161// function buildSkipSet(rulesPath: string): Set<string> {
162// const set = new Set<string>();
163// try { set.add(fs.realpathSync(rulesPath)); } catch {}
164// for (const k of CANONICAL_GENERATED) {
165// try { set.add(fs.realpathSync(k)); } catch {}
166// }
167// return set;
168// }
169// ```
170fn build_skip_set(rules_path: &str) -> std::collections::HashSet<std::path::PathBuf> {
171 // What: `let mut set: HashSet<PathBuf> = HashSet::new();` -- the
172 // usual mutable-empty-collection pattern.
173 // Why: Accumulate canonical-form paths we want to skip.
174 // TS map: `const set = new Set<string>();`.
175 //
176 // In TS you'd write (pseudocode):
177 // ```ts
178 // const set = new Set<string>();
179 // ```
180 let mut set: std::collections::HashSet<std::path::PathBuf> =
181 std::collections::HashSet::new();
182
183 // What: `if let Ok(p) = std::fs::canonicalize(rules_path) { set.insert(p); }`.
184 // `canonicalize` resolves symlinks AND makes the path
185 // absolute; identical files reached via different
186 // relative paths compare equal at the canonical level.
187 // A missing rules file would fail to canonicalize -- the
188 // loader will surface that error separately via
189 // `load_ruleset`, so we silently skip the insertion here.
190 // Why: Anchor the skip on the actual filesystem identity of
191 // the rules file rather than its basename.
192 // TS map: `try { set.add(fs.realpathSync(rulesPath)); } catch {}`.
193 //
194 // In TS you'd write (pseudocode):
195 // ```ts
196 // try { set.add(fs.realpathSync(rulesPath)); } catch {}
197 // ```
198 if let Ok(p) = std::fs::canonicalize(rules_path) {
199 set.insert(p);
200 }
201 // What: Canonical generated-source paths relative to the repo
202 // root. Each is a file we know contains literal copies of
203 // rule bodies -- scanning them in --all mode would
204 // produce self-matches. Pinned by their expected location
205 // so the matcher does not fire on unrelated files of the
206 // same name elsewhere in the tree.
207 // Why: Same anti-self-match guard as the previous basename
208 // list, but anchored to specific paths. If the binary is
209 // run from outside the monorepo or these files have been
210 // relocated, canonicalize fails and the entry is dropped
211 // -- still no false negative because the file does not
212 // exist at the expected location, so the walker would
213 // not encounter it either.
214 // TS map: constant string array of canonical paths.
215 //
216 // In TS you'd write (pseudocode):
217 // ```ts
218 // const CANONICAL_GENERATED = [ "...", "...", "..." ];
219 // ```
220 let canonical_generated = [
221 "packages/cli/forbidden-strings/data/betterleaks-default-config.toml",
222 "packages/cli/forbidden-strings/src/port-betterleaks-relaxations.ts",
223 "packages/cli/forbidden-strings/forbidden-strings.local.example.txt",
224 ];
225 for k in canonical_generated {
226 if let Ok(p) = std::fs::canonicalize(k) {
227 set.insert(p);
228 }
229 }
230 set
231}
232
233// What: `fn is_walker_skipped(path: &str, skip_set: &HashSet<PathBuf>) -> bool`
234// returns true when the path's canonical form matches a
235// skip-set entry. Used ONLY for walker output in --all mode;
236// explicit positional args bypass this check entirely.
237// Why: Closes BUG 6: the previous `is_skipped_file` ran on every
238// queued path regardless of source, hiding real positive
239// findings on `sub/forbidden-strings.local.txt`-style explicit
240// args. The path-anchored form here is consulted only when
241// the caller knows the path came from the walker.
242// TS map: `function isWalkerSkipped(path: string, skipSet: Set<string>): boolean`.
243//
244// In TS you'd write (pseudocode):
245// ```ts
246// function isWalkerSkipped(path: string, skipSet: Set<string>): boolean {
247// try {
248// const canonical = fs.realpathSync(path);
249// return skipSet.has(canonical);
250// } catch { return false; }
251// }
252// ```
253fn is_walker_skipped(
254 path: &str,
255 skip_set: &std::collections::HashSet<std::path::PathBuf>,
256) -> bool {
257 // What: Canonicalize per file and lookup in the skip set. A
258 // canonicalize failure (broken symlink, vanished file)
259 // returns false -- if we cannot resolve the path, we are
260 // definitely not skipping it. The downstream `fs::read`
261 // will surface any read error via the BUG 4 fix.
262 // Why: Per-file canonicalize is one stat syscall; with the
263 // ~2700-file walked corpus, that's a few ms total --
264 // well under the scan cost itself.
265 // TS map: try/catch around realpathSync.
266 //
267 // In TS you'd write (pseudocode):
268 // ```ts
269 // try {
270 // const canonical = fs.realpathSync(path);
271 // return skipSet.has(canonical);
272 // } catch { return false; }
273 // ```
274 if let Ok(canonical) = std::fs::canonicalize(path) {
275 return skip_set.contains(&canonical);
276 }
277 false
278}
279
280// What: `BIN_PROBE_SIZE` is the byte length read up-front from every
281// file before deciding whether the file is binary. 8 KiB is
282// the same probe size the pre-BUG-5 `is_likely_binary`
283// heuristic used; it matches `git diff`'s "binary or text"
284// heuristic threshold.
285// Why: The probe length tunes a tradeoff: smaller probe lets a
286// binary file with a leading text header (PDF header,
287// machine-O header) sneak past as text; larger probe wastes
288// memory on small files. 8 KiB catches the common cases
289// (PNG, JPG, ELF, WASM, zip, ZSTD frames) and is the
290// established convention.
291const BIN_PROBE_SIZE: usize = 8192;
292
293// What: `read_with_binary_check(path)` reads a file under a binary
294// heuristic:
295// 1. Always read the first `BIN_PROBE_SIZE` bytes.
296// 2. If the file is smaller than that, return what we got.
297// 3. If the probe contains a NUL byte and the file is
298// larger than the probe, return only the probe (the
299// rest is treated as binary tail and not scanned).
300// 4. Otherwise (probe is NUL-free), read and return the
301// full file.
302// Why: Closes the BUG-5 regression without re-introducing the
303// soundness gap that BUG 5 fixed. BUG 5 removed a heuristic
304// that threw away the WHOLE file when the first 8 KiB
305// contained a NUL byte; that masked secrets sitting BEFORE
306// the NUL. This rule keeps that signal (the first 8 KiB is
307// always scanned), but caps the per-file work on large
308// binary blobs (firmware images, vmlinuz, font caches, lock
309// sidecars) at 8 KiB instead of full content. Acceptable
310// miss: a secret living AFTER a NUL byte in a file that is
311// ALSO larger than 8 KiB. Acceptable: those files are the
312// "binary blob with bytes that happen to spell a secret"
313// case, and the secret-leak risk is dominated by source
314// files and small lock files which still scan in full.
315// TS map: `function readWithBinaryCheck(path: string): Buffer`.
316//
317// In TS you'd write (pseudocode):
318// ```ts
319// function readWithBinaryCheck(path: string): Buffer {
320// const fd = fs.openSync(path, "r");
321// try {
322// const probe = Buffer.alloc(BIN_PROBE_SIZE);
323// const n = fs.readSync(fd, probe, 0, BIN_PROBE_SIZE, null);
324// if (n < BIN_PROBE_SIZE) return probe.subarray(0, n);
325// if (probe.indexOf(0) !== -1) return probe;
326// return Buffer.concat([probe, fs.readSync.readRestOf(fd)]);
327// } finally {
328// fs.closeSync(fd);
329// }
330// }
331// ```
332fn read_with_binary_check(path: &str) -> Result<Vec<u8>, std::io::Error> {
333 use std::fs::File;
334 use std::io::Read;
335
336 let mut file = File::open(path)?;
337 let mut buf: Vec<u8> = Vec::with_capacity(BIN_PROBE_SIZE);
338 (&mut file)
339 .take(BIN_PROBE_SIZE as u64)
340 .read_to_end(&mut buf)?;
341
342 if buf.len() < BIN_PROBE_SIZE {
343 return Ok(buf);
344 }
345
346 if memchr::memchr(0, &buf).is_some() {
347 return Ok(buf);
348 }
349
350 file.read_to_end(&mut buf)?;
351 Ok(buf)
352}
353
354// What: `pub fn run_cli_from_env() -> Result<i32, String>` is the
355// library entry point. It reads `env::args()` and env vars,
356// parses flags, loads the ruleset, runs the parallel scan,
357// prints hits to stderr, and returns the exit code the OS
358// should see. `Result<i32, String>` lets the binary thin
359// wrapper decide how to report a catastrophic failure (the
360// `Err` arm) versus a regular run (`Ok(0)` clean,
361// `Ok(1)` violation, `Ok(2)` usage error already eprinted).
362// Sibling shape considered: returning `ExitCode` directly --
363// rejected because tests written against the lib want a
364// plain `i32` they can compare, and `ExitCode` has no `Eq`.
365// Why: Coordinate arg parsing, ruleset loading, parallel scan,
366// and result reporting from a unit testable surface. The bin
367// target's `main` is now a five-line wrapper that turns the
368// returned code into an `ExitCode` and prints `Err` to
369// stderr with a fixed prefix.
370// TS map: No entry-point function in TS; Node scripts just run top-
371// to-bottom. Mentally picture an
372// `async function runCliFromEnv(): Promise<number>` that
373// the bin's tiny wrapper awaits and passes to
374// `process.exit`.
375//
376// In TS you'd write (pseudocode):
377// ```ts
378// async function runCliFromEnv(): Promise<number> {
379// // ...
380// return anyViolation ? 1 : 0;
381// }
382// process.exit(await runCliFromEnv());
383// ```
384pub fn run_cli_from_env() -> Result<i32, String> {
385 // What: `let args: Vec<String> = env::args().skip(1).collect();`
386 // reads command-line arguments. `env::args()` returns an
387 // iterator of `String`s where index 0 is the program name
388 // ("forbidden-strings"); `.skip(1)` drops it; `.collect()`
389 // materializes the remainder into a `Vec<String>`. The
390 // explicit `Vec<String>` annotation tells `.collect()` what
391 // container to build (without it, the collect call is
392 // ambiguous). Sibling type to consider: `Vec<&str>` would
393 // BORROW the args, but `env::args()` already yields owned
394 // `String`s -- borrowing is not an option here.
395 // Why: We need the user's actual flags/files; the program name
396 // is irrelevant.
397 // TS map: `const args = process.argv.slice(2);`.
398 //
399 // In TS you'd write (pseudocode):
400 // ```ts
401 // const args: string[] = process.argv.slice(2);
402 // ```
403 let args: Vec<String> = env::args().skip(1).collect();
404
405 // What: `let mut rules_path: Option<String> = env::var("...").ok();`
406 // reads an environment variable. `env::var` returns
407 // `Result<String, VarError>` (Err if unset); `.ok()` converts
408 // it into `Option<String>` -- `Some(value)` if set, `None`
409 // otherwise. The `mut` lets us reassign `rules_path` later if
410 // `--rules` overrides. Sibling type: `Option<&str>` would
411 // need the env value to live somewhere else; `String` is
412 // owned so it can outlive any function call.
413 // Why: Initial source for the rules-file path; `--rules` flag
414 // takes precedence and overwrites this.
415 // TS map: `let rulesPath: string | undefined = process.env.FORBIDDEN_STRINGS_RULES;`.
416 //
417 // In TS you'd write (pseudocode):
418 // ```ts
419 // let rulesPath: string | undefined = process.env.FORBIDDEN_STRINGS_RULES;
420 // ```
421 let mut rules_path: Option<String> = env::var("FORBIDDEN_STRINGS_RULES").ok();
422
423 // What: `let mut all = false;` declares a mutable boolean. No
424 // type annotation needed -- the literal `false` infers `bool`.
425 // Why: Tracks whether `--all` was passed; we toggle it to true
426 // when we encounter the flag.
427 // TS map: `let all = false;`.
428 //
429 // In TS you'd write (pseudocode):
430 // ```ts
431 // let all = false;
432 // ```
433 let mut all = false;
434
435 // What: `let mut files: Vec<String> = Vec::new();` allocates an
436 // empty growable, owned vector of `String`. `Vec::new()` is
437 // the empty-vector constructor; the explicit type annotation
438 // tells the compiler the element type since the empty
439 // constructor cannot infer it. Sibling: `Vec<&str>` cannot
440 // hold values that outlive the source; we want owned data.
441 // Why: Accumulates positional file arguments as we parse argv.
442 // TS map: `const files: string[] = [];`.
443 //
444 // In TS you'd write (pseudocode):
445 // ```ts
446 // const files: string[] = [];
447 // ```
448 let mut files: Vec<String> = Vec::new();
449
450 // What: `let mut i: usize = 0;` declares a mutable index counter.
451 // `usize` is the unsigned integer wide enough to address any
452 // byte in memory on this platform (32 bits on 32-bit OS,
453 // 64 bits on 64-bit OS). Siblings the reader might expect:
454 // `u32`, `u64`, `i32`, `i64`. Why `usize` not `u64`? Every
455 // std API that takes a "size" or "index" wants `usize`;
456 // mixing widths forces casts.
457 // Why: Manual index lets us advance by 2 (consume `--rules` plus
458 // its value) inside the loop body.
459 // TS map: `let i = 0;` (TS has only one number type).
460 //
461 // In TS you'd write (pseudocode):
462 // ```ts
463 // let i = 0;
464 // ```
465 let mut i: usize = 0;
466
467 // What: `while i < args.len() { ... }` is a basic conditional loop.
468 // No iterator, no syntactic sugar -- just "keep going while
469 // condition holds". `args.len()` returns the vector's length
470 // as `usize`.
471 // Why: We need manual index control to consume `--rules` plus
472 // its argument together; a `for arg in &args` loop cannot
473 // skip ahead.
474 // TS map: `while (i < args.length) { ... }`.
475 //
476 // In TS you'd write (pseudocode):
477 // ```ts
478 // while (i < args.length) { ... }
479 // ```
480 while i < args.len() {
481 // What: `let a = &args[i];` borrows the i-th element. `&` is
482 // Rust's "borrow" operator: it gives a read-only
483 // reference to the value without taking ownership; the
484 // original vector still owns the `String`. Without `&`,
485 // Rust would try to MOVE the `String` out of the vector,
486 // which is illegal because `Vec<String>` does not
487 // support hole-poking moves.
488 // Why: We want to inspect the arg's contents (compare to
489 // "--rules", etc.) without consuming it.
490 // TS map: `const a = args[i];` -- TS has no ownership system,
491 // so reading is always implicitly "borrowing".
492 //
493 // In TS you'd write (pseudocode):
494 // ```ts
495 // const a = args[i];
496 // ```
497 let a = &args[i];
498 if a == "--rules" {
499 i += 1;
500 if i >= args.len() {
501 eprintln!("--rules needs an argument");
502 // What: `return Ok(2);` early-exits `run_cli_from_env`
503 // with the eventual OS exit code 2. `Ok(...)`
504 // wraps the `i32` into the success variant of
505 // `Result<i32, String>`; the bin wrapper turns
506 // it into `ExitCode::from(2)`.
507 // Why: Convention: 0 = success, 1 = violation,
508 // 2 = usage / config error. The usage message
509 // was already printed on the previous line.
510 // TS map: `return 2;`.
511 //
512 // In TS you'd write (pseudocode):
513 // ```ts
514 // return 2;
515 // ```
516 return Ok(2);
517 }
518 // What: `rules_path = Some(args[i].clone());` reassigns
519 // the `Option<String>` variable. `Some(...)` wraps
520 // a value into the present variant of `Option`;
521 // `args[i].clone()` deep-copies the indexed `String`
522 // so the assignment OWNS its bytes (we cannot move
523 // out of a Vec, and a borrow would tie `rules_path`
524 // to `args`'s lifetime).
525 // Why: Capture the argument that follows `--rules` as
526 // our authoritative rules path.
527 // TS map: `rulesPath = args[i];` -- TS strings are GC'd, no
528 // clone needed.
529 //
530 // In TS you'd write (pseudocode):
531 // ```ts
532 // rulesPath = args[i];
533 // ```
534 rules_path = Some(args[i].clone());
535 } else if a == "--all" {
536 all = true;
537 } else if a == "--help" || a == "-h" {
538 // What: `concat!` is a compile-time macro joining string
539 // literals into a single `&'static str`. The `!`
540 // marks it as a macro call, not a function call.
541 // `env!("CARGO_PKG_VERSION")` reads `version` from
542 // Cargo.toml at compile time and inlines it as a
543 // string literal.
544 // Why: Print a single static help string with the version
545 // baked in, no runtime allocation, no formatter.
546 // TS map: The TS analogue is template-literal concatenation
547 // plus `process.env.npm_package_version` (read at
548 // build time via a bundler define), but TS has no
549 // macro system -- the closest mental model is
550 // "compiled-in string template".
551 //
552 // In TS you'd write (pseudocode):
553 // ```ts
554 // const VERSION = process.env.npm_package_version!;
555 // const HELP = `forbidden-strings ${VERSION}\n...`;
556 // console.log(HELP);
557 // ```
558 println!(
559 "{}",
560 concat!(
561 "forbidden-strings ", env!("CARGO_PKG_VERSION"), "\n",
562 "Linear-time deny-list scanner for Git repos.\n",
563 "\n",
564 "USAGE:\n",
565 " forbidden-strings [--rules <PATH>] [--all] [FILE...]\n",
566 "\n",
567 "FLAGS:\n",
568 " --rules <PATH> Path to the rule file (one rule per line).\n",
569 " Overrides FORBIDDEN_STRINGS_RULES.\n",
570 " Default: ./forbidden-strings.local.txt\n",
571 " --all Scan every git-tracked file under cwd.\n",
572 " Respects .gitignore (via the `ignore` crate).\n",
573 " -h, --help Print this help and exit.\n",
574 " -V, --version Print version and exit.\n",
575 "\n",
576 "ENV:\n",
577 " FORBIDDEN_STRINGS_RULES Default rules path; --rules wins if both are set.\n",
578 " If unset, falls back to ./forbidden-strings.local.txt\n",
579 "\n",
580 "EXIT CODES:\n",
581 " 0 No violations.\n",
582 " 1 One or more violations (printed to stderr, redacted).\n",
583 " 2 Usage error or rule-file error.\n",
584 "\n",
585 "EXAMPLES:\n",
586 " # Scan a few files\n",
587 " forbidden-strings --rules ./rules.txt src/main.ts README.md\n",
588 "\n",
589 " # Scan the whole working tree\n",
590 " FORBIDDEN_STRINGS_RULES=./rules.txt forbidden-strings --all\n",
591 "\n",
592 "RULE FORMAT:\n",
593 " Bare line -> case-sensitive literal substring\n",
594 " /PATTERN/FLAGS -> regex (resharp; supports A&B, ~(A), (?=...), (?<=...))\n",
595 " # ... -> comment\n",
596 " Empty line -> skipped\n",
597 "\n",
598 "RESHARP LIMITATIONS (0.5.x through 0.6.x):\n",
599 " A `~(...)` complement body cannot contain `\\b`, `\\B`, `^`, `$`,\n",
600 " or any user-explicit lookaround. Use `\\W` or literal whitespace for\n",
601 " `\\b`; `\\A`/`\\z` for `^`/`$` when whole-content semantics fit; or\n",
602 " lift the boundary check outside the complement. Loader rejects every\n",
603 " failing shape with a named-trigger error. See TROUBLESHOOTING.resharp.md.\n",
604 "\n",
605 "OUTPUT:\n",
606 " PATH:LINE:COL_START..COL_END rule=N (matched substring is NEVER printed)\n",
607 "\n",
608 "See README.md for set-algebra rule examples and CI integration.\n",
609 ),
610 );
611 return Ok(0);
612 } else if a == "--version" || a == "-V" {
613 // What: Same `concat!` + `env!` trick: compile-time string
614 // literal, no runtime cost. `env!` panics at compile
615 // time if `CARGO_PKG_VERSION` is unset, which is
616 // impossible inside a Cargo build.
617 // Why: Match `cargo`/`rustc` convention -- `--version`
618 // prints `<name> <semver>` on stdout.
619 // TS map: `console.log(`forbidden-strings ${VERSION}`)`.
620 //
621 // In TS you'd write (pseudocode):
622 // ```ts
623 // console.log(`forbidden-strings ${VERSION}`);
624 // ```
625 println!("forbidden-strings {}", env!("CARGO_PKG_VERSION"));
626 return Ok(0);
627 } else if a.starts_with("--") || a.starts_with("-") && a.len() > 1 {
628 eprintln!("unknown flag {}", a);
629 return Ok(2);
630 } else {
631 // What: `files.push(a.clone())`. `a` is a `&String`
632 // (borrowed); `.clone()` deep-copies the `String`
633 // so the new owned copy can be moved into the
634 // vector. We cannot push the borrow itself --
635 // `Vec<String>` requires owned `String`s and the
636 // borrow's lifetime would not outlive `args`.
637 // Why: Stash the positional file argument for later
638 // scanning.
639 // TS map: `files.push(a);` -- TS strings are GC'd; no clone.
640 //
641 // In TS you'd write (pseudocode):
642 // ```ts
643 // files.push(a);
644 // ```
645 files.push(a.clone());
646 }
647 // What: `i += 1;` advances to the next argv slot. Plain
648 // integer increment; no Rust-specific magic.
649 // Why: Move past the just-consumed flag/value.
650 // TS map: `i += 1;`.
651 //
652 // In TS you'd write (pseudocode):
653 // ```ts
654 // i += 1;
655 // ```
656 i += 1;
657 }
658
659 // What: `unwrap_or_else(|| ...)` returns the inner `Some` value or
660 // runs the closure to produce a fallback. The closure body
661 // is a string literal converted to `String` via `.to_string()`.
662 // Why: Default the rules path to `forbidden-strings.local.txt` in
663 // cwd when neither `--rules` nor `FORBIDDEN_STRINGS_RULES`
664 // is set, matching the conventional filename. The loader
665 // emits a clear "file not found" error if the default
666 // doesn't exist; we don't pre-check and shadow that error.
667 // TS map: `rulesPath ?? "forbidden-strings.local.txt"`.
668 //
669 // In TS you'd write (pseudocode):
670 // ```ts
671 // const finalRulesPath = rulesPath ?? "forbidden-strings.local.txt";
672 // ```
673 let rules_path = rules_path.unwrap_or_else(|| "forbidden-strings.local.txt".to_string());
674
675 // Run `load_ruleset` and `list_files` concurrently when --all is
676 // set: rules loading is CPU-bound (regex compile + AC build);
677 // file walking is I/O-bound (directory traversal + gitignore parse).
678 // They share no state, so overlapping them shaves whichever side
679 // is shorter.
680 // What: `rayon::join(|| f1(), || f2())` runs two closures in
681 // parallel using the rayon threadpool. Returns a tuple
682 // of their return values once both finish. If only one
683 // closure has substantial work (e.g. when --all is off,
684 // we have no file walk to do), join still runs both --
685 // but the empty closure adds negligible cost.
686 // Why: Rules load is ~12ms for a 1k-rule ruleset; file walk
687 // is ~7ms on this repo. Sequential = 19ms; parallel = 12ms.
688 // TS map: `await Promise.all([loadRuleset(rulesPath), listFiles(".")])`.
689 //
690 // In TS you'd write (pseudocode):
691 // ```ts
692 // const [rulesetResult, filesResult] = await Promise.all([
693 // loadRuleset(rulesPath),
694 // all ? listFiles(".") : Promise.resolve(null),
695 // ]);
696 // ```
697 let (ruleset_result, listed_result): (Result<_, String>, Option<Result<Vec<String>, String>>) =
698 rayon::join(
699 || load_ruleset(&rules_path),
700 || if all { Some(list_files(".")) } else { None },
701 );
702
703 // What: `let ruleset = match ruleset_result { Ok(r) => r, Err(e) => { ...; return ... } };`
704 // is a `match` expression destructuring a `Result<RuleSet, String>`.
705 // `Ok(r)` binds the success payload to local `r` and
706 // "evaluates" the arm to that value; `Err(e)` binds the
707 // failure payload, prints it, and early-returns from
708 // `main`. The match expression as a whole evaluates to
709 // the `Ok` arm's value; assigning it to `ruleset` gives us
710 // a plain `RuleSet` to use below (no more wrapper).
711 // Why: Unwrap the `Result` while presenting a friendly error to
712 // the user instead of a panic.
713 // TS map: `try { ruleset = await loadRuleset(...); } catch (e) { console.error(...); process.exit(2); }`.
714 //
715 // In TS you'd write (pseudocode):
716 // ```ts
717 // let ruleset: RuleSet;
718 // try { ruleset = rulesetResult; }
719 // catch (e) { console.error(`forbidden-strings: ${e}`); process.exit(2); }
720 // ```
721 let ruleset = match ruleset_result {
722 Ok(r) => r,
723 Err(e) => {
724 eprintln!("forbidden-strings: {}", e);
725 return Ok(2);
726 }
727 };
728
729 if env::var("FORBIDDEN_STRINGS_DEBUG_BUCKETS").is_ok() {
730 let ac_cs_pat = ruleset.ac_meta.iter().filter(|m| matches!(m, crate::rules::AcMeta::RegexPrefix { .. })).count();
731 let ac_cs_lit = ruleset.ac_meta.iter().filter(|m| matches!(m, crate::rules::AcMeta::Literal { .. })).count();
732 let ac_ci_pat = ruleset.ac_meta_ci.len();
733 let residual_count: usize = ruleset.residual_shards.iter().map(|s| match s {
734 crate::rules::ResidualShard::Single { .. } => 1,
735 crate::rules::ResidualShard::Combined { positions, .. } => positions.len(),
736 }).sum();
737 let single_shard_count = ruleset.residual_shards.iter().filter(|s| matches!(s, crate::rules::ResidualShard::Single { .. })).count();
738 let combined_shard_count = ruleset.residual_shards.len() - single_shard_count;
739 eprintln!(
740 "forbidden-strings buckets: ac_cs_lit={} ac_cs_regex_prefix={} ac_ci_regex_prefix={} residual={} (in {} single + {} combined shards) regex_rules_total={}",
741 ac_cs_lit, ac_cs_pat, ac_ci_pat, residual_count, single_shard_count, combined_shard_count, ruleset.regex_rules.len(),
742 );
743 if env::var("FORBIDDEN_STRINGS_DEBUG_RESIDUAL_LIST").is_ok() {
744 for shard in &ruleset.residual_shards {
745 let positions: Vec<usize> = match shard {
746 crate::rules::ResidualShard::Single { rule_pos } => vec![*rule_pos],
747 crate::rules::ResidualShard::Combined { positions, .. } => positions.clone(),
748 };
749 for pos in positions {
750 let r = &ruleset.regex_rules[pos];
751 eprintln!("residual rule line={}", r.idx);
752 }
753 }
754 }
755 }
756
757 // What: `if let Some(listed) = listed_result { match listed { ... } }`.
758 // One-arm pattern match: enter the block ONLY when
759 // `listed_result` is `Some`, binding the inner
760 // `Result<Vec<String>, String>` to `listed`. Inside, a
761 // regular `match` extracts `Ok` (replace `files` with the
762 // walker's output) or `Err` (print, exit 2).
763 // Why: `listed_result` is `Some(...)` only when `--all` was
764 // passed; otherwise `None` and we skip silently, leaving
765 // `files` set to whatever came from positional args.
766 // TS map: `if (listedResult) { try { files = listedResult; } catch (e) { ... } }`.
767 //
768 // In TS you'd write (pseudocode):
769 // ```ts
770 // if (listedResult !== null) {
771 // try { files = listedResult; }
772 // catch (e) { console.error(`forbidden-strings: ${e}`); process.exit(2); }
773 // }
774 // ```
775 if let Some(listed) = listed_result {
776 match listed {
777 Ok(f) => files = f,
778 Err(e) => {
779 eprintln!("forbidden-strings: {}", e);
780 return Ok(2);
781 }
782 }
783 }
784
785 // Fused read+scan: each rayon thread maps one file's bytes
786 // (via mmap; falls back to `fs::read` if mmap fails) and
787 // immediately scans them. The two-phase split that used to live
788 // here (Phase A reads, Phase B scans) traded cache locality for
789 // a clean separation but produced no measurable speedup -- after
790 // P1 the AC scan is so fast that file bytes go from disk to AC to
791 // discard within tens of microseconds. Fusing keeps each file's
792 // bytes hot in L1/L2 across the read->scan boundary instead of
793 // risking eviction during the materialize-then-iterate round trip.
794 // What: `files.par_iter().flat_map_iter(|p| { try mmap(p); scan_content(p, &bytes, &rs) }).collect::<Vec<String>>()`
795 // runs map+scan as one rayon work unit per file. The
796 // closure's `Mmap` (or `Vec<u8>` fallback) lives only
797 // until the scan finishes for that file; rayon
798 // work-steals across cores.
799 // Why: Mmap saves the alloc + memcpy that `fs::read` does.
800 // On a hot page cache, that's measurable on `--all`;
801 // on a cold cache, MADV_SEQUENTIAL lets the kernel
802 // readahead-pipeline files. Fallback to `fs::read`
803 // handles the cases mmap can't (empty files, /proc
804 // entries, character devices).
805 // TS map: `(await Promise.all(files.map(async (p) => scanContent(p, await readFileFastest(p), rs)))).flat()`.
806 //
807 // In TS you'd write (pseudocode):
808 // ```ts
809 // const hits = (await Promise.all(
810 // files.map(async (p) => scanContent(p, await readFileFastest(p), ruleset))
811 // )).flat();
812 // ```
813 // What: Build the canonical-path skip set once at startup
814 // (rather than per-file). The set captures the actual
815 // rules file plus the canonical generated-source paths;
816 // empty when none of them resolve. Used only in --all
817 // mode to filter walker output.
818 // Why: Closes BUG 6: explicit positional args are never
819 // skipped; only walker output is filtered, and the filter
820 // is path-anchored (not basename-anchored), so
821 // `sub/forbidden-strings.local.txt` no longer collides
822 // with the actual rules file path.
823 // TS map: `const skipSet = buildSkipSet(rulesPath);`.
824 //
825 // In TS you'd write (pseudocode):
826 // ```ts
827 // const skipSet = buildSkipSet(rulesPath);
828 // ```
829 let skip_set = if all { build_skip_set(&rules_path) } else { std::collections::HashSet::new() };
830
831 let hits: Vec<String> = files
832 .par_iter()
833 .flat_map_iter(|p| {
834 // What: `if all && is_walker_skipped(p, &skip_set) { return Vec::new(); }`.
835 // Only runs the skip check on walker output
836 // (--all mode). For explicit positional args
837 // (`forbidden-strings <path>...` without --all),
838 // the file is ALWAYS scanned -- the user asked.
839 // Why: Closes BUG 6: the previous basename-based skip
840 // hid real findings on
841 // `sub/forbidden-strings.local.txt` and friends
842 // passed as explicit args. The new check applies
843 // only when the walker discovered the file
844 // automatically.
845 //
846 // Inside the conditional, `is_walker_skipped`
847 // canonicalizes the path and compares against
848 // the pre-built skip set. Path-anchored matching
849 // also closes BUG 11 (Windows backslash basename)
850 // by routing through `std::fs::canonicalize`.
851 // TS map: `if (all && isWalkerSkipped(p, skipSet)) return [];`.
852 //
853 // In TS you'd write (pseudocode):
854 // ```ts
855 // if (all && isWalkerSkipped(p, skipSet)) return [];
856 // ```
857 if all && is_walker_skipped(p, &skip_set) {
858 return Vec::new();
859 }
860 // What: `let content = fs::read(p).unwrap_or_default();`.
861 // `fs::read` returns `Result<Vec<u8>, io::Error>`
862 // (the file's raw bytes or an I/O error).
863 // `.unwrap_or_default()` extracts the `Ok` value or
864 // substitutes `Vec::<u8>::default()` (the empty
865 // vec) and SILENTLY DROPS the error. The implicit
866 // inferred type is `Vec<u8>`. Sibling pattern:
867 // `fs::read_to_string` returns `Result<String, _>`
868 // but requires UTF-8 -- we want raw bytes here
869 // because rules scan binary files too.
870 // Why: A file we can't read (permissions, vanished,
871 // etc.) becomes "empty content" and the scan
872 // pass produces zero hits for it. Crashing the
873 // whole walk on one unreadable file is worse.
874 // TS map: `try { content = await readFile(p); } catch { content = new Uint8Array(); }`.
875 // Gotcha: `.unwrap_or_default()` SILENTLY discards the
876 // `io::Error`. We accept that here because the
877 // per-file scan is best-effort.
878 //
879 // In TS you'd write (pseudocode):
880 // ```ts
881 // let content: Uint8Array;
882 // try { content = await readFile(p); }
883 // catch (e) { return [`${p}: read error: ${e.message}`]; }
884 // return scanContent(p, content, ruleset);
885 // ```
886 // What: `match fs::read(p) { Ok(c) => ..., Err(e) => ... }`.
887 // Read error path now emits a synthetic "hit"
888 // string formatted as `{path}: read error: {err}`
889 // instead of silently substituting empty content.
890 // The synthetic entry makes the file appear in the
891 // output report AND keeps the exit code at 1 (hits
892 // non-empty -> ExitCode::from(1) downstream).
893 // Why: Closes BUG 4. Pre-fix, `fs::read(p).unwrap_or_default()`
894 // dropped every io::Error: permissions, missing
895 // file, broken symlink, /proc EACCES, etc. became
896 // "empty content", the scan emitted zero hits, and
897 // the run exited 0. A secret-scanning CI control
898 // must NOT silently pass on unreadable files; the
899 // operator needs to know they had no signal.
900 // TS map: `try { ... } catch (e) { return [makeError(p, e)] }`.
901 //
902 // In TS you'd write (pseudocode):
903 // ```ts
904 // try { content = await readFile(p); }
905 // catch (e) { return [`${p}: read error: ${e}`]; }
906 // ```
907 let content = match read_with_binary_check(p) {
908 Ok(c) => c,
909 Err(e) => {
910 return vec![format!("{}: read error: {}", p, e)];
911 }
912 };
913 // What: `scan_content(p, &content, &ruleset)` is a function
914 // call. `&content` and `&ruleset` are BORROW
915 // expressions: we lend the vec and ruleset to the
916 // callee read-only. The callee returns a fresh
917 // `Vec<String>` of hits which becomes this closure's
918 // tail expression (no `;` -> implicit return).
919 // Why: Hand the just-read bytes to the scanner; the
920 // returned hits become this closure's contribution
921 // to the parallel-flat_map output.
922 // TS map: `return scanContent(p, content, ruleset);`.
923 //
924 // In TS you'd write (pseudocode):
925 // ```ts
926 // return scanContent(p, content, ruleset);
927 // ```
928 scan_content(p, &content, &ruleset)
929 })
930 .collect();
931
932 // What: `std::io::stderr().lock()` returns a `StderrLock`, an
933 // RAII handle holding the stderr mutex. Held writes
934 // don't interleave with other threads.
935 // Why: Print all hits in one batch.
936 // TS map: No equivalent; Node has no stderr lock concept.
937 //
938 // In TS you'd write (pseudocode):
939 // ```ts
940 // for (const h of hits) process.stderr.write(h + "\n");
941 // ```
942 let stderr = std::io::stderr();
943 let mut handle = stderr.lock();
944 for h in &hits {
945 let _ = writeln!(handle, "{}", h);
946 }
947
948 // What: `if hits.is_empty() { Ok(0) } else { Ok(1) }`.
949 // This is an `if`-as-EXPRESSION (not statement) with no
950 // trailing `;`: its value becomes the function's return.
951 // `Ok(0)` and `Ok(1)` construct the success variant of
952 // `Result<i32, String>` with the OS-exit code inside; the
953 // bin wrapper converts to `ExitCode` for the actual exit.
954 // Why: No hits = clean exit; one or more hits = "violation"
955 // exit so CI marks the run as failed.
956 // TS map: `return hits.length === 0 ? 0 : 1;`.
957 //
958 // In TS you'd write (pseudocode):
959 // ```ts
960 // return hits.length === 0 ? 0 : 1;
961 // ```
962 if hits.is_empty() {
963 Ok(0)
964 } else {
965 Ok(1)
966 }
967}