use std::borrow::Cow;
use std::ops::Range;
use std::sync::LazyLock;
use regex_automata::meta::{BuildError, Regex};
use regex_automata::{Anchored, Input, MatchKind, PatternSet};
use regex_syntax::hir::{Class, Hir, HirKind, Look, Repetition};
use super::classes::{class_ranges, range_of};
use super::field::{is_ignorable, is_mark};
static DECIMALS: LazyLock<Vec<(u32, u32)>> = LazyLock::new(|| class_ranges(r"\d"));
static DASHES: LazyLock<Vec<(u32, u32)>> = LazyLock::new(|| class_ranges(r"\p{Pd}"));
pub(super) fn decimal(c: char) -> Option<u8> {
if let Some(d) = c.to_digit(10) {
return u8::try_from(d).ok();
}
if c.is_ascii() {
return None;
}
let (lo, _) = range_of(&DECIMALS, c)?;
u8::try_from((u32::from(c) - lo) % 10).ok()
}
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.+\-]+(?:'[\w.+\-]+|%(?:25)?2[Bb][\w.+\-]*)*(?:@|%(?:25)?40)[\w\-]+(?:[.\x{3002}\x{ff0e}\x{ff61}][\w\-]+)*[.\x{3002}\x{ff0e}\x{ff61}][\w\-]*\p{L}[\w\-]*\b";
const IGNORABLE: &str = r"\x{ad}\x{34f}\x{61c}\x{115f}\x{1160}\x{17b4}\x{17b5}\x{180b}-\x{180f}\x{200b}-\x{200f}\x{202a}-\x{202e}\x{2060}-\x{206f}\x{3164}\x{fe00}-\x{fe0f}\x{feff}\x{ffa0}\x{fff0}-\x{fff8}\x{e0000}-\x{e0fff}";
static CARD_PATTERN: LazyLock<String> = LazyLock::new(|| {
let gap = format!(r"[{IGNORABLE}]*[\p{{Zs}}\p{{Pd}}]?[{IGNORABLE}]*");
digit_run(&format!(r"(?:{gap}\d){{11,17}}{gap}"))
});
fn digit_run(body: &str) -> String {
format!(r"(?:(?-u:\b)[0-9]|[\d--[0-9]]){body}(?:[0-9](?-u:\b)|[\d--[0-9]])")
}
static AU_PATTERNS: LazyLock<[String; 4]> = LazyLock::new(|| {
[
digit_run(r"\d\p{Zs}?\d{3}\p{Zs}?\d{3}\p{Zs}?\d{2}"),
digit_run(r"\d{2}\p{Zs}?\d{3}\p{Zs}?\d{2}"),
digit_run(r"\d{3}\p{Zs}?\d{5}\p{Zs}?(?:\d\p{Zs}?)?"),
digit_run(r"\d{2}\p{Zs}?\d{3}\p{Zs}?\d{1,2}"),
]
});
pub(super) fn defaults() -> Result<Vec<Pii>, Box<BuildError>> {
let [abn, acn, medicare, tfn] = &*AU_PATTERNS;
let table: &[(&'static str, &'static str, Check, &'static [&'static str])] = &[
("credit-card", CARD_PATTERN.as_str(), Check::Luhn, &[]),
(
"iban",
r"(?-u:\b)[A-Z]{2}\d{2}(?:\p{Zs}?[A-Z0-9]){11,30}(?-u:\b)",
Check::Iban,
&[],
),
("email", EMAIL_BODY, Check::Email, &[]),
#[cfg(feature = "scrub-phone")]
("phone", r"\+?\d[\d \-.()]{6,20}\d", Check::Phone, &[]),
(
"au-abn",
abn,
Check::AuAbn,
&["abn", "australian business number"],
),
(
"au-acn",
acn,
Check::AuAcn,
&["acn", "australian company number"],
),
(
"au-medicare",
medicare,
Check::AuMedicare,
&["medicare", "medicare card", "medicare number"],
),
("au-tfn", tfn, 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()
.filter(|part| !matches!(part.kind(), HirKind::Class(c) if ascii_ranges(c).is_empty()))
.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>)) {
for m in merge_spans(self.confirmed_each(text)) {
on(m);
}
}
pub(super) fn confirmed_each(&self, text: &str) -> Vec<Range<usize>> {
match self.check {
Check::Email => {
let mut found = Vec::new();
email_candidates(&self.regex, text, &mut |m| {
if self.accepts(text, &m) {
found.push(m);
}
});
found
}
Check::Luhn => self.cards(text),
_ => self
.regex
.find_iter(text.as_bytes())
.map(|m| m.range())
.filter(|m| self.accepts(text, m))
.collect(),
}
}
fn accepts(&self, text: &str, m: &Range<usize>) -> bool {
let candidate = match self.check {
Check::Luhn => without_ignorable(&text[m.clone()]),
_ => Cow::Borrowed(&text[m.clone()]),
};
let anchored = match self.check {
Check::Luhn => {
card_grouped(&candidate)
|| has_word(text, m.start, &CARD_WORDS)
|| has_script_word(text, m.start)
}
_ => self.keywords.is_empty() || has_keyword(text, m.start, self.keywords),
};
anchored && self.check(&candidate)
}
fn cards(&self, text: &str) -> Vec<Range<usize>> {
let bytes = text.as_bytes();
let mut found = Vec::new();
let mut at = 0;
while let Some(m) = self.regex.find(Input::new(bytes).range(at..)) {
let wide = m.range();
at = wide.start + text[wide.start..].chars().next().map_or(1, char::len_utf8);
if text[..wide.start].chars().next_back().is_some_and(is_digit) {
continue;
}
let mut digits = 0;
for (i, c) in text[wide.clone()].char_indices() {
if !is_digit(c) {
continue;
}
digits += 1;
let end = wide.start + i + c.len_utf8();
if digits >= 13 && ends_a_card(text, end, c, end == wide.end) {
let card = wide.start..end;
if self.accepts(text, &card) {
found.push(card);
}
}
}
}
found
}
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 ends_a_card(text: &str, end: usize, last: char, longest: bool) -> bool {
let next = text[end..].chars().next();
if next.is_some_and(is_digit) {
return false;
}
longest
|| !last.is_ascii_digit()
|| !next.is_some_and(|c| c.is_ascii_alphanumeric() || c == '_')
}
pub(super) fn merge_spans(mut spans: Vec<Range<usize>>) -> Vec<Range<usize>> {
spans.sort_by_key(|r| (r.start, r.end));
let mut merged: Vec<Range<usize>> = Vec::with_capacity(spans.len());
for span in spans {
match merged.last_mut() {
Some(last) if span.start < last.end => last.end = last.end.max(span.end),
_ => merged.push(span),
}
}
merged
}
fn is_digit(c: char) -> bool {
decimal(c).is_some()
}
const SCRIPT_CARD_WORDS: [&str; 8] = [
"\u{5361}\u{53f7}",
"\u{4fe1}\u{7528}\u{5361}",
"\u{94f6}\u{884c}\u{5361}",
"\u{30ab}\u{30fc}\u{30c9}",
"\u{ce74}\u{b4dc}",
"\u{43a}\u{430}\u{440}\u{442}\u{430}",
"\u{43a}\u{430}\u{440}\u{442}\u{44b}",
"\u{43a}\u{430}\u{440}\u{442}\u{443}",
];
fn has_script_word(text: &str, at: usize) -> bool {
let window = &text[window_start(text, at)..at];
!window.is_ascii() && {
let lower = window.to_lowercase();
SCRIPT_CARD_WORDS.iter().any(|word| lower.contains(word))
}
}
fn without_ignorable(candidate: &str) -> Cow<'_, str> {
if candidate.is_ascii() || !candidate.chars().any(is_ignorable) {
return Cow::Borrowed(candidate);
}
Cow::Owned(candidate.chars().filter(|&c| !is_ignorable(c)).collect())
}
const PROXIMITY_READ: usize = PROXIMITY * 4;
fn window_start(text: &str, at: usize) -> usize {
let mut counted = 0;
for (read, (i, c)) in text[..at].char_indices().rev().enumerate() {
if !(is_mark(c) || is_ignorable(c)) {
counted += 1;
}
if counted == PROXIMITY || read + 1 == PROXIMITY_READ {
return i;
}
}
0
}
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 joins =
|c: Option<char>| c.is_some_and(|c| c.is_numeric() || c.is_lowercase() || c.is_uppercase());
(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()))
&& !joins(text[..i].chars().next_back())
&& !joins(text[i + w.len()..].chars().next())
&& !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() > 33
&& body[body.len() - 33] == b'_'
&& body[body.len() - 32..]
.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| is_group_separator(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.chars().all(|c| decimal(c).is_some()) {
return false;
}
lens[n] = group.chars().count();
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(),
Some('\'') if inner_quote(text, at - 1) => at -= 1,
_ => 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 if inner_quote(text, at) => at += 1,
None => return at,
}
}
}
fn inner_quote(text: &str, at: usize) -> bool {
text.as_bytes().get(at) == Some(&b'\'')
&& text[..at].chars().next_back().is_some_and(is_local)
&& text[at + 1..].chars().next().is_some_and(is_local)
}
fn is_group_separator(c: char) -> bool {
c.is_whitespace() || range_of(&DASHES, c).is_some()
}
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 = decimal(c)?;
*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, is_group_separator) 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| !(c == '.' || is_group_separator(c)))
.collect::<String>()
.trim()
.to_uppercase();
compact.parse::<iban::Iban>().is_ok()
}
fn au_digits(candidate: &str) -> Option<Digits> {
digits(candidate.trim(), is_group_separator)
}
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, is_group_separator) 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;