truman-core 0.1.0

Core types, filters, and parallel scanner for Truman secret detection
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
//! Parallel file scanner with streaming callbacks.
//!
//! Detection-line rule: files are read as bytes and decoded with lossy
//! UTF-8. Content is split on `\n`; each raw line has at most one trailing
//! `\r` stripped (i.e. we rstripped only `\r\n`, never other whitespace).
//! Detector byte positions (`RawFinding.col_start/col_end`) index into
//! this rstripped line, and [`crate::finding::Span`] stores the full
//! rstripped `line_text` so positions are exact and reproducible.
//!
//! Staged pipeline per file:
//! `skip_file` → read lines → per line (`1`-indexed):
//! `skip_line` (with previous line for nextline pragmas) → per detector
//! `detect()` → per `RawFinding`: `skip_secret_at` (explicit byte offset
//! for `likely_id`) → `verify()` → verification-policy
//! (`skip_due_to_verification`) → build [`Finding`](crate::finding::Finding)
//! (SHA1 hex, byte-exact [`Span`](crate::finding::Span)) → emit
//! [`ScanEvent::Finding`] immediately (streaming, no buffering).
//!
//! Parallelism: files are independent, so both [`Scanner::scan_paths`]
//! and [`Scanner::scan_paths_streaming`] scan files in parallel across
//! all available cores by default (see [`ScanConfig::jobs`]). Lines within
//! a file stay sequential (nextline-pragma state), and detectors within a
//! line stay in registration order. Per-file event order
//! (`FileStart` → `Finding*` → `FileDone`) is always preserved; across
//! files, completion order is not guaranteed when `jobs != 1`.

use rayon::prelude::*;
use sha1::{Digest, Sha1};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;

use crate::detector::{Detector, DetectorContext, DetectorRegistry};
use crate::error::TrumanError;
use crate::filetype::determine_file_type;
use crate::filter::{FilterConfig, FilterSet};
use crate::finding::{Finding, Location, Span, VerifiedResult};
use crate::prefilter::Prefilter;

/// How to scan.
#[derive(Debug, Clone, Default)]
pub struct ScanConfig {
    /// Filter toggles + exclusion patterns.
    pub filters: FilterConfig,
    /// Detector names to run; empty means "all registered".
    pub detectors: Vec<String>,
    /// Forwarded to each detector as `ctx.enable_eager_search`.
    pub enable_eager: bool,
    /// Scan all files, including gitignored ones. When false (default),
    /// directory walks respect `.gitignore` (via the `ignore` crate);
    /// when true, ignored files are also scanned. Mirrors the CLI
    /// `--all-files` flag.
    pub all_files: bool,
    /// Number of worker threads for file scans.
    ///
    /// `0` (default) means automatic: all available cores
    /// (`std::thread::available_parallelism`, honouring `RAYON_NUM_THREADS`
    /// when set). `1` forces single-threaded, deterministic file order.
    /// `N > 1` uses exactly `N` threads. Mirrors the CLI `--jobs/-j` flag.
    pub jobs: usize,
}

impl ScanConfig {
    /// Effective worker thread count: `jobs` when non-zero, otherwise all
    /// available cores. Always at least 1.
    ///
    /// When `jobs == 0`, `RAYON_NUM_THREADS` (if set to a positive integer)
    /// takes precedence over `available_parallelism`, so the collect
    /// (`rayon`) and streaming (scoped-thread) engines agree.
    pub fn effective_threads(&self) -> usize {
        if self.jobs > 0 {
            return self.jobs.max(1);
        }
        if let Ok(v) = std::env::var("RAYON_NUM_THREADS") {
            if let Ok(n) = v.trim().parse::<usize>() {
                if n > 0 {
                    return n;
                }
            }
        }
        std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(4)
            .max(1)
    }
}

/// Per-file statistics emitted with `ScanEvent::FileDone`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileStats {
    /// Scanned file.
    pub file: PathBuf,
    pub lines_scanned: u64,
    pub findings: u64,
}

impl FileStats {
    /// Path of the scanned file (alias for [`FileStats::file`]).
    pub fn path(&self) -> &Path {
        &self.file
    }
}

