grippo 0.2.3

Parse, match and scrub data faster and more efficiently.
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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
// Project:   grippo
// File:      src/scrub/mod.rs
// Purpose:   Find and redact secrets with gitleaks rules and answers
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Secret detection and redaction with gitleaks' rules and gitleaks' answers.
//!
//! Each rule's keywords go into one overlapping signature set over the
//! lower-cased text, so text that names no keyword runs no regex. A rule's
//! regex runs ASCII-only, as RE2 does. Its secret is the configured capture
//! group, else the first non-empty one, else the whole match. A secret at or
//! under the rule's entropy is dropped, and so is one an allowlist matches.

pub mod config;
pub mod field;
#[cfg(feature = "scrub-json")]
mod json;
mod pii;
#[cfg(feature = "record")]
mod record;
mod redact;
mod report;
mod rule;
mod target;
#[cfg(any(feature = "scrub-json", feature = "record"))]
mod walk;

use std::borrow::Cow;
use std::ops::Range;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use regex_automata::util::captures::Captures;
use thiserror::Error;

pub use config::{AllowlistConfig, GITLEAKS, RuleConfig, RuleSpec};
#[cfg(feature = "record")]
pub use record::JsonBytes;
#[cfg(all(feature = "record", feature = "parse"))]
pub use record::LayeredBytes;
#[cfg(all(feature = "record", feature = "xml"))]
pub use record::XmlBytes;
pub use redact::{HASH_ALGORITHM, HashKey, Redaction};
pub use report::{Entry, Kind, Layer, Report};
pub use target::{Scrub, TextBytes};

use crate::path::keys;
use crate::strmatch::{Signature, SignatureError, SignatureScratch, SignatureSet};
use field::CredentialMatcher;
use pii::Pii;
use redact::Redactor;
use report::RuleMeta;
use rule::{Allow, Outcome, Rule};

/// Why a scrubber didn't build.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ScrubError {
    /// The rule config isn't valid TOML for a gitleaks config.
    #[error("scrub: the rule config doesn't parse: {0}")]
    Config(#[from] toml::de::Error),
    /// The config's global allowlist, or one the caller gave, doesn't
    /// compile.
    #[error("scrub: an allowlist doesn't build: {reason}")]
    GlobalAllowlist {
        /// What failed.
        reason: String,
    },
    /// [`Strictness::Strict`] and a rule would be skipped.
    #[error("scrub: rule {rule:?} can't run: {reason}")]
    Skipped {
        /// The rule id.
        rule: String,
        /// Why.
        reason: SkipReason,
    },
    /// A built-in PII pattern didn't compile.
    #[error("scrub: a built-in PII pattern doesn't compile: {source}")]
    Builtin {
        /// The engine's error.
        #[source]
        source: Box<regex_automata::meta::BuildError>,
    },
    /// The keyword set didn't build.
    #[error(transparent)]
    Keywords(#[from] SignatureError),
}

/// Why a rule was left out of a build.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum SkipReason {
    /// It matches on a file path, which text has none of.
    #[error("it matches on a file path")]
    PathGated,
    /// It has no regex.
    #[error("it has no regex")]
    NoRegex,
    /// Its regex or one of its allowlist regexes doesn't compile.
    #[error("a regex doesn't compile: {0}")]
    BadRegex(String),
    /// A field exception path is empty, has an empty segment, or has a `*`
    /// other than a whole last segment.
    #[error("the field path is malformed")]
    BadFieldPath,
}

/// A rule left out of a build, and why.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Skipped {
    /// The rule id.
    pub rule: String,
    /// Why.
    pub reason: SkipReason,
}

/// What a `gitleaks:allow` on a line does.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum AllowMarker {
    /// Nothing: in log text, whoever writes part of a line controls it.
    #[default]
    Ignore,
    /// The secret layer skips the line, as gitleaks does for source code.
    Honour,
}

/// What a build does with a rule it can't run.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Strictness {
    /// Leave it out and list it in [`Scrubber::skipped`].
    #[default]
    Lenient,
    /// Fail the build with [`ScrubError::Skipped`].
    Strict,
}

/// One secret found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding<'s> {
    /// The rule's id.
    pub rule: &'s str,
    /// The whole regex match.
    pub matched: Range<usize>,
    /// The secret within the text.
    pub secret: Range<usize>,
}

/// Each scrubber's id, so a scratch or report from another one is caught.
static NEXT_ID: AtomicU64 = AtomicU64::new(1);

/// The report row and token stem of a value redacted for its field name.
pub const FIELD_RULE: &str = "credential-field";

/// The stem of the token a redaction by rule `id` writes: `credit-card`
/// gives `CREDIT_CARD`, written as `[CREDIT_CARD_REDACTED]` or, hashed, as
/// `[CREDIT_CARD_<16 hex>]`.
#[must_use]
pub fn rule_token(id: &str) -> String {
    RuleMeta::new(id, Layer::Secret).token.into()
}

