grippo 0.2.2

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
// Project:   grippo
// File:      src/scrub/rule.rs
// Purpose:   One gitleaks rule and its allowlists, compiled
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A rule's regex in RE2 syntax, compiled ASCII-only as RE2 runs it, and the
//! allowlists, entropy gate and secret group that decide what it reports.

use std::collections::HashMap;
use std::ops::Range;

use aho_corasick::AhoCorasick;
use regex_automata::meta::Regex;
use regex_automata::util::captures::Captures;
use regex_automata::util::syntax;
use regex_automata::{Anchored, Input, PatternID};

use super::config::AllowlistConfig;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Target {
    Secret,
    Match,
    Line,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Condition {
    /// A regex or a stopword matches.
    Any,
    /// Every configured check matches.
    All,
    /// An `AND` list with a path or commit check, which log text never meets.
    Never,
}

#[derive(Debug)]
pub(super) struct Allow {
    regexes: Vec<Regex>,
    /// Lower-cased stopwords in one automaton, matched without ASCII case.
    stopwords: Option<AhoCorasick>,
    target: Target,
    condition: Condition,
}

#[derive(Debug)]
pub(super) struct Rule {
    pub regex: Regex,
    /// Where a match can start, for a rule led by a bounded run before its
    /// keyword. `None` searches the whole text.
    pub starts: Option<KeywordStarts>,
    pub secret_group: Option<usize>,
    pub entropy: Option<f64>,
    pub allow: Vec<Allow>,
}

/// What one regex match came to.
pub(super) enum Outcome {
    Found {
        matched: Range<usize>,
        secret: Range<usize>,
    },
    LowEntropy,
    Allowlisted,
}

/// `true` when `rest`, just past a `{`, holds `n}`, `n,}` or `n,m}`.
fn is_repeat(rest: &[u8]) -> bool {
    let digits = |s: &[u8]| s.iter().take_while(|b| b.is_ascii_digit()).count();
    let n = digits(rest);
    if n == 0 {
        return false;
    }
    match rest.get(n) {
        Some(b'}') => true,
        Some(b',') => {
            let m = digits(&rest[n + 1..]);
            rest.get(n + 1 + m) == Some(&b'}')
        }
        _ => false,
    }
}

/// RE2 syntax as regex-syntax reads it: a `{` that opens no repeat is a
/// literal in RE2 and an error here, so it is escaped.
pub(super) fn from_re2(re: &str) -> String {
    let b = re.as_bytes();
    let mut out = String::with_capacity(re.len() + 8);
    let (mut i, mut class) = (0, false);
    while i < b.len() {
        match b[i] {
            b'\\' => {
                let end = (i + 2).min(b.len());
                out.push_str(&re[i..end]);
                i = end;
                continue;
            }
            b'[' if !class => {
                class = true;
                out.push('[');
                i += 1;
                // A `]` straight after `[` or `[^` is a literal member.
                if b.get(i) == Some(&b'^') {
                    out.push('^');
                    i += 1;
                }
                if b.get(i) == Some(&b']') {
                    out.push(']');
                    i += 1;
                }
                continue;
            }
            b'[' if b.get(i + 1) == Some(&b':') => {
                if let Some(len) = re[i..].find(":]") {
                    out.push_str(&re[i..i + len + 2]);
                    i += len + 2;
                    continue;
                }
            }
            b']' if class => class = false,
            b'{' if !class && !is_repeat(&b[i + 1..]) => {
                out.push_str("\\{");
                i += 1;
                continue;
            }
            _ => {}
        }
        let len = re[i..].chars().next().map_or(1, char::len_utf8);
        out.push_str(&re[i..i + len]);
        i += len;
    }
    out
}

/// The most a rule's lazy DFA keeps between searches. The generic rules'
/// counted runs build many states: at the library's 2 MiB the cache fills,
/// clears and builds again on the same line, which made those rules run at
/// half speed. Real lines grow it by about 2 MiB a thread at this ceiling.
const DFA_CACHE: usize = 8 << 20;

pub(super) fn compile(re: &str) -> Result<Regex, Box<regex_automata::meta::BuildError>> {
    Regex::builder()
        .configure(Regex::config().hybrid_cache_capacity(DFA_CACHE))
        .syntax(syntax::Config::new().unicode(false).utf8(false))
        .build(&from_re2(re))
        .map_err(Box::new)
}

pub(super) fn allow(cfg: &AllowlistConfig) -> Result<Allow, String> {
    let and = cfg
        .condition
        .as_deref()
        .is_some_and(|c| c.eq_ignore_ascii_case("AND"));
    let regexes: Vec<Regex> = cfg
        .regexes
        .iter()
        .map(|r| compile(r))
        .collect::<Result<_, _>>()
        .map_err(|e| e.to_string())?;
    let stopwords = if cfg.stopwords.is_empty() {
        None
    } else {
        let words: Vec<String> = cfg.stopwords.iter().map(|s| s.to_lowercase()).collect();
        let ac = AhoCorasick::builder()
            .ascii_case_insensitive(true)
            .build(&words)
            .map_err(|e| e.to_string())?;
        Some(ac)
    };
    Ok(Allow {
        regexes,
        stopwords,
        target: match cfg.regex_target.as_deref() {
            Some("match") => Target::Match,
            Some("line") => Target::Line,
            _ => Target::Secret,
        },
        condition: match (and, cfg.paths.is_empty() && cfg.commits.is_empty()) {
            (false, _) => Condition::Any,
            (true, true) => Condition::All,
            (true, false) => Condition::Never,
        },
    })
}

/// Shannon entropy as gitleaks computes it: counts over characters, divided
/// by the length in bytes.
pub(super) fn entropy(secret: &[u8]) -> f64 {
    if secret.is_empty() {
        return 0.0;
    }
    #[allow(
        clippy::cast_precision_loss,
        reason = "a secret is far shorter than 2^52 bytes"
    )]
    let inv = 1.0 / secret.len() as f64;
    let term = |n: u32| {
        let f = f64::from(n) * inv;
        -f * f.log2()
    };
    if secret.is_ascii() {
        let mut counts = [0_u32; 128];
        for &b in secret {
            counts[usize::from(b)] += 1;
        }
        return counts.iter().filter(|&&n| n > 0).map(|&n| term(n)).sum();
    }
    let text = String::from_utf8_lossy(secret);
    let mut counts: HashMap<char, u32> = HashMap::new();
    for c in text.chars() {
        *counts.entry(c).or_default() += 1;
    }
    counts.values().map(|&n| term(n)).sum()
}