/// Streaming scan events.
///
/// `scan_file_with_callback` delivers these in file order. For multi-file
/// scans, per-file subsequences (`FileStart` → `Finding*` → `FileDone`) are
/// always ordered, but files may complete out of order when scanning with
/// `jobs != 1`. The callback returns `true` to continue or `false` to abort.
#[derive(Debug)]
pub enum ScanEvent {
    FileStart(PathBuf),
    Finding(Finding),
    FileDone(FileStats),
    Error(TrumanError),
}

/// Compute lowercase SHA1 hex of the plaintext secret.
pub fn hash_secret(secret: &str) -> String {
    let mut h = Sha1::new();
    h.update(secret.as_bytes());
    hex::encode(h.finalize())
}

/// Fallback hex encoding without an extra dependency: sha1 digest -> hex.
mod hex {
    pub fn encode(digest: impl AsRef<[u8]>) -> String {
        let mut s = String::with_capacity(digest.as_ref().len() * 2);
        for b in digest.as_ref() {
            s.push(char::from_digit((b >> 4) as u32, 16).unwrap());
            s.push(char::from_digit((b & 0xf) as u32, 16).unwrap());
        }
        s
    }
}

/// The scanner: registry + config + filter set.
#[derive(Debug, Clone)]
pub struct Scanner {
    plan: Arc<DetectionPlan>,
    config: ScanConfig,
    filters: FilterSet,
}

#[derive(Debug)]
struct DetectionPlan {
    detectors: Vec<Arc<dyn Detector>>,
    prefilter: Prefilter,
}

impl Scanner {
    pub fn new(registry: DetectorRegistry, config: ScanConfig) -> Self {
        Self::with_shared_registry(Arc::new(registry), config)
    }

    pub fn with_shared_registry(registry: Arc<DetectorRegistry>, config: ScanConfig) -> Self {
        let filters = FilterSet::new(config.filters.clone());
        let detectors = if config.detectors.is_empty() {
            registry.detectors().to_vec()
        } else {
            registry
                .detectors()
                .iter()
                .filter(|d| config.detectors.iter().any(|n| n == d.name()))
                .cloned()
                .collect()
        };
        let prefilter = Prefilter::new(&detectors, config.enable_eager);
        Self {
            plan: Arc::new(DetectionPlan {
                detectors,
                prefilter,
            }),
            config,
            filters,
        }
    }

    /// Scan one file, streaming events to `callback`.
    ///
    /// Staged pipeline: `skip_file` → lossy-UTF8 read → per line
    /// (`1`-indexed, single trailing `\r` stripped): `skip_line` (with
    /// previous line) → per detector `detect()` → per finding:
    /// `skip_secret_at(col_start)` → `verify()` →
    /// `skip_due_to_verification` → emit `Finding` immediately.
    ///
    /// `callback` is a `&mut dyn FnMut` (trait object) so callers may pass
    /// either a inline closure or an erased `ScanCallback`-style object.
    ///
    /// Returns `true` if the file completed, `false` if the callback
    /// aborted early.
    pub fn scan_file_with_callback(
        &self,
        path: &Path,
        callback: &mut dyn FnMut(ScanEvent) -> bool,
    ) -> bool {
        if !callback(ScanEvent::FileStart(path.to_path_buf())) {
            return false;
        }

        // File stage: invalid / non-text / excluded / lock /
        // swagger files are skipped without reading (mirrors Python's
        // `_is_filtered_out(filename)` gate in `scan_file`).
        if self.filters.skip_file(path) {
            return callback(ScanEvent::FileDone(FileStats {
                file: path.to_path_buf(),
                lines_scanned: 0,
                findings: 0,
            }));
        }

        let bytes = match std::fs::read(path) {
            Ok(b) => b,
            Err(e) => {
                callback(ScanEvent::Error(TrumanError::Io {
                    path: path.to_string_lossy().to_string(),
                    source: e,
                }));
                return true;
            }
        };
        // Lossy UTF-8 (tolerant of binary / non-UTF8 files).
        let content = String::from_utf8_lossy(&bytes);

        let filetype = determine_file_type(path);
        let mut candidates = self.plan.prefilter.scratch();
        let mut prev_line: Option<&str> = None;
        let mut lines_scanned: u64 = 0;
        let mut findings: u64 = 0;

        // Split on '\n', strip a single trailing '\r' per line.
        for (idx, raw) in content.split('\n').enumerate() {
            let line = raw.strip_suffix('\r').unwrap_or(raw);
            let line_number = (idx + 1) as u32;
            lines_scanned += 1;

            let dominated = self.filters.skip_line(line, prev_line, path);
            // Remember current line for nextline-pragma evaluation even
            // when skipped.
            let ctx = DetectorContext {
                file: path,
                filetype,
                line_number,
                enable_eager_search: self.config.enable_eager,
            };

            if !dominated {
                self.plan.prefilter.select(line, &mut candidates);
                for id in candidates.iter() {
                    let detector = &self.plan.detectors[id];
                    let raw_findings = detector.detect(line, &ctx);
                    for rf in raw_findings {
                        // Validate byte indices defensively.
                        if rf.col_end < rf.col_start || rf.col_end > line.len() {
                            continue;
                        }
                        if !line.is_char_boundary(rf.col_start)
                            || !line.is_char_boundary(rf.col_end)
                        {
                            continue;
                        }
                        if self.filters.skip_secret_at(
                            &rf.secret,
                            line,
                            rf.col_start,
                            detector.name(),
                        ) {
                            continue;
                        }
                        let verified = if self.config.filters.no_verify {
                            VerifiedResult::Unverified
                        } else {
                            detector.verify(&rf.secret, &ctx)
                        };
                        if self.filters.skip_due_to_verification(verified) {
                            continue;
                        }
                        // Backward-compatible context hook (always false);
                        // the real policy decision happened above.
                        if self
                            .filters
                            .skip_context(&rf.secret, line, path, line_number)
                        {
                            continue;
                        }
                        let finding = Finding {
                            detector: detector.name().to_string(),
                            secret_type: detector.secret_type().to_string(),
                            hashed_secret: hash_secret(&rf.secret),
                            secret: rf.secret,
                            location: Location {
                                file: path.to_path_buf(),
                                span: Span::new(
                                    line_number,
                                    rf.col_start,
                                    rf.col_end,
                                    line.to_string(),
                                ),
                            },
                            verified,
                        };
                        findings += 1;
                        if !callback(ScanEvent::Finding(finding)) {
                            return false;
                        }
                    }
                }
            }
            prev_line = Some(line);
        }

        callback(ScanEvent::FileDone(FileStats {
            file: path.to_path_buf(),
            lines_scanned,
            findings,
        }))
    }