/// The id of every PII check this build runs, in the order they run. `phone`
/// is there only with `scrub-phone`.
pub const PII_RULES: &[&str] = &[
    "credit-card",
    "iban",
    "email",
    #[cfg(feature = "scrub-phone")]
    "phone",
    "au-abn",
    "au-acn",
    "au-medicare",
    "au-tfn",
];

/// The layers a scrubber runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Layers(u8);

impl Layers {
    /// gitleaks' rules over the value.
    pub const SECRET: Self = Self(1);
    /// A credential field name redacts its whole value.
    pub const FIELD: Self = Self(2);
    /// Card numbers, IBANs, emails and national ids, each
    /// confirmed by its own check.
    pub const PII: Self = Self(4);
    /// Credential pairs in free text: the value after `password=`,
    /// `Authorization:` and the like, URL passwords, bearer tokens, signed
    /// URL parameters and a header value an error quotes as refused. Counted
    /// as [`FIELD_RULE`] on its own row.
    pub const TEXT: Self = Self(8);
    /// Every layer.
    pub const ALL: Self = Self(15);

    /// Both sets of layers.
    #[must_use]
    pub const fn with(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    /// These layers less `other`'s.
    #[must_use]
    pub const fn without(self, other: Self) -> Self {
        Self(self.0 & !other.0)
    }

    /// `true` when `layer` runs.
    #[must_use]
    pub const fn runs(self, layer: Layer) -> bool {
        let bit = match layer {
            Layer::Secret => Self::SECRET.0,
            Layer::Field => Self::FIELD.0,
            Layer::Pii => Self::PII.0,
            Layer::Text => Self::TEXT.0,
        };
        self.0 & bit != 0
    }
}

/// A field path a scrub leaves alone: its keys as [`crate::path`] writes a
/// name, exact, or ending `.*` for every field below.
#[derive(Debug, Clone)]
struct FieldException {
    segments: Vec<String>,
    below: bool,
}

impl FieldException {
    /// `None` for an empty path, an empty segment, a bare `*`, or a `*`
    /// anywhere but a whole last segment.
    fn new(path: &str) -> Option<Self> {
        let (path, below) = path.strip_suffix(".*").map_or((path, false), |p| (p, true));
        let segments: Vec<String> = keys(path).map(Cow::into_owned).collect();
        let bad = segments.iter().any(|s| s.is_empty() || s.contains('*'));
        (!bad).then_some(Self { segments, below })
    }

    fn covers(&self, path: &[&str]) -> bool {
        let n = self.segments.len();
        let len_fits = if self.below {
            path.len() > n
        } else {
            path.len() == n
        };
        len_fits && self.segments.iter().zip(path).all(|(a, b)| a == b)
    }

    /// Where `path` sits against this path taken as a scope. `a.*` holds the
    /// fields below `a`, not `a` itself, as it does for an exception.
    fn scope(&self, path: &[&str]) -> Scope {
        let shared = self.segments.iter().zip(path).all(|(a, b)| a == b);
        let n = self.segments.len();
        match path.len().cmp(&n) {
            _ if !shared => Scope::Out,
            std::cmp::Ordering::Less => Scope::Above,
            std::cmp::Ordering::Equal if self.below => Scope::Above,
            std::cmp::Ordering::Equal | std::cmp::Ordering::Greater => Scope::In,
        }
    }
}

/// Where a value's path sits against a scrubber's scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Scope {
    /// At or below a scoped path: scrubbed.
    In,
    /// Above a scoped path: left alone, its members walked.
    Above,
    /// Neither: left alone with all its members.
    Out,
}

/// Builds a [`Scrubber`].
#[must_use]
pub struct ScrubberBuilder {
    redaction: Redaction,
    strictness: Strictness,
    keep: Option<Box<dyn Fn(&RuleSpec) -> bool + Send + Sync>>,
    layers: Layers,
    credentials: CredentialMatcher,
    exceptions: Vec<String>,
    only: Vec<String>,
    allow_marker: AllowMarker,
    without: Vec<String>,
    allow: Vec<AllowlistConfig>,
    scoped: Vec<(Vec<String>, AllowlistConfig)>,
    observe: Vec<String>,
}

impl ScrubberBuilder {
    /// What `gitleaks:allow` does. [`AllowMarker::Ignore`] when not set.
    pub const fn allow_marker(mut self, marker: AllowMarker) -> Self {
        self.allow_marker = marker;
        self
    }

    /// The layers to run. [`Layers::ALL`] when not set.
    pub const fn layers(mut self, layers: Layers) -> Self {
        self.layers = layers;
        self
    }

