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
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
// Project:   grippo
// File:      src/scrub/pii.rs
// Purpose:   Personal data found by pattern and confirmed by its own check
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! The PII layer.
//!
//! Each validator finds candidates with its pattern, then keeps one only when
//! its check passes and, for the national ids, a keyword sits in the 30
//! characters before it. Validators run in a fixed order, each over the text
//! the last one wrote, so a token one writes is never a candidate for the next.

use std::ops::Range;

use regex_automata::meta::{BuildError, Regex};
use regex_automata::{Anchored, Input, MatchKind, PatternSet};
use regex_syntax::hir::{Hir, HirKind, Look, Repetition};

/// Characters before a candidate searched for a keyword.
const PROXIMITY: usize = 30;

/// How a candidate is confirmed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Check {
    /// Luhn over 13 to 19 ASCII digits.
    Luhn,
    /// ISO 7064 mod 97 and the country's IBAN format.
    Iban,
    /// The pattern is the check.
    Email,
    /// libphonenumber parses it as an international number and calls it valid.
    #[cfg(feature = "scrub-phone")]
    Phone,
    /// The ATO's mod 89 check over 11 digits.
    AuAbn,
    /// The ASIC check digit over 9 digits.
    AuAcn,
    /// The ATO's mod 11 check over 8 or 9 digits.
    AuTfn,
    /// The Medicare check digit over 10 or 11 digits.
    AuMedicare,
}

/// One validator: its report id, pattern, check and context keywords.
#[derive(Debug)]
pub(super) struct Pii {
    pub id: &'static str,
    pattern: &'static str,
    regex: Regex,
    check: Check,
    keywords: &'static [&'static str],
}

/// The email body, found from a start the scanner has already checked.
const EMAIL_BODY: &str = r"[\w.+\-]+(?:%(?:25)?2[Bb][\w.+\-]*)*(?:@|%(?:25)?40)[\w\-]+(?:\.[\w\-]+)*\.[\w\-]*[^\W\d_][\w\-]*\b";

/// Every validator, in the order they run.
pub(super) fn defaults() -> Result<Vec<Pii>, Box<BuildError>> {
    let table: &[(&'static str, &'static str, Check, &'static [&'static str])] = &[
        ("credit-card", r"\b(?:\d[ -]?){12,18}\d\b", Check::Luhn, &[]),
        (
            "iban",
            r"\b[A-Z]{2}\d{2}(?:[ ]?[A-Z0-9]){11,30}\b",
            Check::Iban,
            &[],
        ),
        ("email", EMAIL_BODY, Check::Email, &[]),
        #[cfg(feature = "scrub-phone")]
        ("phone", r"\+?\d[\d \-.()]{6,20}\d", Check::Phone, &[]),
        (
            "au-abn",
            r"\b\d{2}[ ]?\d{3}[ ]?\d{3}[ ]?\d{3}\b",
            Check::AuAbn,
            &["abn", "australian business number"],
        ),
        (
            "au-acn",
            r"\b\d{3}[ ]?\d{3}[ ]?\d{3}\b",
            Check::AuAcn,
            &["acn", "australian company number"],
        ),
        (
            "au-medicare",
            r"\b\d{4}[ ]?\d{5}[ ]?\d(?:[ ]?\d)?\b",
            Check::AuMedicare,
            &["medicare", "medicare card", "medicare number"],
        ),
        (
            "au-tfn",
            r"\b\d{3}[ ]?\d{3}[ ]?\d{2,3}\b",
            Check::AuTfn,
            &["tfn", "tax file number"],
        ),
    ];
    table
        .iter()
        .map(|&(id, re, check, keywords)| {
            Ok(Pii {
                id,
                pattern: re,
                regex: Regex::new(re).map_err(Box::new)?,
                check,
                keywords,
            })
        })
        .collect()
}

/// Every validator's pattern in one search, so a text is read once to learn
/// which validators have a candidate in it at all.
#[derive(Debug)]
pub(super) struct Gate {
    any: Regex,
    /// The same patterns with their word boundaries left out, for a text
    /// past ASCII. It matches wherever they do and in a few places more, and
    /// its DFA never meets a boundary at a character past ASCII, which
    /// sends the whole text to a far slower engine.
    loose: Regex,
    /// The validator each of `any`'s patterns belongs to.
    validators: Vec<usize>,
    /// Validators `any` leaves out, which run on every text.
    always: u32,
}