    /// Effective worker thread count (see [`ScanConfig::jobs`]).
    ///
    /// `0` means all available cores; `1` means single-threaded.
    pub fn num_threads(&self) -> usize {
        self.config.effective_threads()
    }

    /// Collect candidate files for one input path.
    ///
    /// Directories are walked with the `ignore` crate (hidden files
    /// included) with a `walkdir` fallback when the ignore walker yields
    /// nothing. Unless `config.all_files` is set, `.gitignore` /
    /// `.git/exclude` are respected; with `all_files` ignored files are
    /// also scanned (mirrors the CLI `--all-files` flag). Results are
    /// sorted for deterministic discovery order. Plain files are returned as-is;
    /// existence / `skip_file` filtering happens in
    /// `scan_file_with_callback` (so explicitly-passed files still emit
    /// `FileStart`/`FileDone`).
    fn collect_files(&self, path: &Path) -> Vec<PathBuf> {
        if !path.is_dir() {
            return vec![path.to_path_buf()];
        }
        let mut files = Vec::new();
        let walker = ignore::WalkBuilder::new(path)
            .hidden(false)
            .git_ignore(!self.config.all_files)
            .git_exclude(!self.config.all_files)
            .build();
        for entry in walker.flatten() {
            let fp = entry.path().to_path_buf();
            if fp.is_file() {
                files.push(fp);
            }
        }
        if files.is_empty() {
            // Fallback: plain recursive walk (e.g. outside a git repo or
            // when ignore rules hide everything).
            for entry in walkdir::WalkDir::new(path).into_iter().flatten() {
                let fp = entry.path().to_path_buf();
                if fp.is_file() {
                    files.push(fp);
                }
            }
        }
        files.sort();
        files
    }

    /// Collect candidate files for all input paths.
    ///
    /// Each input path is walked via [`Scanner::collect_files`] (sorted
    /// per path); the concatenated list preserves input order. Used by both
    /// [`Scanner::scan_paths`] and [`Scanner::scan_paths_streaming`] so the
    /// two engines discover identical file sets.
    fn collect_all_files(&self, paths: &[impl AsRef<Path>]) -> Vec<PathBuf> {
        let mut files: Vec<PathBuf> = Vec::new();
        for p in paths {
            files.extend(self.collect_files(p.as_ref()));
        }
        files
    }