    /// The terms that make a field name a credential.
    /// [`field::SENSITIVE_FIELDS`] when not set.
    pub fn credential_terms(mut self, credentials: CredentialMatcher) -> Self {
        self.credentials = credentials;
        self
    }

    /// Field paths left alone, such as `event_data.TokenElevationType` or
    /// `event_data.*`. A key holding a dot is written quoted, as in
    /// `labels["app.kind"]`. An exception beats a credential field name. Each
    /// finding it hides is counted as [`Kind::ExceptedField`].
    pub fn except_fields<I, S>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.exceptions
            .extend(paths.into_iter().map(|p| p.as_ref().to_owned()));
        self
    }

    /// Scrub only these field paths and everything below them, written as in
    /// [`Self::except_fields`]. A layer's mount, such as `cef` after
    /// `syslog > cef` or `doc` after `ndjson > field("doc"):xml`, scopes the
    /// scrub to that layer. Values outside are left alone and never counted,
    /// and an exception still beats the scope. Every field when not set.
    /// [`Scrubber::scrub_text`] reads no path, so a scope doesn't reach it.
    pub fn only_fields<I, S>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.only
            .extend(paths.into_iter().map(|p| p.as_ref().to_owned()));
        self
    }

    /// What a found secret becomes. [`Redaction::Mask`] when not set.
    pub fn redaction(mut self, redaction: Redaction) -> Self {
        self.redaction = redaction;
        self
    }

    /// What to do with a rule that can't run. [`Strictness::Lenient`] when
    /// not set.
    pub const fn strictness(mut self, strictness: Strictness) -> Self {
        self.strictness = strictness;
        self
    }

    /// Build only the rules `keep` accepts. The rest are never evaluated and
    /// never counted.
    pub fn keep(mut self, keep: impl Fn(&RuleSpec) -> bool + Send + Sync + 'static) -> Self {
        self.keep = Some(Box::new(keep));
        self
    }

    /// Leave these rules out by id: a config rule, one of [`PII_RULES`], or
    /// [`FIELD_RULE`], which drops the field and text layers. A rule left out
    /// is never evaluated and never counted.
    pub fn without_rules<I, S>(mut self, ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.without.extend(ids.into_iter().map(Into::into));
        self
    }

    /// Count these rules' finds as [`Kind::Observed`] and leave their bytes
    /// alone, by id as in [`Self::without_rules`], while the other rules
    /// redact.
    pub fn observe_rules<I, S>(mut self, ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.observe.extend(ids.into_iter().map(Into::into));
        self
    }

    /// A global allowlist of the caller's, beside the config's.
    pub fn allow(mut self, allowlist: AllowlistConfig) -> Self {
        self.allow.push(allowlist);
        self
    }

    /// An allowlist of the caller's for these rules only, by id: a config
    /// rule or one of [`PII_RULES`].
    pub fn allow_rules<I, S>(mut self, ids: I, allowlist: AllowlistConfig) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let ids = ids.into_iter().map(Into::into).collect();
        self.scoped.push((ids, allowlist));
        self
    }

    /// Build from a rule config.
    ///
    /// # Errors
    ///
    /// [`ScrubError`] when the global allowlist or the keyword set doesn't
    /// build, or under [`Strictness::Strict`] when a rule can't run.
    pub fn build(self, config: &RuleConfig) -> Result<Scrubber, ScrubError> {
        let mut rules = Vec::new();
        let mut meta = Vec::new();
        let mut sigs = Vec::new();
        let mut keyed = Vec::new();
        let mut unkeyed = Vec::new();
        let mut skipped = Vec::new();
        let out = |id: &str| self.without.iter().any(|w| w == id);
        let layers = if out(FIELD_RULE) {
            self.layers.without(Layers::FIELD.with(Layers::TEXT))
        } else {
            self.layers
        };
        let secret = layers.runs(Layer::Secret);
        let kept = config
            .rules
            .iter()
            .filter(|r| secret && !out(&r.id) && self.keep.as_ref().is_none_or(|k| k(r)));
        let own = |id: &str| -> Result<Vec<Allow>, ScrubError> {
            self.scoped
                .iter()
                .filter(|(ids, _)| ids.iter().any(|i| i == id))
                .map(|(_, cfg)| rule::allow(cfg))
                .collect::<Result<_, _>>()
                .map_err(|reason| ScrubError::GlobalAllowlist { reason })
        };
        for spec in kept {
            let mut rule = match compile_rule(spec) {
                Ok(rule) => rule,
                Err(reason) if self.strictness == Strictness::Strict => {
                    return Err(ScrubError::Skipped {
                        rule: spec.id.clone(),
                        reason,
                    });
                }
                Err(reason) => {
                    skipped.push(Skipped {
                        rule: spec.id.clone(),
                        reason,
                    });
                    continue;
                }
            };
            rule.allow.extend(own(&spec.id)?);
            let i = rules.len();
            rules.push(rule);
            meta.push(RuleMeta::new(&spec.id, Layer::Secret));
            let words: Vec<String> = spec
                .keywords
                .iter()
                .map(|k| k.to_lowercase())
                .filter(|k| !k.is_empty())
                .collect();
            if words.is_empty() {
                unkeyed.push(i);
            } else {
                sigs.push(Signature::builder().any_of(&words).build()?);
                keyed.push(i);
            }
        }
        let global: Vec<Allow> = config
            .allowlist
            .iter()
            .chain(&self.allow)
            .map(rule::allow)
            .collect::<Result<_, _>>()
            .map_err(|reason| ScrubError::GlobalAllowlist { reason })?;
        meta.push(RuleMeta::new(FIELD_RULE, Layer::Field));
        meta.push(RuleMeta::new(FIELD_RULE, Layer::Text));
        let mut exceptions = Vec::new();
        let mut scope = Vec::new();
        let paths =
            (self.exceptions.iter().map(|p| (p, false))).chain(self.only.iter().map(|p| (p, true)));
        for (path, scoped) in paths {
            match FieldException::new(path) {
                Some(e) if scoped => scope.push(e),
                Some(e) => exceptions.push(e),
                None if self.strictness == Strictness::Strict => {
                    return Err(ScrubError::Skipped {
                        rule: path.clone(),
                        reason: SkipReason::BadFieldPath,
                    });
                }
                None => skipped.push(Skipped {
                    rule: path.clone(),
                    reason: SkipReason::BadFieldPath,
                }),
            }
        }
        let mut pii = if layers.runs(Layer::Pii) {
            pii::defaults().map_err(|source| ScrubError::Builtin { source })?
        } else {
            Vec::new()
        };
        pii.retain(|p| !out(p.id));
        let pii_gate = pii::Gate::new(&pii).map_err(|source| ScrubError::Builtin { source })?;
        let pii_allow = pii.iter().map(|p| own(p.id)).collect::<Result<_, _>>()?;
        meta.extend(pii.iter().map(|p| RuleMeta::new(p.id, Layer::Pii)));
        let observe = meta
            .iter()
            .map(|m| self.observe.iter().any(|o| **o == *m.id))
            .collect();
        Ok(Scrubber {
            keywords: SignatureSet::new(&sigs)?,
            rules,
            meta: meta.into(),
            keyed,
            unkeyed,
            global,
            skipped,
            redactor: Redactor::from(&self.redaction),
            pii_gate,
            pii_allow,
            observe,
            layers,
            credentials: self.credentials,
            exceptions,
            scope,
            id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
            allow_marker: self.allow_marker,
            pii,
            pair_token: format!(
                "[{}_REDACTED]",
                RuleMeta::new(FIELD_RULE, Layer::Text).token
            ),
        })
    }
}