/// Whether any of `allows` drops the match `m` in `text`, read as a rule's
/// match would be: the match is both the secret and the whole match.
pub(super) fn allowlisted(allows: &[Allow], text: &[u8], m: Range<usize>) -> bool {
    if allows.is_empty() {
        return false;
    }
    let start = memchr::memrchr(b'\n', &text[..m.start]).map_or(0, |p| p + 1);
    let end = memchr::memchr(b'\n', &text[m.end..]).map_or(text.len(), |p| m.end + p);
    let found = &text[m];
    allows
        .iter()
        .any(|a| a.allows(found, found, &text[start..end], &mut None))
}

impl Allow {
    pub(super) fn memory_usage(&self) -> usize {
        self.regexes.iter().map(Regex::memory_usage).sum()
    }

    /// `line_hit` caches the line regexes' answer, which is the same for
    /// every match on one line.
    fn allows(
        &self,
        secret: &[u8],
        matched: &[u8],
        line: &[u8],
        line_hit: &mut Option<bool>,
    ) -> bool {
        if self.condition == Condition::Never {
            return false;
        }
        let any = |target: &[u8]| self.regexes.iter().any(|r| r.is_match(target));
        let regex = match self.target {
            Target::Secret => any(secret),
            Target::Match => any(matched),
            Target::Line => *line_hit.get_or_insert_with(|| any(line)),
        };
        let stop = self.stopwords.as_ref().is_some_and(|ac| {
            if secret.is_ascii() {
                ac.is_match(secret)
            } else {
                ac.is_match(String::from_utf8_lossy(secret).to_lowercase().as_bytes())
            }
        });
        match self.condition {
            Condition::All => {
                (self.regexes.is_empty() || regex) && (self.stopwords.is_none() || stop)
            }
            Condition::Any | Condition::Never => regex || stop,
        }
    }
}