    /// Scan one file, collecting only findings.
    ///
    /// Thin wrapper over [`Scanner::scan_file_with_callback`] that drops
    /// `FileStart`/`FileDone`/`Error` events. Used by [`Scanner::scan_paths`].
    fn scan_one_file_collect(&self, path: &Path) -> Vec<Finding> {
        let mut local = Vec::new();
        self.scan_file_with_callback(path, &mut |ev| {
            if let ScanEvent::Finding(f) = ev {
                local.push(f);
            }
            true
        });
        local
    }

    /// Non-streaming convenience: scan files/dirs, return all findings.
    ///
    /// Directories are walked recursively (gitignore-aware via `ignore`,
    /// `walkdir` fallback). Files rejected by `skip_file` emit no findings
    /// (handled inside `scan_file_with_callback`). Individual-file IO
    /// errors are ignored (use the streaming API to observe them).
    ///
    /// File scans run in parallel across [`ScanConfig::jobs`] threads
    /// (default: all available cores); per-file line order and detector
    /// order are preserved, while file completion order is not guaranteed.
    /// Results are sorted by (file, line, columns, hash) for
    /// deterministic output. `jobs == 1` forces a sequential scan.
    pub fn scan_paths(&self, paths: &[impl AsRef<Path>]) -> Vec<Finding> {
        let files = self.collect_all_files(paths);
        if files.is_empty() {
            return Vec::new();
        }
        let threads = self.config.effective_threads().min(files.len()).max(1);
        let mut out: Vec<Finding> = if threads <= 1 {
            files
                .iter()
                .flat_map(|fp| self.scan_one_file_collect(fp))
                .collect()
        } else if self.config.jobs == 0 {
            // Default: rayon global pool (sized to all cores / RAYON_NUM_THREADS).
            files
                .par_iter()
                .flat_map(|fp| self.scan_one_file_collect(fp))
                .collect()
        } else {
            // Explicit `--jobs N`: dedicated pool with exactly N threads.
            match rayon::ThreadPoolBuilder::new().num_threads(threads).build() {
                Ok(pool) => pool.install(|| {
                    files
                        .par_iter()
                        .flat_map(|fp| self.scan_one_file_collect(fp))
                        .collect()
                }),
                Err(_) => files
                    .par_iter()
                    .flat_map(|fp| self.scan_one_file_collect(fp))
                    .collect(),
            }
        };
        out.sort_by(|a, b| {
            a.location
                .file
                .cmp(&b.location.file)
                .then(a.location.span.line.cmp(&b.location.span.line))
                .then(a.location.span.col_start.cmp(&b.location.span.col_start))
                .then(a.location.span.col_end.cmp(&b.location.span.col_end))
                .then(a.hashed_secret.cmp(&b.hashed_secret))
        });
        out
    }

    /// Streaming scan over files/dirs.
    ///
    /// Like [`Scanner::scan_paths`] but emits every [`ScanEvent`]
    /// (`FileStart` / `Finding` / `FileDone` / `Error`) to `callback`
    /// instead of buffering. Returns `true` when all files completed,
    /// `false` if the callback aborted early.
    ///
    /// Files are scanned in parallel across [`ScanConfig::jobs`] threads
    /// (default: all available cores) and events are forwarded to the
    /// single-threaded `callback` as workers complete. Per-file event order
    /// (`FileStart` → `Finding*` → `FileDone`) is always preserved; across
    /// files, completion order is not guaranteed when `jobs != 1` (pass
    /// `jobs = 1` for deterministic sorted-file order). The callback must
    /// stay fast; abort (`false`) stops new files promptly (in-flight files
    /// finish their current send), and the scan then returns `false`.
    pub fn scan_paths_streaming(
        &self,
        paths: &[impl AsRef<Path>],
        callback: &mut dyn FnMut(ScanEvent) -> bool,
    ) -> bool {
        let files = self.collect_all_files(paths);
        if files.is_empty() {
            return true;
        }
        let threads = self.config.effective_threads().min(files.len()).max(1);
        if threads <= 1 || files.len() <= 1 {
            // Sequential fast path: exact file order, immediate abort.
            for fp in &files {
                if !self.scan_file_with_callback(fp, callback) {
                    return false;
                }
            }
            return true;
        }
        self.scan_paths_streaming_parallel(&files, threads, callback)
    }