fn compile_rule(spec: &RuleSpec) -> Result<Rule, SkipReason> {
    if spec.path.is_some() {
        return Err(SkipReason::PathGated);
    }
    let re = spec.regex.as_deref().ok_or(SkipReason::NoRegex)?;
    let bad = |e: Box<regex_automata::meta::BuildError>| SkipReason::BadRegex(e.to_string());
    Ok(Rule {
        regex: rule::compile(re).map_err(bad)?,
        starts: rule::KeywordStarts::new(re, &spec.keywords),
        secret_group: spec.secret_group.filter(|&g| g > 0),
        entropy: spec.entropy.filter(|&e| e != 0.0),
        allow: spec
            .allowlists
            .iter()
            .map(rule::allow)
            .collect::<Result<_, _>>()
            .map_err(SkipReason::BadRegex)?,
    })
}

/// A built rule set, shared across threads.
#[derive(Debug)]
pub struct Scrubber {
    rules: Vec<Rule>,
    meta: Arc<[RuleMeta]>,
    /// Signature `i` is rule `keyed[i]`.
    keyed: Vec<usize>,
    keywords: SignatureSet,
    unkeyed: Vec<usize>,
    global: Vec<Allow>,
    skipped: Vec<Skipped>,
    redactor: Redactor,
    /// Per PII check, the caller's allowlists for it.
    pii_allow: Vec<Vec<Allow>>,
    /// Per report row, `true` when its finds are counted and left alone.
    observe: Box<[bool]>,
    layers: Layers,
    credentials: CredentialMatcher,
    exceptions: Vec<FieldException>,
    /// The paths scrubbed, with everything below them: every path when empty.
    scope: Vec<FieldException>,
    pii: Vec<Pii>,
    /// Which of `pii` have a candidate in a text, found in one pass.
    pii_gate: pii::Gate,
    /// Ties a scratch and a report to the scrubber that made them.
    id: u64,
    allow_marker: AllowMarker,
    /// What the text layer writes in place of a value.
    pair_token: String,
}