/// `hir` with every word boundary taken out, which matches wherever `hir`
/// does.
fn without_boundaries(hir: &Hir) -> Hir {
    let each = |parts: &[Hir]| parts.iter().map(without_boundaries).collect();
    match hir.kind() {
        HirKind::Look(Look::WordUnicode | Look::WordAscii) => Hir::empty(),
        HirKind::Capture(c) => without_boundaries(&c.sub),
        HirKind::Repetition(r) => Hir::repetition(Repetition {
            sub: Box::new(without_boundaries(&r.sub)),
            ..r.clone()
        }),
        HirKind::Concat(parts) => Hir::concat(each(parts)),
        HirKind::Alternation(parts) => Hir::alternation(each(parts)),
        _ => hir.clone(),
    }
}

impl Gate {
    /// A gate over `pii`. The email validator stays out: its pattern is tried
    /// from starts its own scan picks, and that scan is its gate.
    pub(super) fn new(pii: &[Pii]) -> Result<Self, Box<BuildError>> {
        let (mut exact, mut loose) = (Vec::new(), Vec::new());
        let mut validators = Vec::new();
        let mut always = 0_u32;
        for (k, validator) in pii.iter().enumerate() {
            // A pattern left out of the search runs on every text.
            match regex_syntax::parse(validator.pattern) {
                Ok(hir) if validator.check != Check::Email => {
                    loose.push(without_boundaries(&hir));
                    exact.push(hir);
                    validators.push(k);
                }
                _ => always |= 1 << k,
            }
        }
        // Every pattern that matches, not only the first at each position.
        let build = |hirs: &[Hir]| {
            Regex::builder()
                .configure(Regex::config().match_kind(MatchKind::All))
                .build_many_from_hir(hirs)
                .map_err(Box::new)
        };
        Ok(Self {
            any: build(&exact)?,
            loose: build(&loose)?,
            validators,
            always,
        })
    }

    pub(super) fn memory_usage(&self) -> usize {
        self.any.memory_usage() + self.loose.memory_usage()
    }

    /// A set for [`Self::candidates`] to reuse.
    pub(super) fn scratch(&self) -> PatternSet {
        PatternSet::new(self.any.pattern_len())
    }

    /// A bit for each validator whose pattern matches somewhere in `text`,
    /// or that the gate doesn't cover.
    pub(super) fn candidates(&self, text: &str, seen: &mut PatternSet) -> u32 {
        if seen.capacity() != self.any.pattern_len() {
            *seen = self.scratch();
        }
        seen.clear();
        let gate = if text.is_ascii() {
            &self.any
        } else {
            &self.loose
        };
        gate.which_overlapping_matches(&Input::new(text), seen);
        seen.iter().fold(self.always, |mask, pattern| {
            mask | 1 << self.validators[pattern.as_usize()]
        })
    }
}

impl Pii {
    pub(super) fn memory_usage(&self) -> usize {
        self.regex.memory_usage()
    }

    /// The candidates in `text` this validator confirms, left to right.
    pub(super) fn confirmed(&self, text: &str, mut on: impl FnMut(Range<usize>)) {
        let mut keep = |m: Range<usize>| {
            let candidate = &text[m.clone()];
            let anchored = match self.check {
                // A Luhn-valid digit run alone is too often an id or an epoch.
                Check::Luhn => card_grouped(candidate) || has_word(text, m.start, &CARD_WORDS),
                _ => self.keywords.is_empty() || has_keyword(text, m.start, self.keywords),
            };
            if anchored && self.check(candidate) {
                on(m);
            }
        };
        if self.check == Check::Email {
            email_candidates(&self.regex, text, &mut keep);
        } else {
            for m in self.regex.find_iter(text.as_bytes()) {
                keep(m.range());
            }
        }
    }

    fn check(&self, candidate: &str) -> bool {
        match self.check {
            Check::Luhn => luhn(candidate),
            Check::Iban => iban(candidate),
            Check::Email => !systemd_unit(candidate),
            #[cfg(feature = "scrub-phone")]
            Check::Phone => phone(candidate),
            Check::AuAbn => au_abn(candidate),
            Check::AuAcn => au_acn(candidate),
            Check::AuTfn => au_tfn(candidate),
            Check::AuMedicare => au_medicare(candidate),
        }
    }
}