/// A rule whose regex is a run of up to `reach` bytes of one class, then an
/// expression every match of which starts with one of the rule's keywords.
///
/// Every match then starts in the run of the class that ends at one of its
/// keywords, no further back than `reach` and not before the last match. The
/// earliest such start for a keyword reaches every match through it, so the
/// rule's own regex held to start there gives the match `find_iter` would.
#[derive(Debug)]
pub(super) struct KeywordStarts {
    /// Every occurrence of the rule's keywords, without ASCII case.
    keywords: AhoCorasick,
    class: [bool; 256],
    reach: usize,
}

impl KeywordStarts {
    /// The starts for `re`, or `None` when `re` isn't a bounded run then
    /// keyword-led text.
    pub(super) fn new(re: &str, keywords: &[String]) -> Option<Self> {
        use regex_syntax::hir::literal::{ExtractKind, Extractor};
        use regex_syntax::hir::{Class, Hir, HirKind};
        if keywords.iter().any(String::is_empty) {
            return None;
        }
        let hir = regex_syntax::ParserBuilder::new()
            .unicode(false)
            .utf8(false)
            .build()
            .parse(&from_re2(re))
            .ok()?;
        let HirKind::Concat(parts) = hir.kind() else {
            return None;
        };
        let HirKind::Repetition(run) = parts.first()?.kind() else {
            return None;
        };
        let HirKind::Class(Class::Bytes(bytes)) = run.sub.kind() else {
            return None;
        };
        let reach = usize::try_from(run.max?).ok()?;
        let mut class = [false; 256];
        for r in bytes.ranges() {
            for b in r.start()..=r.end() {
                class[usize::from(b)] = true;
            }
        }
        // Every match of what follows the run starts with one of these. A
        // set too large to list is no set.
        let mut extract = Extractor::new();
        extract
            .kind(ExtractKind::Prefix)
            .limit_class(4)
            .limit_repeat(4)
            .limit_literal_len(64)
            .limit_total(4096);
        let rest = Hir::concat(parts.get(1..)?.to_vec());
        let prefixes = extract.extract(&rest);
        let words: Vec<Vec<u8>> = keywords
            .iter()
            .map(|k| k.as_bytes().to_ascii_lowercase())
            .collect();
        let covered = prefixes.literals().is_some_and(|literals| {
            !literals.is_empty()
                && literals.iter().all(|l| {
                    let l = l.as_bytes().to_ascii_lowercase();
                    words.iter().any(|w| l.starts_with(w))
                })
        });
        if run.min != 0 || !covered {
            return None;
        }
        let keywords = AhoCorasick::builder()
            .ascii_case_insensitive(true)
            .build(keywords)
            .ok()?;
        Some(Self {
            keywords,
            class,
            reach,
        })
    }

    /// The matches `regex.find_iter(text)` gives, into `out`.
    pub(super) fn matches(&self, regex: &Regex, text: &[u8], out: &mut Vec<Range<usize>>) {
        let mut hits: Vec<usize> = self
            .keywords
            .find_overlapping_iter(text)
            .map(|m| m.start())
            .collect();
        hits.sort_unstable();
        hits.dedup();
        let (mut end, mut tried) = (0, None);
        for hit in hits {
            if hit < end {
                continue;
            }
            let mut start = hit;
            while start > end
                && hit - start < self.reach
                && self.class[usize::from(text[start - 1])]
            {
                start -= 1;
            }
            if tried == Some(start) {
                continue;
            }
            tried = Some(start);
            let input = Input::new(text).range(start..).anchored(Anchored::Yes);
            if let Some(m) = regex.search(&input) {
                out.push(m.range());
                end = m.end().max(m.start() + 1);
            }
        }
    }
}

/// A rule's matches, from the whole text or from its keywords.
enum Found<'r, 'h> {
    All(regex_automata::meta::FindMatches<'r, 'h>),
    Listed(std::vec::IntoIter<Range<usize>>),
}

impl Iterator for Found<'_, '_> {
    type Item = Range<usize>;