/// A secret found during a scrub: rule index and where.
#[derive(Debug, Clone)]
struct Hit {
    rule: usize,
    secret: Range<usize>,
}

/// Per-thread buffers, reused across calls.
///
/// A scratch belongs to the scrubber that made it. One from another scrubber
/// is replaced on first use.
pub struct ScrubScratch {
    owner: u64,
    lower: Vec<u8>,
    hits: SignatureScratch,
    run: Vec<bool>,
    caps: Vec<Captures>,
    found: Vec<Hit>,
    #[cfg_attr(not(any(feature = "scrub-json", feature = "record")), allow(dead_code))]
    number: String,
    spellings: field::Spellings,
    pii_seen: regex_automata::PatternSet,
    /// A record walk's index stack.
    #[cfg(any(feature = "scrub-json", feature = "record"))]
    stack: Vec<usize>,
    /// A record walk's key path, empty between calls.
    #[cfg(any(feature = "scrub-json", feature = "record"))]
    path: Vec<&'static str>,
    /// A raw JSON record's values, empty between calls.
    #[cfg(feature = "record")]
    events: Vec<walk::Event<'static, &'static str>>,
    #[cfg(feature = "record")]
    json: crate::record::WalkBufs,
    /// A record rewritten in place is spliced here, then copied back.
    #[cfg(feature = "record")]
    spliced: Vec<u8>,
    /// The counts for the record being scrubbed, added to the caller's report
    /// only when it scrubs.
    pending: Option<Report>,
}

impl std::fmt::Debug for ScrubScratch {
    /// Buffer sizes only: the buffers hold the last record's text.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ScrubScratch")
            .field("lower_capacity", &self.lower.capacity())
            .field("rules", &self.caps.len())
            .finish_non_exhaustive()
    }
}

/// What the FIELD layer did with one value.
enum FieldLayer {
    /// The name isn't a credential, so the other layers run.
    NotCredential,
    /// A credential left as it is: excepted, or observed only.
    Kept,
    /// A credential and the token written in its place.
    Replaced(Vec<u8>),
}

impl Scrubber {
    /// `report`, replaced with a fresh one when another scrubber made it.
    fn own(&self, report: &mut Report) {
        if report.owner() != self.id {
            *report = self.report();
        }
    }

    /// Where `path` sits against the scope: [`Scope::In`] when there's none.
    fn scope_of(&self, path: &[&str]) -> Scope {
        let mut at = if self.scope.is_empty() {
            Scope::In
        } else {
            Scope::Out
        };
        for s in &self.scope {
            match s.scope(path) {
                Scope::In => return Scope::In,
                Scope::Above => at = Scope::Above,
                Scope::Out => {}
            }
        }
        at
    }

    /// A builder: mask redaction, lenient, every rule and layer, the default
    /// credential terms, no exceptions, no scope.
    pub fn builder() -> ScrubberBuilder {
        ScrubberBuilder {
            redaction: Redaction::Mask,
            strictness: Strictness::Lenient,
            keep: None,
            layers: Layers::ALL,
            credentials: CredentialMatcher::default_terms().clone(),
            exceptions: Vec::new(),
            only: Vec::new(),
            allow_marker: AllowMarker::Ignore,
            without: Vec::new(),
            allow: Vec::new(),
            scoped: Vec::new(),
            observe: Vec::new(),
        }
    }