/// systemd's unit types, none of them a TLD mail is sent to.
const UNIT_TYPES: [&str; 11] = [
    "service",
    "socket",
    "device",
    "mount",
    "automount",
    "swap",
    "target",
    "path",
    "timer",
    "slice",
    "scope",
];

/// `true` for a templated systemd unit such as `user@1000.service`, which the
/// email body also matches.
fn systemd_unit(candidate: &str) -> bool {
    candidate
        .rsplit_once('.')
        .is_some_and(|(_, last)| UNIT_TYPES.contains(&last))
}

/// Words that make a Luhn-valid number a card, wherever it is grouped.
const CARD_WORDS: [&str; 7] = [
    "card",
    "creditcard",
    "cc",
    "pan",
    "visa",
    "mastercard",
    "amex",
];

/// Where the [`PROXIMITY`] characters before `at` start.
fn window_start(text: &str, at: usize) -> usize {
    text[..at]
        .char_indices()
        .rev()
        .nth(PROXIMITY - 1)
        .map_or(0, |(i, _)| i)
}

/// `true` when a keyword sits in the [`PROXIMITY`] characters before `at`,
/// compared lower-cased.
fn has_keyword(text: &str, at: usize, keywords: &[&str]) -> bool {
    let before = &text.as_bytes()[window_start(text, at)..at];
    keywords.iter().any(|k| {
        before
            .windows(k.len())
            .any(|w| w.eq_ignore_ascii_case(k.as_bytes()))
    })
}

/// As [`has_keyword`], with no ASCII letter or digit either side of the
/// word, so `cc` in `access` doesn't count and `cc` in `cc_number` does.
fn has_word(text: &str, at: usize, words: &[&str]) -> bool {
    let b = text.as_bytes();
    let alnum = |i: Option<usize>| {
        i.and_then(|i| b.get(i))
            .is_some_and(u8::is_ascii_alphanumeric)
    };
    (window_start(text, at)..at).any(|i| {
        words.iter().any(|w| {
            b.get(i..i + w.len())
                .is_some_and(|s| i + w.len() <= at && s.eq_ignore_ascii_case(w.as_bytes()))
                && !alnum(i.checked_sub(1))
                && !alnum(Some(i + w.len()))
                && !in_token(b, i)
        })
    })
}

/// `true` when byte `i` sits inside a token grippo wrote, `[CREDIT_CARD_REDACTED]`
/// or `[CREDIT_CARD_<16 hex>]`, so a second pass reads it as no word.
fn in_token(b: &[u8], i: usize) -> bool {
    let inner = |c: &u8| c.is_ascii_alphanumeric() || *c == b'_';
    let start = b[..i].iter().rposition(|c| !inner(c));
    let end = b[i..].iter().position(|c| !inner(c)).map(|n| i + n);
    let (Some(open), Some(close)) = (start, end) else {
        return false;
    };
    if b[open] != b'[' || b[close] != b']' {
        return false;
    }
    let body = &b[open + 1..close];
    let hash = body.len() > 17
        && body[body.len() - 17] == b'_'
        && body[body.len() - 16..]
            .iter()
            .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(c));
    body.ends_with(b"_REDACTED") || hash
}

/// `true` when `candidate` is grouped as a card is printed: 4-4-4-4, 4-6-5 or
/// 4-6-4, with one separator, a space or a dash, throughout.
fn card_grouped(candidate: &str) -> bool {
    let Some(sep) = candidate.chars().find(|&c| c == ' ' || c == '-') else {
        return false;
    };
    let mut lens = [0_usize; 4];
    let mut n = 0;
    for group in candidate.split(sep) {
        if n == lens.len() || group.is_empty() || !group.bytes().all(|b| b.is_ascii_digit()) {
            return false;
        }
        lens[n] = group.len();
        n += 1;
    }
    matches!(lens[..n], [4, 4, 4, 4] | [4, 6, 5 | 4])
}

const fn is_hex(b: Option<&u8>) -> bool {
    matches!(b, Some(b) if b.is_ascii_hexdigit())
}