    fn next(&mut self) -> Option<Range<usize>> {
        match self {
            Self::All(all) => all.next().map(|m| m.range()),
            Self::Listed(listed) => listed.next(),
        }
    }
}

impl Rule {
    /// Call `on` with the outcome of every match in `text`.
    pub(super) fn run(
        &self,
        text: &[u8],
        global: &[Allow],
        honour_marker: bool,
        caps: &mut Captures,
        mut on: impl FnMut(Outcome),
    ) {
        // The lines the last match spanned, and whether they hold the marker.
        // Matches come in order, so each byte is scanned for lines once.
        let mut lines: Option<(Range<usize>, bool)> = None;
        // Each allowlist's line-regex answer for `lines`, cleared when it moves.
        let mut line_hits: Vec<Option<bool>> = Vec::new();
        let mut reusable = false;
        let found = self.starts.as_ref().map_or_else(
            || Found::All(self.regex.find_iter(text)),
            |starts| {
                let mut listed = Vec::new();
                starts.matches(&self.regex, text, &mut listed);
                Found::Listed(listed.into_iter())
            },
        );
        for matched in found {
            let (span, marked) = match &lines {
                Some((span, marked))
                    if reusable && span.start <= matched.start && matched.end <= span.end =>
                {
                    (span.clone(), *marked)
                }
                _ => {
                    let floor = match &lines {
                        Some((s, _)) if s.start <= matched.start => s.start,
                        _ => 0,
                    };
                    let start = memchr::memrchr(b'\n', &text[floor..matched.start])
                        .map_or(floor, |p| floor + p + 1);
                    let end = memchr::memchr(b'\n', &text[matched.end..])
                        .map_or(text.len(), |p| matched.end + p);
                    let lines_text = &text[start..end];
                    let marked = honour_marker
                        && memchr::memmem::find(lines_text, b"gitleaks:allow").is_some();
                    // A span over several lines serves only the match that made it.
                    let one_line = memchr::memchr(b'\n', lines_text).is_none();
                    lines = Some((start..end, marked));
                    reusable = one_line;
                    line_hits.fill(None);
                    (start..end, marked)
                }
            };
            if marked {
                continue;
            }
            let line = &text[span];
            let Some(local) = self.secret_in(&text[matched.clone()], caps) else {
                continue;
            };
            let secret = matched.start + local.start..matched.start + local.end;
            let bytes = &text[secret.clone()];
            if self.entropy.is_some_and(|min| entropy(bytes) <= min) {
                on(Outcome::LowEntropy);
                continue;
            }
            let whole = &text[matched.clone()];
            line_hits.resize(global.len() + self.allow.len(), None);
            let allowed = global
                .iter()
                .chain(&self.allow)
                .zip(line_hits.iter_mut())
                .any(|(a, hit)| a.allows(bytes, whole, line, hit));
            if allowed {
                on(Outcome::Allowlisted);
                continue;
            }
            on(Outcome::Found { matched, secret });
        }
    }

    /// The secret within one match, as gitleaks picks it: the regex re-run on
    /// the match, then the configured group, else the first non-empty group,
    /// else the whole match. `None` when the configured group doesn't exist.
    fn secret_in(&self, whole: &[u8], caps: &mut Captures) -> Option<Range<usize>> {
        // A regex with no group of its own has nothing to pick from.
        if caps.group_info().group_len(PatternID::ZERO) < 2 {
            return Some(0..whole.len());
        }
        // The match nearly always starts the text it is re-run on, and a
        // search held to the start can read the groups in one pass. Where
        // it finds nothing, a search from anywhere runs instead and gives the
        // same answer.
        self.regex
            .search_captures(&Input::new(whole).anchored(Anchored::Yes), caps);
        if !caps.is_match() {
            self.regex.search_captures(&Input::new(whole), caps);
        }
        let groups = caps.group_len();
        if groups < 2 {
            return Some(0..whole.len());
        }
        match self.secret_group {
            Some(g) if g >= groups => None,
            Some(g) => Some(caps.get_group(g).map_or(0..0, |s| s.range())),
            None => Some(
                (1..groups)
                    .find_map(|g| caps.get_group(g).filter(|s| !s.is_empty()))
                    .map_or(0..whole.len(), |s| s.range()),
            ),
        }
    }
}