use std::ops::Range;
use regex_automata::meta::{BuildError, Regex};
use regex_automata::{Anchored, Input, MatchKind, PatternSet};
use regex_syntax::hir::{Class, Hir, HirKind, Look, Repetition};
const PROXIMITY: usize = 30;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Check {
Luhn,
Iban,
Email,
#[cfg(feature = "scrub-phone")]
Phone,
AuAbn,
AuAcn,
AuTfn,
AuMedicare,
}
#[derive(Debug)]
pub(super) struct Pii {
pub id: &'static str,
pattern: &'static str,
regex: Regex,
check: Check,
keywords: &'static [&'static str],
}
const EMAIL_BODY: &str = r"[\w.+\-]+(?:%(?:25)?2[Bb][\w.+\-]*)*(?:@|%(?:25)?40)[\w\-]+(?:\.[\w\-]+)*\.[\w\-]*[^\W\d_][\w\-]*\b";
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()
}
#[derive(Debug)]
pub(super) struct Gate {
any: Regex,
loose: Regex,
validators: Vec<usize>,
always: u32,
email: u32,
least: Vec<Least>,
}
#[derive(Debug, Clone, Copy)]
struct Least {
digits: usize,
bytes: usize,
}
impl Least {
fn of(hir: &Hir) -> Self {
Self {
digits: least_digits(hir),
bytes: hir.properties().minimum_len().unwrap_or(0),
}
}
}
fn ascii_ranges(class: &Class) -> Vec<(u32, u32)> {
match class {
Class::Unicode(c) => c
.iter()
.map(|r| (u32::from(r.start()), u32::from(r.end()).min(0x7F)))
.filter(|&(lo, hi)| lo <= hi)
.collect(),
Class::Bytes(c) => c
.iter()
.map(|r| (u32::from(r.start()), u32::from(r.end()).min(0x7F)))
.filter(|&(lo, hi)| lo <= hi)
.collect(),
}
}
fn least_digits(hir: &Hir) -> usize {
match hir.kind() {
HirKind::Literal(lit) => lit.0.iter().filter(|b| b.is_ascii_digit()).count(),
HirKind::Class(c) => {
let ranges = ascii_ranges(c);
let digits = |&(lo, hi): &(u32, u32)| lo >= u32::from(b'0') && hi <= u32::from(b'9');
usize::from(!ranges.is_empty() && ranges.iter().all(digits))
}
HirKind::Capture(c) => least_digits(&c.sub),
HirKind::Repetition(r) => {
least_digits(&r.sub).saturating_mul(usize::try_from(r.min).unwrap_or(usize::MAX))
}
HirKind::Concat(parts) => parts.iter().map(least_digits).sum(),
HirKind::Alternation(parts) => parts.iter().map(least_digits).min().unwrap_or(0),
HirKind::Empty | HirKind::Look(_) => 0,
}
}
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 {
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;
let mut email = 0_u32;
let mut least = Vec::new();
for (k, validator) in pii.iter().enumerate() {
match regex_syntax::parse(validator.pattern) {
Ok(hir) if validator.check != Check::Email => {
least.push(Least::of(&hir));
loose.push(without_boundaries(&hir));
exact.push(hir);
validators.push(k);
}
_ => {
always |= 1 << k;
if validator.check == Check::Email {
email |= 1 << k;
}
}
}
}
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,
email,
least,
})
}
pub(super) fn memory_usage(&self) -> usize {
self.any.memory_usage() + self.loose.memory_usage()
}
pub(super) fn scratch(&self) -> PatternSet {
PatternSet::new(self.any.pattern_len())
}
pub(super) fn may_find(&self, text: &[u8]) -> bool {
let digits = if text.is_ascii() {
text.iter().filter(|b| b.is_ascii_digit()).count()
} else {
usize::MAX
};
self.always & !self.email != 0
|| (self.email != 0 && memchr::memchr2(b'@', b'%', text).is_some())
|| self
.least
.iter()
.any(|l| digits >= l.digits && text.len() >= l.bytes)
}
pub(super) fn candidates(&self, text: &str, seen: &mut PatternSet) -> u32 {
if seen.capacity() != self.any.pattern_len() {
*seen = self.scratch();
}
seen.clear();
let ascii = text.is_ascii();
let digits = if ascii {
text.bytes().filter(u8::is_ascii_digit).count()
} else {
usize::MAX
};
let possible = self
.least
.iter()
.any(|l| digits >= l.digits && text.len() >= l.bytes);
if !possible {
return self.always;
}
let gate = if 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()
}
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 {
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),
}
}
}
const UNIT_TYPES: [&str; 11] = [
"service",
"socket",
"device",
"mount",
"automount",
"swap",
"target",
"path",
"timer",
"slice",
"scope",
];
fn systemd_unit(candidate: &str) -> bool {
candidate
.rsplit_once('.')
.is_some_and(|(_, last)| UNIT_TYPES.contains(&last))
}
const CARD_WORDS: [&str; 7] = [
"card",
"creditcard",
"cc",
"pan",
"visa",
"mastercard",
"amex",
];
fn window_start(text: &str, at: usize) -> usize {
text[..at]
.char_indices()
.rev()
.nth(PROXIMITY - 1)
.map_or(0, |(i, _)| i)
}
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()))
})
}
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)
})
})
}
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
}
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())
}
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))
}
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
}
fn email_candidates(body: &Regex, text: &str, on: &mut impl FnMut(Range<usize>)) {
let bytes = text.as_bytes();
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;
}
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 {
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);
}
break;
}
}
}
fn is_local(c: char) -> bool {
is_word(c) || matches!(c, '.' | '+' | '-')
}
fn is_word(c: char) -> bool {
if c.is_ascii() {
c.is_ascii_alphanumeric() || c == '_'
} else {
regex_syntax::is_word_character(c)
}
}
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,
}
}
}
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)
}
struct Digits {
buf: [u8; 24],
len: usize,
}
impl std::ops::Deref for Digits {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.buf[..self.len]
}
}
#[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()
}
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;