/// `true` when the three bytes before `at` are `%` and two hex digits.
fn after_escape(b: &[u8], at: usize) -> bool {
    at >= 3 && b[at - 3] == b'%' && is_hex(b.get(at - 2)) && is_hex(b.get(at - 1))
}

/// Where an address may start: a word
/// boundary not inside a `%XX` escape, the end of an escape that doesn't
/// open `%25XX`, or the end of a double-encoded `%25XX`.
fn email_may_start(text: &str, at: usize) -> bool {
    let b = text.as_bytes();
    let hex_follows = is_hex(b.get(at)) && is_hex(b.get(at + 1));
    let word = |c: Option<char>| c.is_some_and(is_word);
    let boundary = word(text[..at].chars().next_back()) != word(text[at..].chars().next());
    let in_escape = at >= 1 && b[at - 1] == b'%' && hex_follows;
    let opens_double = at >= 3 && &b[at - 3..at] == b"%25" && hex_follows;
    let after_double =
        at >= 5 && &b[at - 5..at - 2] == b"%25" && is_hex(b.get(at - 2)) && is_hex(b.get(at - 1));
    (boundary && !in_escape) || (after_escape(b, at) && !opens_double) || after_double
}

/// Addresses in `text`, each the leftmost body match from a permitted start.
///
/// A body holds an at sign, plain or escaped, where its local part ends, so
/// only the text that runs up to one is read.
fn email_candidates(body: &Regex, text: &str, on: &mut impl FnMut(Range<usize>)) {
    let bytes = text.as_bytes();
    // Where the last address ended: no later one starts before it.
    let mut done = 0;
    let mut search = 0;
    while let Some(found) = memchr::memchr2(b'@', b'%', &bytes[search..]) {
        let sign = search + found;
        search = sign + 1;
        let rest = &bytes[sign..];
        let is_sign = rest[0] == b'@' || rest.starts_with(b"%40") || rest.starts_with(b"%2540");
        if !is_sign || sign < done {
            continue;
        }
        // Every start whose local part ends at `sign` lies in the run of
        // local characters and `%` before it.
        let mut at = sign;
        while at > done {
            match text[..at].chars().next_back() {
                Some(c) if is_local(c) || c == '%' => at -= c.len_utf8(),
                _ => break,
            }
        }
        while let Some(c) = text[at..sign].chars().next() {
            if !(is_local(c) && email_may_start(text, at)) {
                at += c.len_utf8();
                continue;
            }
            let end = local_part_end(text, at);
            if end != sign {
                // It ends at an earlier sign, tried when that one was read,
                // or at a `%` that opens no escape.
                at = end.max(at + c.len_utf8());
                continue;
            }
            let input = Input::new(bytes).range(at..).anchored(Anchored::Yes);
            if let Some(m) = body.find(input) {
                on(m.range());
                done = m.end();
                search = search.max(done);
            }
            // A body from any later start in this local part would extend to
            // one from `at`, so none matches.
            break;
        }
    }
}

fn is_local(c: char) -> bool {
    is_word(c) || matches!(c, '.' | '+' | '-')
}

/// `\w` as the patterns read it, with ASCII answered without the tables.
fn is_word(c: char) -> bool {
    if c.is_ascii() {
        c.is_ascii_alphanumeric() || c == '_'
    } else {
        regex_syntax::is_word_character(c)
    }
}

/// Where the body's local part `[\w.+\-]+(?:%(?:25)?2[Bb][\w.+\-]*)*` can
/// run to from `start`, at its longest.
fn local_part_end(text: &str, start: usize) -> usize {
    let mut at = start;
    loop {
        at += text[at..]
            .chars()
            .take_while(|&c| is_local(c))
            .map(char::len_utf8)
            .sum::<usize>();
        let rest = &text.as_bytes()[at..];
        let escape = [3, 5].into_iter().find(|&n| {
            rest.len() >= n
                && rest[0] == b'%'
                && (n == 3 || &rest[1..3] == b"25")
                && rest[n - 2] == b'2'
                && matches!(rest[n - 1], b'B' | b'b')
        });
        match escape {
            Some(n) => at += n,
            None => return at,
        }
    }
}