    /// The FIELD layer for one value.
    fn field_layer(
        &self,
        path: &[&str],
        value: &[u8],
        excepted: bool,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> FieldLayer {
        let name = path.last().copied().unwrap_or_default();
        let parent = path.len().checked_sub(2).map_or("", |i| path[i]);
        if !self.layers.runs(Layer::Field)
            || value.is_empty()
            || name.is_empty()
            || !self
                .credentials
                .matches_value(name, parent, value, &mut scratch.spellings)
        {
            return FieldLayer::NotCredential;
        }
        let field = self.rules.len();
        if excepted {
            report.add(field, Kind::ExceptedField);
            return FieldLayer::Kept;
        }
        if self.observes(field) {
            report.add(field, Kind::Observed);
            return FieldLayer::Kept;
        }
        report.add(field, Kind::Redacted);
        report.set_changed();
        let mut out = Vec::with_capacity(FIELD_RULE.len() + 20);
        self.redactor
            .write(&mut out, &self.meta[field].token, value);
        FieldLayer::Replaced(out)
    }

    /// As [`Scrubber::scrub_field`] for a number or bool: only a credential
    /// field name redacts it, so a timestamp or an id keeps its type.
    #[cfg(any(feature = "scrub-json", feature = "record"))]
    fn scrub_number(
        &self,
        path: &[&str],
        value: &[u8],
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Option<Vec<u8>> {
        self.own(report);
        let excepted = self.exceptions.iter().any(|e| e.covers(path));
        match self.field_layer(path, value, excepted, scratch, report) {
            FieldLayer::Replaced(out) => Some(out),
            FieldLayer::NotCredential | FieldLayer::Kept => None,
        }
    }

    /// Scrub one field's value, `path` naming it from the record's root.
    ///
    /// A path outside [`ScrubberBuilder::only_fields`] is left alone and not
    /// counted. An excepted path is left alone, its findings counted as
    /// [`Kind::ExceptedField`]. A credential field name redacts the whole
    /// value as [`FIELD_RULE`]. Anything else goes to [`Scrubber::scrub_text`].
    pub fn scrub_field(
        &self,
        path: &[&str],
        value: &[u8],
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Option<Vec<u8>> {
        self.own(report);
        if self.scope_of(path) != Scope::In {
            return None;
        }
        let excepted = self.exceptions.iter().any(|e| e.covers(path));
        match self.field_layer(path, value, excepted, scratch, report) {
            FieldLayer::NotCredential => {}
            FieldLayer::Kept => return None,
            FieldLayer::Replaced(out) => return Some(out),
        }
        if excepted {
            self.scan(value, scratch, |rule, outcome| {
                if let Outcome::Found { .. } = outcome {
                    report.add(rule, Kind::ExceptedField);
                }
            });
            for chunk in value.utf8_chunks() {
                if self.layers.runs(Layer::Text) {
                    self.scrub_pairs_str(
                        chunk.valid(),
                        &mut scratch.spellings,
                        Kind::ExceptedField,
                        report,
                    );
                }
                let candidates = self
                    .pii_gate
                    .candidates(chunk.valid(), &mut scratch.pii_seen);
                for (k, validator) in self.pii.iter().enumerate() {
                    if candidates & (1 << k) == 0 {
                        continue;
                    }
                    let rule = self.pii_base() + k;
                    validator.confirmed(chunk.valid(), |_| report.add(rule, Kind::ExceptedField));
                }
            }
            return None;
        }
        self.scrub_text(value, scratch, report)
    }

    /// Build from a rule config with the builder's defaults.
    ///
    /// # Errors
    ///
    /// As [`ScrubberBuilder::build`].
    pub fn new(config: &RuleConfig) -> Result<Self, ScrubError> {
        Self::builder().build(config)
    }

    /// The gitleaks v8.30.1 default rules with the builder's defaults.
    ///
    /// # Errors
    ///
    /// As [`ScrubberBuilder::build`].
    pub fn gitleaks() -> Result<Self, ScrubError> {
        Self::new(&RuleConfig::from_toml(GITLEAKS)?)
    }

    /// Number of rules built.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.rules.len()
    }

    /// `true` when no rule was built.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.rules.is_empty()
    }

    /// Rules left out of the build, in config order.
    #[must_use]
    pub fn skipped(&self) -> &[Skipped] {
        &self.skipped
    }

    /// Heap bytes held by the compiled regexes. Lazy DFA caches live in the
    /// regexes' own pools and grow per thread as text arrives.
    #[must_use]
    pub fn memory_usage(&self) -> usize {
        let rules: usize = self
            .rules
            .iter()
            .map(|r| {
                r.regex.memory_usage() + r.allow.iter().map(Allow::memory_usage).sum::<usize>()
            })
            .sum();
        rules
            + self.global.iter().map(Allow::memory_usage).sum::<usize>()
            + self.pii.iter().map(Pii::memory_usage).sum::<usize>()
            + self.pii_gate.memory_usage()
    }

    /// Buffers for one thread.
    #[must_use]
    pub fn scratch(&self) -> ScrubScratch {
        ScrubScratch {
            owner: self.id,
            lower: Vec::new(),
            hits: self.keywords.scratch(),
            run: vec![false; self.rules.len()],
            caps: self
                .rules
                .iter()
                .map(|r| r.regex.create_captures())
                .collect(),
            found: Vec::new(),
            number: String::new(),
            spellings: field::Spellings::default(),
            pii_seen: self.pii_gate.scratch(),
            #[cfg(any(feature = "scrub-json", feature = "record"))]
            stack: Vec::new(),
            #[cfg(any(feature = "scrub-json", feature = "record"))]
            path: Vec::new(),
            #[cfg(feature = "record")]
            events: Vec::new(),
            #[cfg(feature = "record")]
            json: crate::record::WalkBufs::default(),
            #[cfg(feature = "record")]
            spliced: Vec::new(),
            pending: None,
        }
    }

    /// A report sized for this scrubber, to reuse across records.
    #[must_use]
    pub fn report(&self) -> Report {
        Report::new(Arc::clone(&self.meta), self.id)
    }

    /// Every secret in `text`, rule by rule. Counts nothing and changes
    /// nothing.
    pub fn find(&self, text: &[u8], scratch: &mut ScrubScratch) -> Vec<Finding<'_>> {
        let mut found = Vec::new();
        self.scan(text, scratch, |i, outcome| {
            if let Outcome::Found { matched, secret } = outcome {
                found.push(Finding {
                    rule: &self.meta[i].id,
                    matched,
                    secret,
                });
            }
        });
        found
    }