    /// Parallel streaming engine: scoped work-stealing workers + bounded channel.
    ///
    /// Workers pull file indices via an atomic counter (dynamic balancing for
    /// mixed file sizes), scan with [`Scanner::scan_file_with_callback`], and
    /// forward each event over a bounded `sync_channel`. The caller (scope
    /// owner) is the sole consumer and invokes `callback` serially, so a
    /// `&mut dyn FnMut` (which is `!Send`) never crosses threads. `Scanner`
    /// itself is `Send + Sync` (`Arc<DetectionPlan>` + `Regex` filters), so
    /// `&self` shares freely.
    ///
    /// Abort: the consumer sets `aborted` and drops the receiver to unblock
    /// workers parked on a full channel; workers also poll `aborted` before
    /// each file and after each send, so no new files start after abort.
    fn scan_paths_streaming_parallel(
        &self,
        files: &[PathBuf],
        threads: usize,
        callback: &mut dyn FnMut(ScanEvent) -> bool,
    ) -> bool {
        // Bounded backpressure: enough for in-flight files plus findings
        // without unbounded buffering of huge finding bursts.
        let capacity = (threads.saturating_mul(32)).clamp(64, 2048);
        let (tx, rx) = std::sync::mpsc::sync_channel::<ScanEvent>(capacity);
        let next = AtomicUsize::new(0);
        let aborted = AtomicBool::new(false);

        std::thread::scope(|s| {
            for _ in 0..threads {
                let tx = tx.clone();
                let next = &next;
                let aborted = &aborted;
                s.spawn(move || {
                    loop {
                        if aborted.load(Ordering::Relaxed) {
                            break;
                        }
                        let idx = next.fetch_add(1, Ordering::Relaxed);
                        let Some(fp) = files.get(idx) else {
                            break;
                        };
                        let mut send = |ev: ScanEvent| -> bool {
                            if aborted.load(Ordering::Relaxed) {
                                return false;
                            }
                            match tx.send(ev) {
                                Ok(()) => !aborted.load(Ordering::Relaxed),
                                Err(_) => {
                                    aborted.store(true, Ordering::Relaxed);
                                    false
                                }
                            }
                        };
                        if !self.scan_file_with_callback(fp, &mut send) {
                            // Aborted mid-file (consumer asked, or send failed).
                            aborted.store(true, Ordering::Relaxed);
                            break;
                        }
                    }
                });
            }
            drop(tx);

            let mut completed = true;
            loop {
                match rx.recv() {
                    Ok(ev) => {
                        if aborted.load(Ordering::Relaxed) {
                            completed = false;
                            break;
                        }
                        if !callback(ev) {
                            completed = false;
                            aborted.store(true, Ordering::Relaxed);
                            break;
                        }
                    }
                    Err(_) => break, // all workers done
                }
            }
            // Drop the receiver before joining so workers blocked on a full
            // channel observe `Disconnected` instead of deadlocking.
            drop(rx);
            // Ensure workers observe abort even if they are between files.
            if !completed {
                aborted.store(true, Ordering::Relaxed);
            }
            completed
        })
    }
}