/// `candidate` without the characters `drop` accepts, when what is left is
/// all ASCII digits.
fn digits(candidate: &str, drop: impl Fn(char) -> bool) -> Option<Digits> {
    let mut d = Digits {
        buf: [0; 24],
        len: 0,
    };
    for c in candidate.chars().filter(|&c| !drop(c)) {
        let digit = c
            .is_ascii_digit()
            .then(|| c.to_digit(10).and_then(|n| u8::try_from(n).ok()))
            .flatten()?;
        *d.buf.get_mut(d.len)? = digit;
        d.len += 1;
    }
    Some(d)
}

/// Up to 24 digit values, held without allocating. Every check here needs 19
/// at most.
struct Digits {
    buf: [u8; 24],
    len: usize,
}

impl std::ops::Deref for Digits {
    type Target = [u8];

    fn deref(&self) -> &[u8] {
        &self.buf[..self.len]
    }
}

/// Parse with no default region, then check the number is one a carrier
/// could assign.
#[cfg(feature = "scrub-phone")]
fn phone(candidate: &str) -> bool {
    use rlibphonenumber::PHONE_NUMBER_UTIL;
    PHONE_NUMBER_UTIL
        .parse(candidate, None)
        .is_ok_and(|n| PHONE_NUMBER_UTIL.is_valid_number(&n))
}

fn luhn(candidate: &str) -> bool {
    let Some(d) = digits(candidate, |c| c == ' ' || c == '-') else {
        return false;
    };
    if !(13..=19).contains(&d.len()) {
        return false;
    }
    let sum: u32 = d
        .iter()
        .rev()
        .enumerate()
        .map(|(i, &n)| {
            let n = u32::from(n);
            if i % 2 == 1 {
                let x = n * 2;
                x / 10 + x % 10
            } else {
                n
            }
        })
        .sum();
    sum.is_multiple_of(10)
}

fn iban(candidate: &str) -> bool {
    let compact: String = candidate
        .chars()
        .filter(|c| !matches!(c, ' ' | '-' | '.'))
        .collect::<String>()
        .trim()
        .to_uppercase();
    compact.parse::<iban::Iban>().is_ok()
}

/// stdnum's `compact` for the AU ids: spaces out, then all ASCII digits.
fn au_digits(candidate: &str) -> Option<Digits> {
    digits(candidate.trim(), |c| c == ' ')
}

fn au_abn(candidate: &str) -> bool {
    let Some(d) = au_digits(candidate) else {
        return false;
    };
    if d.len() != 11 {
        return false;
    }
    let weights: [i64; 9] = [3, 5, 7, 9, 11, 13, 15, 17, 19];
    let s: i64 = weights
        .iter()
        .zip(&d[2..])
        .map(|(w, &n)| -w * i64::from(n))
        .sum();
    let check = 11 + (s - 1).rem_euclid(89);
    check == i64::from(d[0]) * 10 + i64::from(d[1])
}

fn au_acn(candidate: &str) -> bool {
    let Some(d) = au_digits(candidate) else {
        return false;
    };
    if d.len() != 9 {
        return false;
    }
    let s: i64 = d[..8]
        .iter()
        .zip(-8_i64..)
        .map(|(&n, w)| i64::from(n) * w)
        .sum();
    s.rem_euclid(10) == i64::from(d[8])
}

fn au_tfn(candidate: &str) -> bool {
    let Some(d) = au_digits(candidate) else {
        return false;
    };
    if d.len() != 8 && d.len() != 9 {
        return false;
    }
    let weights = [1, 4, 3, 7, 5, 8, 6, 9, 10];
    let s: u32 = weights
        .iter()
        .zip(d.iter())
        .map(|(w, &n)| w * u32::from(n))
        .sum();
    s.is_multiple_of(11)
}

fn au_medicare(candidate: &str) -> bool {
    let Some(d) = digits(candidate, char::is_whitespace) else {
        return false;
    };
    if d.len() != 10 && d.len() != 11 {
        return false;
    }
    let issue = d.get(10).copied().unwrap_or(1);
    if !(2..=6).contains(&d[0]) || issue == 0 {
        return false;
    }
    let weights = [1, 3, 7, 9, 1, 3, 7, 9];
    let s: u32 = weights
        .iter()
        .zip(d.iter())
        .map(|(w, &n)| w * u32::from(n))
        .sum();
    s % 10 == u32::from(d[8])
}

#[cfg(test)]
#[path = "pii_tests.rs"]
mod tests;