    /// Scrub `text`, counting into `report`: the secret layer, then credential
    /// pairs in the text, then each PII validator, each over what the last
    /// wrote. `None` when the bytes stay as they are: nothing found, or
    /// [`Redaction::Observe`].
    ///
    /// The credential pair layer reads invalid UTF-8 as U+FFFD, so a value
    /// runs on through it. Where that layer rewrites the text, the invalid
    /// bytes come out as U+FFFD.
    pub fn scrub_text(
        &self,
        text: &[u8],
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Option<Vec<u8>> {
        self.own(report);
        let secret = self.scrub_secrets(text, scratch, report);
        let pairs = if self.layers.runs(Layer::Text) {
            let kind = self.found_kind(self.rules.len() + 1);
            let read = String::from_utf8_lossy(secret.as_deref().unwrap_or(text));
            self.scrub_pairs_str(&read, &mut scratch.spellings, kind, report)
                .map(String::into_bytes)
        } else {
            None
        };
        let pairs = pairs.or(secret);
        let pii = if self.pii.is_empty() {
            None
        } else {
            let seen = &mut scratch.pii_seen;
            per_chunk(pairs.as_deref().unwrap_or(text), |s| {
                self.scrub_pii_str(s, seen, report)
            })
        };
        let out = pii.or(pairs);
        if out.is_some() {
            report.set_changed();
        }
        out
    }

    /// The text layer: values after credential keys, URL passwords, bearer
    /// tokens, signed URL parameters and refused header values, each counted
    /// on the text row.
    fn scrub_pairs_str(
        &self,
        text: &str,
        spellings: &mut field::Spellings,
        kind: Kind,
        report: &mut Report,
    ) -> Option<String> {
        let token = self.pair_token.as_str();
        let (masked, _) = field::mask_text_in(text, &self.credentials, token, spellings);
        let Cow::Owned(masked) = masked else {
            return None;
        };
        // Tokens a later pass wrote over an earlier one count once. A change
        // that left the count level, such as two tokens merged, still counts.
        let found = masked
            .matches(token)
            .count()
            .saturating_sub(text.matches(token).count())
            .max(1);
        report.add_n(self.rules.len() + 1, kind, found);
        (kind == Kind::Redacted).then_some(masked)
    }

    /// `true` when report row `row` counts its finds and leaves the bytes.
    fn observes(&self, row: usize) -> bool {
        self.redactor.observes() || self.observe[row]
    }

    /// What a find on report row `row` counts as.
    fn found_kind(&self, row: usize) -> Kind {
        if self.observes(row) {
            Kind::Observed
        } else {
            Kind::Redacted
        }
    }

    fn scrub_pii_str(
        &self,
        text: &str,
        seen: &mut regex_automata::PatternSet,
        report: &mut Report,
    ) -> Option<String> {
        let mut current: Cow<'_, str> = Cow::Borrowed(text);
        let mut candidates = self.pii_gate.candidates(text, seen);
        for (k, validator) in self.pii.iter().enumerate() {
            if candidates & (1 << k) == 0 {
                continue;
            }
            let rule = self.pii_base() + k;
            let observe = self.observes(rule);
            let mut out: Option<String> = None;
            let mut copied = 0;
            validator.confirmed(&current, |m| {
                let bytes = current.as_bytes();
                if rule::allowlisted(&self.global, bytes, m.clone())
                    || rule::allowlisted(&self.pii_allow[k], bytes, m.clone())
                {
                    report.add(rule, Kind::AllowlistedValue);
                    return;
                }
                if observe {
                    report.add(rule, Kind::Observed);
                    return;
                }
                report.add(rule, Kind::Redacted);
                let o = out.get_or_insert_with(|| String::with_capacity(current.len() + 32));
                o.push_str(&current[copied..m.start]);
                self.redactor
                    .write_str(o, &self.meta[rule].token, current[m.clone()].as_bytes());
                copied = m.end;
            });
            if let Some(mut o) = out {
                o.push_str(&current[copied..]);
                current = Cow::Owned(o);
                // A token just written can hold what a later pattern matches.
                candidates = self.pii_gate.candidates(&current, seen);
            }
        }
        match current {
            Cow::Owned(s) => Some(s),
            Cow::Borrowed(_) => None,
        }
    }

    /// Where the PII validators' report rows start: after the rules, the
    /// field row and the text row.
    const fn pii_base(&self) -> usize {
        self.rules.len() + 2
    }

    /// The secret layer alone.
    fn scrub_secrets(
        &self,
        text: &[u8],
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Option<Vec<u8>> {
        let mut found = std::mem::take(&mut scratch.found);
        found.clear();
        self.scan(text, scratch, |rule, outcome| match outcome {
            Outcome::Found { secret, .. } => {
                let observe = self.observes(rule);
                report.add(
                    rule,
                    if observe {
                        Kind::Observed
                    } else {
                        Kind::Redacted
                    },
                );
                if !observe && !secret.is_empty() {
                    found.push(Hit {
                        rule,
                        secret: char_bounds(text, secret),
                    });
                }
            }
            Outcome::LowEntropy => report.add(rule, Kind::LowEntropy),
            Outcome::Allowlisted => report.add(rule, Kind::AllowlistedValue),
        });
        let out = (!found.is_empty()).then(|| self.redact(text, &mut found));
        scratch.found = found;
        out
    }

    /// `text` with each run of overlapping secrets replaced by one token,
    /// named for the rule whose secret starts first, the longest on a tie.
    fn redact(&self, text: &[u8], found: &mut [Hit]) -> Vec<u8> {
        found.sort_unstable_by(|a, b| {
            (a.secret.start, b.secret.end, a.rule).cmp(&(b.secret.start, a.secret.end, b.rule))
        });
        let mut out = Vec::with_capacity(text.len() + 32 * found.len());
        let mut at = 0;
        let mut i = 0;
        while i < found.len() {
            let first = &found[i];
            let mut end = first.secret.end;
            let mut j = i + 1;
            while j < found.len() && found[j].secret.start < end {
                end = end.max(found[j].secret.end);
                j += 1;
            }
            out.extend_from_slice(&text[at..first.secret.start]);
            self.redactor.write(
                &mut out,
                &self.meta[first.rule].token,
                &text[first.secret.start..end],
            );
            at = end;
            i = j;
        }
        out.extend_from_slice(&text[at..]);
        out
    }

    /// Run every rule whose keywords appear, calling `on` with each outcome.
    fn scan(&self, text: &[u8], scratch: &mut ScrubScratch, mut on: impl FnMut(usize, Outcome)) {
        if scratch.owner != self.id {
            *scratch = self.scratch();
        }
        scratch.lower.clear();
        scratch
            .lower
            .extend(text.iter().map(u8::to_ascii_lowercase));
        scratch.run.clear();
        scratch.run.resize(self.rules.len(), false);
        for &i in &self.unkeyed {
            scratch.run[i] = true;
        }
        let (keyed, run) = (&self.keyed, &mut scratch.run);
        self.keywords
            .for_each_match(&scratch.lower, &mut scratch.hits, |m| {
                run[keyed[m.index]] = true;
            });
        for (i, rule) in self.rules.iter().enumerate() {
            if scratch.run[i] {
                rule.run(
                    text,
                    &self.global,
                    self.allow_marker == AllowMarker::Honour,
                    &mut scratch.caps[i],
                    |o| on(i, o),
                );
            }
        }
    }
}

/// `r` widened so it neither starts nor ends inside a UTF-8 character.
fn char_bounds(text: &[u8], r: Range<usize>) -> Range<usize> {
    let inside = |i: usize| text.get(i).is_some_and(|b| b & 0xC0 == 0x80);
    let mut start = r.start;
    while start > 0 && inside(start) {
        start -= 1;
    }
    let mut end = r.end;
    while inside(end) {
        end += 1;
    }
    start..end
}

/// `text` with `f` applied to each valid UTF-8 run, bytes between runs kept.
/// `None` when `f` changed no run.
fn per_chunk(text: &[u8], mut f: impl FnMut(&str) -> Option<String>) -> Option<Vec<u8>> {
    let mut out: Option<Vec<u8>> = None;
    let (mut at, mut copied) = (0, 0);
    for chunk in text.utf8_chunks() {
        let valid = chunk.valid();
        if let Some(s) = f(valid) {
            let o = out.get_or_insert_with(|| Vec::with_capacity(text.len()));
            o.extend_from_slice(&text[copied..at]);
            o.extend_from_slice(s.as_bytes());
            copied = at + valid.len();
        }
        at += valid.len() + chunk.invalid().len();
    }
    out.map(|mut o| {
        o.extend_from_slice(&text[copied..]);
        o
    })
}

#[cfg(test)]
mod tests;