/// Free-function streaming scan: build a [`Scanner`] from `registry` +
/// `config` and stream `paths` to `callback`.
///
/// Files are scanned in parallel across `config.jobs` threads (default: all
/// cores); per-file event order is preserved while file completion order is
/// not guaranteed when `jobs != 1`.
///
/// Returns `true` when all files completed, `false` on early abort.
pub fn scan_paths_streaming(
    registry: DetectorRegistry,
    config: ScanConfig,
    paths: &[impl AsRef<Path>],
    callback: &mut dyn FnMut(ScanEvent) -> bool,
) -> bool {
    Scanner::new(registry, config).scan_paths_streaming(paths, callback)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::detector::{Detector, RawFinding};
    use std::io::Write;

    #[derive(Debug)]
    struct WordDetector;
    impl Detector for WordDetector {
        fn name(&self) -> &'static str {
            "WordDetector"
        }
        fn secret_type(&self) -> &str {
            "Word"
        }
        fn detect(&self, line: &str, _ctx: &DetectorContext) -> Vec<RawFinding> {
            match line.find("hunter2") {
                Some(s) => vec![RawFinding::new("hunter2".into(), s, s + 7)],
                None => vec![],
            }
        }
    }

    fn scanner() -> Scanner {
        let mut reg = DetectorRegistry::new();
        reg.register(WordDetector);
        // WordDetector is not in the regex-based set and "hunter2" lines
        // used here carry no id-like prefix, so defaults are safe; disable
        // the rest explicitly to keep this unit focused on plumbing.
        let mut filters = FilterConfig::default();
        filters.likely_id = false;
        filters.sequential = false;
        Scanner::new(
            reg,
            ScanConfig {
                filters,
                detectors: vec![],
                enable_eager: false,
                all_files: false,
                jobs: 0,
            },
        )
    }

    #[allow(dead_code)]
    fn scanner_with_filters(_filters: FilterConfig) -> Scanner {
        // Kept for symmetry with FilterConfig-focused tests; currently
        // unused by default (all callers build via Scanner::new).
        let mut reg = DetectorRegistry::new();
        reg.register(WordDetector);
        Scanner::new(reg, ScanConfig::default())
    }

    #[test]
    fn positions_are_exact_and_sha1_matches() {
        let dir = std::env::temp_dir();
        let path = dir.join(format!("truman-test-{}.txt", std::process::id()));
        let mut f = std::fs::File::create(&path).unwrap();
        writeln!(f, "pass = hunter2").unwrap();
        drop(f);
        let findings = scanner().scan_paths(&[&path]);
        std::fs::remove_file(&path).ok();
        assert_eq!(findings.len(), 1);
        let finding = &findings[0];
        // "pass = hunter2": hunter2 starts at byte 7, ends at 14.
        assert_eq!(finding.location.span.col_start, 7);
        assert_eq!(finding.location.span.col_end, 14);
        assert_eq!(finding.location.span.snippet(), Some("hunter2"));
        // SHA1("hunter2") — cross-checked against Python hashlib.
        let mut h = Sha1::new();
        h.update(b"hunter2");
        let expected = {
            let d = h.finalize();
            d.iter().map(|b| format!("{b:02x}")).collect::<String>()
        };
        assert_eq!(finding.hashed_secret, expected);
    }

    #[test]
    fn allowlist_skips_line() {
        let dir = std::env::temp_dir();
        let path = dir.join(format!("truman-allow-{}.py", std::process::id()));
        std::fs::write(&path, "pass = 'hunter2'  # pragma: allowlist secret\n").unwrap();
        let mut reg = DetectorRegistry::new();
        reg.register(WordDetector);
        let mut cfg = ScanConfig::default();
        cfg.filters.allowlist = true;
        let findings = Scanner::new(reg, cfg).scan_paths(&[&path]);
        std::fs::remove_file(&path).ok();
        assert!(findings.is_empty());
    }

    #[test]
    fn streams_events_in_order_and_supports_abort() {
        let dir = std::env::temp_dir();
        let path = dir.join(format!("truman-stream-{}.txt", std::process::id()));
        std::fs::write(&path, "a hunter2\nb hunter2\n").unwrap();
        let s = scanner();
        let mut kinds: Vec<&str> = Vec::new();
        let mut finding_count = 0u64;
        let mut stats: Option<(u64, u64)> = None;
        s.scan_file_with_callback(&path, &mut |ev| {
            match ev {
                ScanEvent::FileStart(_) => kinds.push("start"),
                ScanEvent::Finding(_) => {
                    kinds.push("finding");
                    finding_count += 1;
                }
                ScanEvent::FileDone(st) => {
                    kinds.push("done");
                    stats = Some((st.lines_scanned, st.findings));
                }
                ScanEvent::Error(_) => kinds.push("error"),
            }
            true
        });
        std::fs::remove_file(&path).ok();
        assert_eq!(kinds, vec!["start", "finding", "finding", "done"]);
        assert_eq!(finding_count, 2);
        assert_eq!(stats, Some((3, 2))); // trailing newline yields a 3rd empty line
    }

    #[test]
    fn abort_stops_scan_early() {
        let dir = std::env::temp_dir();
        let path = dir.join(format!("truman-abort-{}.txt", std::process::id()));
        std::fs::write(&path, "hunter2\nhunter2\nhunter2\n").unwrap();
        let s = scanner();
        let mut seen = 0;
        let completed = s.scan_file_with_callback(&path, &mut |ev| {
            if matches!(ev, ScanEvent::Finding(_)) {
                seen += 1;
                return false; // abort on first finding
            }
            true
        });
        std::fs::remove_file(&path).ok();
        assert!(!completed);
        assert_eq!(seen, 1);
    }

    #[test]
    fn non_text_and_lock_files_are_skipped() {
        let dir = std::env::temp_dir();
        let png = dir.join(format!("truman-skip-{}.png", std::process::id()));
        std::fs::write(&png, "hunter2\n").unwrap();
        let findings = scanner().scan_paths(&[&png]);
        std::fs::remove_file(&png).ok();
        assert!(findings.is_empty());
    }

    #[test]
    fn crlf_positions_relative_to_rstripped_line() {
        let dir = std::env::temp_dir();
        let path = dir.join(format!("truman-crlf-{}.txt", std::process::id()));
        std::fs::write(&path, "pass = hunter2\r\nsecond\r\n").unwrap();
        let findings = scanner().scan_paths(&[&path]);
        std::fs::remove_file(&path).ok();
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].location.span.col_start, 7);
        assert_eq!(findings[0].location.span.col_end, 14);
        assert_eq!(findings[0].location.span.line_text, "pass = hunter2");
    }

    #[test]
    fn scan_paths_streaming_method_streams_all_files() {
        let dir = std::env::temp_dir();
        let a = dir.join(format!("truman-ms-a-{}.txt", std::process::id()));
        let b = dir.join(format!("truman-ms-b-{}.txt", std::process::id()));
        std::fs::write(&a, "hunter2\n").unwrap();
        std::fs::write(&b, "nothing\n").unwrap();
        let s = scanner();
        let mut starts = 0;
        let mut findings_n = 0;
        let mut dones = 0;
        let ok = s.scan_paths_streaming(&[&a, &b], &mut |ev| {
            match ev {
                ScanEvent::FileStart(_) => starts += 1,
                ScanEvent::Finding(_) => findings_n += 1,
                ScanEvent::FileDone(_) => dones += 1,
                ScanEvent::Error(_) => {}
            }
            true
        });
        std::fs::remove_file(&a).ok();
        std::fs::remove_file(&b).ok();
        assert!(ok);
        assert_eq!(starts, 2);
        assert_eq!(dones, 2);
        assert_eq!(findings_n, 1);
    }

    #[test]
    fn verification_policy_only_verified() {
        #[derive(Debug)]
        struct AlwaysFalse;
        impl Detector for AlwaysFalse {
            fn name(&self) -> &'static str {
                "AlwaysFalse"
            }
            fn secret_type(&self) -> &str {
                "T"
            }
            fn detect(&self, line: &str, _ctx: &DetectorContext) -> Vec<RawFinding> {
                if line.contains("hunter2") {
                    vec![RawFinding::new("hunter2".into(), 0, 7)]
                } else {
                    vec![]
                }
            }
            fn verify(&self, _s: &str, _c: &DetectorContext) -> VerifiedResult {
                VerifiedResult::VerifiedFalse
            }
        }
        let dir = std::env::temp_dir();
        let path = dir.join(format!("truman-verify-{}.txt", std::process::id()));
        std::fs::write(&path, "hunter2\n").unwrap();

        // Default policy drops VerifiedFalse.
        let mut reg = DetectorRegistry::new();
        reg.register(AlwaysFalse);
        let s = Scanner::new(reg, ScanConfig::default());
        assert!(s.scan_paths(&[&path]).is_empty());

        // no_verify keeps it (as Unverified).
        let mut reg2 = DetectorRegistry::new();
        reg2.register(AlwaysFalse);
        let mut cfg = ScanConfig::default();
        cfg.filters.no_verify = true;
        let s2 = Scanner::new(reg2, cfg);
        assert_eq!(s2.scan_paths(&[&path]).len(), 1);
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn scan_paths_is_sorted_and_parallel_safe() {
        let dir = std::env::temp_dir();
        let files: Vec<PathBuf> = (0..8)
            .map(|i| dir.join(format!("truman-par-{}-{}.txt", std::process::id(), i)))
            .collect();
        for (i, p) in files.iter().enumerate() {
            std::fs::write(p, format!("line hunter2 {}\n", i)).unwrap();
        }
        let findings = scanner().scan_paths(&files);
        for p in &files {
            std::fs::remove_file(p).ok();
        }
        assert_eq!(findings.len(), 8);
        let mut sorted = findings.clone();
        sorted.sort_by(|a, b| a.location.file.cmp(&b.location.file));
        assert_eq!(findings, sorted);
    }

    fn scanner_with_jobs(jobs: usize) -> Scanner {
        let mut reg = DetectorRegistry::new();
        reg.register(WordDetector);
        let mut filters = FilterConfig::default();
        filters.likely_id = false;
        filters.sequential = false;
        let mut cfg = ScanConfig {
            filters,
            detectors: vec![],
            enable_eager: false,
            all_files: false,
            jobs,
        };
        // Keep the unit focused on threading, not verification policy.
        cfg.filters.no_verify = true;
        Scanner::new(reg, cfg)
    }

    #[test]
    fn effective_threads_respects_jobs() {
        let mut cfg = ScanConfig::default();
        cfg.jobs = 1;
        assert_eq!(cfg.effective_threads(), 1);
        cfg.jobs = 4;
        assert_eq!(cfg.effective_threads(), 4);
        cfg.jobs = 0;
        assert!(cfg.effective_threads() >= 1);
        assert_eq!(scanner_with_jobs(2).num_threads(), 2);
    }

    #[test]
    fn scan_paths_jobs_variants_agree() {
        let dir = std::env::temp_dir();
        let files: Vec<PathBuf> = (0..8)
            .map(|i| dir.join(format!("truman-jobs-{}-{}.txt", std::process::id(), i)))
            .collect();
        for (i, p) in files.iter().enumerate() {
            std::fs::write(p, format!("line hunter2 {}\n", i)).unwrap();
        }
        let seq = scanner_with_jobs(1).scan_paths(&files);
        let auto = scanner_with_jobs(0).scan_paths(&files);
        let four = scanner_with_jobs(4).scan_paths(&files);
        for p in &files {
            std::fs::remove_file(p).ok();
        }
        assert_eq!(seq.len(), 8);
        assert_eq!(auto, seq);
        assert_eq!(four, seq);
    }

    #[test]
    fn scan_paths_streaming_parallel_preserves_counts_and_per_file_order() {
        let dir = std::env::temp_dir();
        let files: Vec<PathBuf> = (0..16)
            .map(|i| dir.join(format!("truman-pstream-{}-{}.txt", std::process::id(), i)))
            .collect();
        for (i, p) in files.iter().enumerate() {
            if i % 2 == 0 {
                std::fs::write(p, "a hunter2\nb hunter2\n").unwrap();
            } else {
                std::fs::write(p, "nothing here\n").unwrap();
            }
        }
        for jobs in [0usize, 1, 4] {
            let s = scanner_with_jobs(jobs);
            let mut starts = 0usize;
            let mut dones = 0usize;
            let mut findings_n = 0usize;
            // Per-file order: FileStart must precede its Findings/FileDone.
            let mut open: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
            let ok = s.scan_paths_streaming(&files, &mut |ev| {
                match ev {
                    ScanEvent::FileStart(p) => {
                        starts += 1;
                        assert!(open.insert(p));
                    }
                    ScanEvent::Finding(f) => {
                        findings_n += 1;
                        assert!(open.contains(&f.location.file));
                    }
                    ScanEvent::FileDone(st) => {
                        dones += 1;
                        assert!(open.remove(&st.file));
                    }
                    ScanEvent::Error(_) => {}
                }
                true
            });
            assert!(ok, "jobs={jobs}");
            assert_eq!(starts, 16, "jobs={jobs}");
            assert_eq!(dones, 16, "jobs={jobs}");
            assert_eq!(findings_n, 16, "jobs={jobs}"); // 8 files x 2 findings
            assert!(open.is_empty(), "jobs={jobs}");
        }
        for p in &files {
            std::fs::remove_file(p).ok();
        }
    }

    #[test]
    fn scan_paths_streaming_parallel_abort_returns_false() {
        let dir = std::env::temp_dir();
        let files: Vec<PathBuf> = (0..8)
            .map(|i| dir.join(format!("truman-pabort-{}-{}.txt", std::process::id(), i)))
            .collect();
        for p in &files {
            std::fs::write(p, "hunter2\n").unwrap();
        }
        let s = scanner_with_jobs(4);
        let mut seen = 0usize;
        let completed = s.scan_paths_streaming(&files, &mut |ev| {
            if matches!(ev, ScanEvent::Finding(_)) {
                seen += 1;
                return false;
            }
            true
        });
        for p in &files {
            std::fs::remove_file(p).ok();
        }
        assert!(!completed);
        assert!(seen >= 1);
    }
}