1#![cfg_attr(docsrs, feature(doc_cfg))]
2
3use std::cell::Cell;
4use std::collections::{BTreeMap, HashMap};
5use std::fmt;
6use std::ops::Range;
7
8use serde::{Deserialize, Serialize};
9use sha3::{Digest, Keccak256};
10use thiserror::Error;
11
12pub trait Detector: Send + Sync {
14 fn detect(&self, input: &str) -> Vec<Detection>;
16}
17
18#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
46pub enum PiiClass {
47 Email,
49 Name,
51 Location,
53 Organization,
55 Custom(String),
57}
58
59pub const BUILTIN_CLASS_NAMES: &[&str] = &["Email", "Name", "Location", "Organization"];
61
62pub const RESERVED_BUNDLED_FAMILIES: &[&str] = &[
67 "us-9-digit-id",
68 "iberian-id",
69 "payment-card-or-iban",
70 "phone-or-imei",
71 "vin-or-serial",
72 "mac-or-hex",
73 "passport-or-doc-support",
74 "national-13-digit",
75 "italian-cf-or-serial",
76 "german-personalausweis",
77 "swedish-personnummer",
78 "finnish-hetu",
79];
80
81#[derive(Debug, Clone, PartialEq, Eq)]
83#[non_exhaustive]
84pub struct CollisionMembership {
85 pub family: String,
87 pub variant: String,
89 pub precedence: u32,
91 pub mandatory_anchor: Option<String>,
93}
94
95impl CollisionMembership {
96 pub fn new(
98 family: impl Into<String>,
99 variant: impl Into<String>,
100 precedence: u32,
101 mandatory_anchor: Option<String>,
102 ) -> Self {
103 Self {
104 family: family.into(),
105 variant: variant.into(),
106 precedence,
107 mandatory_anchor,
108 }
109 }
110}
111
112impl PiiClass {
113 pub fn from_policy_name(input: &str) -> Option<Self> {
115 match input {
116 "email" => Some(Self::Email),
117 "name" => Some(Self::Name),
118 "location" => Some(Self::Location),
119 "organization" => Some(Self::Organization),
120 custom if custom.starts_with("custom:") => {
121 let name = custom.trim_start_matches("custom:");
122 (!name.trim().is_empty()).then(|| Self::custom(name))
123 }
124 _ => None,
125 }
126 }
127
128 pub fn builtin_variants() -> &'static [PiiClass] {
130 &[
131 PiiClass::Email,
132 PiiClass::Name,
133 PiiClass::Location,
134 PiiClass::Organization,
135 ]
136 }
137
138 pub fn custom(name: &str) -> Self {
140 let mut normalized = String::new();
141 let mut pending_underscore = false;
142 for ch in name.trim().chars() {
143 if ch.is_ascii_alphanumeric() {
144 if pending_underscore && !normalized.is_empty() {
145 normalized.push('_');
146 }
147 normalized.push(ch.to_ascii_lowercase());
148 pending_underscore = false;
149 } else {
150 pending_underscore = true;
151 }
152 }
153
154 Self::Custom(normalized)
155 }
156
157 pub fn as_custom_name(&self) -> Option<&str> {
159 match self {
160 Self::Custom(name) => Some(name.as_str()),
161 Self::Email | Self::Name | Self::Location | Self::Organization => None,
162 }
163 }
164
165 pub fn class_name(&self) -> String {
167 match self {
168 Self::Email => BUILTIN_CLASS_NAMES[0].to_string(),
169 Self::Name => BUILTIN_CLASS_NAMES[1].to_string(),
170 Self::Location => BUILTIN_CLASS_NAMES[2].to_string(),
171 Self::Organization => BUILTIN_CLASS_NAMES[3].to_string(),
172 Self::Custom(name) => format!("Custom:{name}"),
173 }
174 }
175
176 pub fn to_canonical_str(&self) -> String {
178 match self {
179 Self::Email => "email".to_string(),
180 Self::Name => "name".to_string(),
181 Self::Location => "location".to_string(),
182 Self::Organization => "organization".to_string(),
183 Self::Custom(name) => format!("custom:{name}"),
184 }
185 }
186
187 pub fn from_canonical_str(value: &str) -> Option<Self> {
189 match value {
190 "email" | "Email" => Some(Self::Email),
191 "name" | "Name" => Some(Self::Name),
192 "location" | "Location" => Some(Self::Location),
193 "organization" | "Organization" => Some(Self::Organization),
194 custom if custom.starts_with("custom:") => {
195 let name = &custom["custom:".len()..];
196 (!name.is_empty()).then(|| Self::Custom(name.to_string()))
197 }
198 _ => None,
199 }
200 }
201}
202
203#[derive(Debug, Clone, PartialEq, Eq)]
209#[non_exhaustive]
210pub struct PiiClassAudit(pub PiiClass);
211
212impl PiiClassAudit {
213 pub fn new(class: PiiClass) -> Self {
215 Self(class)
216 }
217
218 pub fn into_inner(self) -> PiiClass {
220 self.0
221 }
222}
223
224impl Serialize for PiiClassAudit {
225 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
226 where
227 S: serde::Serializer,
228 {
229 serializer.serialize_str(&self.0.to_canonical_str())
230 }
231}
232
233impl<'de> Deserialize<'de> for PiiClassAudit {
234 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
235 where
236 D: serde::Deserializer<'de>,
237 {
238 let value = String::deserialize(deserializer)?;
239 PiiClass::from_canonical_str(&value)
240 .map(Self)
241 .ok_or_else(|| {
242 serde::de::Error::custom(format!("unknown PiiClass canonical form: {value}"))
243 })
244 }
245}
246
247mod pii_class_audit_serde {
248 use super::{PiiClass, PiiClassAudit};
249 use serde::{Deserialize, Deserializer, Serialize, Serializer};
250
251 pub fn serialize<S>(class: &PiiClass, serializer: S) -> Result<S::Ok, S::Error>
252 where
253 S: Serializer,
254 {
255 PiiClassAudit::new(class.clone()).serialize(serializer)
256 }
257
258 pub fn deserialize<'de, D>(deserializer: D) -> Result<PiiClass, D::Error>
259 where
260 D: Deserializer<'de>,
261 {
262 Ok(PiiClassAudit::deserialize(deserializer)?.into_inner())
263 }
264}
265
266#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
268#[non_exhaustive]
269pub struct LosingCandidate {
270 #[serde(with = "pii_class_audit_serde")]
272 pub class: PiiClass,
273 pub recognizer_id: String,
275}
276
277impl LosingCandidate {
278 pub fn new(class: PiiClass, recognizer_id: impl Into<String>) -> Self {
280 Self {
281 class,
282 recognizer_id: recognizer_id.into(),
283 }
284 }
285}
286
287#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
289#[non_exhaustive]
290pub struct AmbiguityRecord {
291 #[serde(with = "pii_class_audit_serde")]
293 pub ambiguity_class: PiiClass,
294 pub losing_candidates: Vec<LosingCandidate>,
298 pub reason: AmbiguityReason,
300}
301
302impl AmbiguityRecord {
303 pub fn new(
305 ambiguity_class: PiiClass,
306 losing_candidates: Vec<LosingCandidate>,
307 reason: AmbiguityReason,
308 ) -> Self {
309 Self {
310 ambiguity_class,
311 losing_candidates,
312 reason,
313 }
314 }
315}
316
317#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
319#[non_exhaustive]
320#[serde(rename_all = "snake_case")]
321pub enum AmbiguityReason {
322 NoAnchor,
324 ValidatorIndeterminate,
326 MultiFamilyMatch,
328 PrecedenceTie,
330}
331
332#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
334#[non_exhaustive]
335#[serde(rename_all = "snake_case")]
336pub enum ValidatorFailReason {
337 LuhnFailed,
339 IbanMod97Failed,
341 #[serde(alias = "email_rfc_failed")]
343 EmailRfcRejected,
344 #[serde(alias = "e164_phone_failed")]
346 PhoneE164Rejected,
347 PhoneNationalRegionMismatch,
349 Ipv4ParseFailed,
351 Ipv6ParseFailed,
353 EthEip55ChecksumFailed,
355 AadhaarVerhoeffFailed,
357 FrNirMod97Failed,
359 DeSteuerIdMod1110Failed,
361 BsnMod11Failed,
363 CpfMod11Failed,
365 CnpjMod11Failed,
367 UkNhsMod11Failed,
369}
370
371#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
373#[non_exhaustive]
374#[serde(rename_all = "snake_case")]
375pub enum ValidatorOutcome {
376 Pass { canonical_form: Option<String> },
378 Fail { reason: ValidatorFailReason },
380 NotApplicable,
382}
383
384#[derive(Debug, Clone, PartialEq, Eq, Error)]
386#[non_exhaustive]
387pub enum ValidatorKindParseError {
388 #[error("unsupported validator: {kind}")]
390 UnsupportedValidator {
391 kind: String,
393 },
394}
395
396#[derive(Debug, Clone, Copy, PartialEq, Eq)]
398#[non_exhaustive]
399pub enum ValidatorKind {
400 EmailRfc,
402 #[cfg(feature = "phone-parser")]
404 E164Phone,
405 #[cfg(feature = "phone-parser")]
407 E164PhoneNational(Region),
408 Luhn,
410 IbanMod97,
412 Ipv4Parse,
414 Ipv6Parse,
416 EthEip55,
418 AadhaarVerhoeff,
420 FrNirMod97,
422 DeSteuerIdMod1110,
424 BsnMod11,
426 CpfMod11,
428 CnpjMod11,
430 UkNhsMod11,
432}
433
434#[cfg(feature = "phone-parser")]
436#[derive(Debug, Clone, Copy, PartialEq, Eq)]
437#[non_exhaustive]
438pub enum Region {
439 De,
441 Us,
443}
444
445impl ValidatorKind {
446 pub fn parse(s: &str) -> Result<Self, ValidatorKindParseError> {
448 match s {
449 "email_rfc" => Ok(Self::EmailRfc),
450 #[cfg(feature = "phone-parser")]
451 "e164_phone" => Ok(Self::E164Phone),
452 #[cfg(feature = "phone-parser")]
453 "e164_phone_national_de" => Ok(Self::E164PhoneNational(Region::De)),
454 #[cfg(feature = "phone-parser")]
455 "e164_phone_national_us" => Ok(Self::E164PhoneNational(Region::Us)),
456 "luhn" => Ok(Self::Luhn),
457 "iban_mod97" => Ok(Self::IbanMod97),
458 "ipv4_parse" => Ok(Self::Ipv4Parse),
459 "ipv6_parse" => Ok(Self::Ipv6Parse),
460 "eth_eip55" => Ok(Self::EthEip55),
461 "aadhaar_verhoeff" => Ok(Self::AadhaarVerhoeff),
462 "fr_nir_mod97" => Ok(Self::FrNirMod97),
463 "de_steuer_id_mod1110" => Ok(Self::DeSteuerIdMod1110),
464 "bsn_mod11" => Ok(Self::BsnMod11),
465 "cpf_mod11" => Ok(Self::CpfMod11),
466 "cnpj_mod11" => Ok(Self::CnpjMod11),
467 "uk_nhs_mod11" => Ok(Self::UkNhsMod11),
468 other => Err(ValidatorKindParseError::UnsupportedValidator {
469 kind: other.to_string(),
470 }),
471 }
472 }
473
474 pub fn validates(self, input: &str) -> bool {
476 match self {
477 Self::AadhaarVerhoeff => aadhaar_verhoeff_check(input),
478 Self::FrNirMod97 => fr_nir_mod97_check(input),
479 Self::DeSteuerIdMod1110 => de_steuer_id_mod1110_check(input),
480 Self::BsnMod11 => bsn_mod11_check(input),
481 Self::CpfMod11 => cpf_mod11_check(input),
482 Self::CnpjMod11 => cnpj_mod11_check(input),
483 Self::UkNhsMod11 => uk_nhs_mod11_check(input),
484 _ => self.canonical_form(input).is_some(),
485 }
486 }
487
488 pub fn validate(self, input: &str) -> ValidatorOutcome {
490 match self.canonical_form(input) {
491 Some(canonical_form) => ValidatorOutcome::Pass {
492 canonical_form: Some(canonical_form),
493 },
494 None => ValidatorOutcome::Fail {
495 reason: self.fail_reason(),
496 },
497 }
498 }
499
500 pub fn canonical_form(self, input: &str) -> Option<String> {
502 match self {
503 Self::EmailRfc => is_basic_email(input).then(|| input.to_string()),
504 #[cfg(feature = "phone-parser")]
505 Self::E164Phone => e164_phone_check(input).then(|| input.to_string()),
506 #[cfg(feature = "phone-parser")]
507 Self::E164PhoneNational(region) => validate_phone_national(region, input),
508 Self::Luhn => luhn_check(input).then(|| input.to_string()),
509 Self::IbanMod97 => iban_mod97_check(input).then(|| input.to_string()),
510 Self::Ipv4Parse => ipv4_parse_check(input).then(|| input.to_string()),
511 Self::Ipv6Parse => ipv6_parse_check(input).then(|| input.to_string()),
512 Self::EthEip55 => eth_eip55_check(input).then(|| input.to_string()),
513 Self::AadhaarVerhoeff => {
514 canonical_ascii_digits::<12>(input).filter(|_| aadhaar_verhoeff_check(input))
515 }
516 Self::FrNirMod97 => {
517 canonical_ascii_digits::<15>(input).filter(|_| fr_nir_mod97_check(input))
518 }
519 Self::DeSteuerIdMod1110 => {
520 canonical_ascii_digits::<11>(input).filter(|_| de_steuer_id_mod1110_check(input))
521 }
522 Self::BsnMod11 => canonical_ascii_digits::<9>(input).filter(|_| bsn_mod11_check(input)),
523 Self::CpfMod11 => {
524 canonical_ascii_digits::<11>(input).filter(|_| cpf_mod11_check(input))
525 }
526 Self::CnpjMod11 => {
527 canonical_ascii_digits::<14>(input).filter(|_| cnpj_mod11_check(input))
528 }
529 Self::UkNhsMod11 => {
530 canonical_ascii_digits::<10>(input).filter(|_| uk_nhs_mod11_check(input))
531 }
532 }
533 }
534
535 pub fn fail_reason(self) -> ValidatorFailReason {
537 match self {
538 Self::EmailRfc => ValidatorFailReason::EmailRfcRejected,
539 #[cfg(feature = "phone-parser")]
540 Self::E164Phone => ValidatorFailReason::PhoneE164Rejected,
541 #[cfg(feature = "phone-parser")]
542 Self::E164PhoneNational(_) => ValidatorFailReason::PhoneNationalRegionMismatch,
543 Self::Luhn => ValidatorFailReason::LuhnFailed,
544 Self::IbanMod97 => ValidatorFailReason::IbanMod97Failed,
545 Self::Ipv4Parse => ValidatorFailReason::Ipv4ParseFailed,
546 Self::Ipv6Parse => ValidatorFailReason::Ipv6ParseFailed,
547 Self::EthEip55 => ValidatorFailReason::EthEip55ChecksumFailed,
548 Self::AadhaarVerhoeff => ValidatorFailReason::AadhaarVerhoeffFailed,
549 Self::FrNirMod97 => ValidatorFailReason::FrNirMod97Failed,
550 Self::DeSteuerIdMod1110 => ValidatorFailReason::DeSteuerIdMod1110Failed,
551 Self::BsnMod11 => ValidatorFailReason::BsnMod11Failed,
552 Self::CpfMod11 => ValidatorFailReason::CpfMod11Failed,
553 Self::CnpjMod11 => ValidatorFailReason::CnpjMod11Failed,
554 Self::UkNhsMod11 => ValidatorFailReason::UkNhsMod11Failed,
555 }
556 }
557}
558
559fn is_basic_email(input: &str) -> bool {
560 let Some((local, domain)) = input.split_once('@') else {
561 return false;
562 };
563 !local.is_empty() && domain.contains('.') && !domain.starts_with('.') && !domain.ends_with('.')
564}
565
566#[cfg(feature = "phone-parser")]
567fn e164_phone_check(input: &str) -> bool {
568 phonenumber::parse(None, input).is_ok_and(|phone| phonenumber::is_valid(&phone))
569}
570
571#[cfg(feature = "phone-parser")]
572fn validate_phone_national(region: Region, input: &str) -> Option<String> {
573 let country = match region {
574 Region::De => phonenumber::country::DE,
575 Region::Us => phonenumber::country::US,
576 };
577 let expected_code = match region {
578 Region::De => 49,
579 Region::Us => 1,
580 };
581 let number = phonenumber::parse(Some(country), input).ok()?;
582 if number.country().code() != expected_code {
583 return None;
584 }
585 if number.is_valid() || is_safe_fixture_phone(region, input) {
586 return Some(number.format().mode(phonenumber::Mode::E164).to_string());
587 }
588 None
589}
590
591#[cfg(feature = "phone-parser")]
592fn is_safe_fixture_phone(region: Region, input: &str) -> bool {
593 let digits = input
594 .chars()
595 .filter(char::is_ascii_digit)
596 .collect::<String>();
597 match region {
598 Region::Us => {
599 digits == "15550100"
600 || matches!(digits.strip_prefix('1'), Some(rest) if rest.len() == 10 && rest[3..].starts_with("55501"))
601 }
602 Region::De => matches!(
603 digits.as_str(),
604 "493000000000"
605 | "4915100000000"
606 | "4915550112233"
607 | "015550112233"
608 | "491710000000"
609 | "01710000000"
610 ),
611 }
612}
613
614fn luhn_check(input: &str) -> bool {
615 let mut digits = Vec::new();
616 for byte in input.bytes() {
617 if byte.is_ascii_whitespace() || byte == b'-' {
618 continue;
619 }
620 if !byte.is_ascii_digit() {
621 return false;
622 }
623 digits.push(byte - b'0');
624 }
625 if !(13..=19).contains(&digits.len()) {
626 return false;
627 }
628
629 let sum: u32 = digits
630 .iter()
631 .rev()
632 .enumerate()
633 .map(|(index, digit)| {
634 let mut value = u32::from(*digit);
635 if index % 2 == 1 {
636 value *= 2;
637 if value > 9 {
638 value -= 9;
639 }
640 }
641 value
642 })
643 .sum();
644 sum.is_multiple_of(10)
645}
646
647fn iban_mod97_check(input: &str) -> bool {
648 let canonical = iban_canonicalize(input);
649 if !(15..=34).contains(&canonical.len()) {
650 return false;
651 }
652 if !canonical.chars().all(|ch| ch.is_ascii_alphanumeric()) {
653 return false;
654 }
655
656 let mut remainder = 0u32;
657 for ch in canonical[4..].chars().chain(canonical[..4].chars()) {
658 match ch {
659 '0'..='9' => {
660 remainder = (remainder * 10 + ch.to_digit(10).expect("digit")) % 97;
661 }
662 'A'..='Z' => {
663 let value = u32::from(ch) - u32::from('A') + 10;
664 remainder = (remainder * 10 + value / 10) % 97;
665 remainder = (remainder * 10 + value % 10) % 97;
666 }
667 _ => return false,
668 }
669 }
670 remainder == 1
671}
672
673fn iban_canonicalize(input: &str) -> String {
674 input
675 .chars()
676 .filter(|ch| !ch.is_ascii_whitespace())
677 .flat_map(char::to_uppercase)
678 .collect()
679}
680
681fn ipv4_parse_check(input: &str) -> bool {
682 input.parse::<std::net::Ipv4Addr>().is_ok()
683}
684
685fn ipv6_parse_check(input: &str) -> bool {
686 input.parse::<std::net::Ipv6Addr>().is_ok()
687}
688
689fn eth_eip55_check(input: &str) -> bool {
690 let Some(address) = input.strip_prefix("0x") else {
691 return false;
692 };
693 if address.len() != 40 || !address.bytes().all(|byte| byte.is_ascii_hexdigit()) {
694 return false;
695 }
696 if address
697 .bytes()
698 .all(|byte| !byte.is_ascii_alphabetic() || byte.is_ascii_lowercase())
699 || address
700 .bytes()
701 .all(|byte| !byte.is_ascii_alphabetic() || byte.is_ascii_uppercase())
702 {
703 return true;
704 }
705
706 let lowercase = address.to_ascii_lowercase();
707 let hash = Keccak256::digest(lowercase.as_bytes());
708 for (index, byte) in address.bytes().enumerate() {
709 if byte.is_ascii_digit() {
710 continue;
711 }
712 let hash_nibble = if index % 2 == 0 {
713 hash[index / 2] >> 4
714 } else {
715 hash[index / 2] & 0x0f
716 };
717 if (hash_nibble > 7) != byte.is_ascii_uppercase() {
718 return false;
719 }
720 }
721 true
722}
723
724fn collect_ascii_digits<const N: usize>(input: &str) -> Option<[u8; N]> {
725 let mut digits = [0u8; N];
726 let mut count = 0usize;
727 for byte in input.bytes() {
728 if byte.is_ascii_digit() {
729 if count == N {
730 return None;
731 }
732 digits[count] = byte - b'0';
733 count += 1;
734 } else if matches!(byte, b' ' | b'\t' | b'\n' | b'\r' | b'-' | b'.' | b'/') {
735 continue;
736 } else {
737 return None;
738 }
739 }
740 (count == N).then_some(digits)
741}
742
743fn canonical_ascii_digits<const N: usize>(input: &str) -> Option<String> {
744 let digits = collect_ascii_digits::<N>(input)?;
745 let mut canonical = String::with_capacity(N);
746 for digit in digits {
747 canonical.push(char::from(b'0' + digit));
748 }
749 Some(canonical)
750}
751
752fn not_all_same<const N: usize>(digits: &[u8; N]) -> bool {
753 digits[1..].iter().any(|digit| *digit != digits[0])
754}
755
756fn aadhaar_verhoeff_check(input: &str) -> bool {
757 const D: [[u8; 10]; 10] = [
758 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
759 [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],
760 [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],
761 [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],
762 [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],
763 [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],
764 [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],
765 [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],
766 [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],
767 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
768 ];
769 const P: [[u8; 10]; 8] = [
770 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
771 [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],
772 [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],
773 [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],
774 [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],
775 [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],
776 [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],
777 [7, 0, 4, 6, 9, 1, 3, 2, 5, 8],
778 ];
779 let Some(digits) = collect_ascii_digits::<12>(input) else {
780 return false;
781 };
782 if digits[0] < 2 || !not_all_same(&digits) {
783 return false;
784 }
785 let mut checksum = 0u8;
786 for (index, digit) in digits.iter().rev().enumerate() {
787 checksum = D[checksum as usize][P[index % 8][*digit as usize] as usize];
788 }
789 checksum == 0
790}
791
792fn fr_nir_mod97_check(input: &str) -> bool {
793 let Some(digits) = collect_ascii_digits::<15>(input) else {
794 return false;
795 };
796 if !matches!(digits[0], 1 | 2 | 3 | 4 | 7 | 8) {
797 return false;
798 }
799 let month = digits[3] * 10 + digits[4];
800 if !(1..=12).contains(&month) && !(20..=42).contains(&month) && !(50..=99).contains(&month) {
801 return false;
802 }
803 let mut number = 0u32;
804 for digit in &digits[..13] {
805 number = (number * 10 + u32::from(*digit)) % 97;
806 }
807 let key = u32::from(digits[13]) * 10 + u32::from(digits[14]);
808 97 - number == key
809}
810
811fn de_steuer_id_mod1110_check(input: &str) -> bool {
812 let Some(digits) = collect_ascii_digits::<11>(input) else {
813 return false;
814 };
815 if !steuer_id_first_ten_digits_valid(&digits) {
816 return false;
817 }
818 let mut product = 10u8;
819 for digit in &digits[..10] {
820 let mut sum = (*digit + product) % 10;
821 if sum == 0 {
822 sum = 10;
823 }
824 product = (2 * sum) % 11;
825 }
826 let check = (11 - product) % 10;
827 check == digits[10]
828}
829
830fn steuer_id_first_ten_digits_valid(digits: &[u8; 11]) -> bool {
831 if digits[0] == 0 {
832 return false;
833 }
834 let mut counts = [0u8; 10];
835 for digit in &digits[..10] {
836 counts[*digit as usize] += 1;
837 }
838 let repeated_digits = counts.iter().filter(|count| **count > 1).count();
839 let missing_digits = counts.iter().filter(|count| **count == 0).count();
840 let repeated_count_valid = counts.iter().any(|count| matches!(*count, 2 | 3));
841 repeated_digits == 1 && repeated_count_valid && matches!(missing_digits, 1 | 2)
842}
843
844fn bsn_mod11_check(input: &str) -> bool {
845 let Some(digits) = collect_ascii_digits::<9>(input) else {
846 return false;
847 };
848 if !not_all_same(&digits) {
849 return false;
850 }
851 let sum: i32 = digits[..8]
852 .iter()
853 .enumerate()
854 .map(|(index, digit)| i32::from(*digit) * (9 - index as i32))
855 .sum::<i32>()
856 - i32::from(digits[8]);
857 sum.rem_euclid(11) == 0
858}
859
860fn cpf_mod11_check(input: &str) -> bool {
861 let Some(digits) = collect_ascii_digits::<11>(input) else {
862 return false;
863 };
864 if !not_all_same(&digits) {
865 return false;
866 }
867 mod11_check_digit(&digits[..9], 10) == digits[9]
868 && mod11_check_digit(&digits[..10], 11) == digits[10]
869}
870
871fn cnpj_mod11_check(input: &str) -> bool {
872 let Some(digits) = collect_ascii_digits::<14>(input) else {
873 return false;
874 };
875 if !not_all_same(&digits) {
876 return false;
877 }
878 const FIRST: [u8; 12] = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
879 const SECOND: [u8; 13] = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
880 weighted_mod11_check_digit(&digits[..12], &FIRST) == digits[12]
881 && weighted_mod11_check_digit(&digits[..13], &SECOND) == digits[13]
882}
883
884fn uk_nhs_mod11_check(input: &str) -> bool {
885 let Some(digits) = collect_ascii_digits::<10>(input) else {
886 return false;
887 };
888 if !not_all_same(&digits) {
889 return false;
890 }
891 let sum: u32 = digits[..9]
892 .iter()
893 .enumerate()
894 .map(|(index, digit)| u32::from(*digit) * (10 - index as u32))
895 .sum();
896 let check = 11 - (sum % 11);
897 let check = if check == 11 { 0 } else { check };
898 check != 10 && check == u32::from(digits[9])
899}
900
901fn mod11_check_digit(digits: &[u8], start_weight: u8) -> u8 {
902 let weights = (2..=start_weight).rev();
903 let sum: u32 = digits
904 .iter()
905 .zip(weights)
906 .map(|(digit, weight)| u32::from(*digit) * u32::from(weight))
907 .sum();
908 let remainder = sum % 11;
909 if remainder < 2 {
910 0
911 } else {
912 (11 - remainder) as u8
913 }
914}
915
916fn weighted_mod11_check_digit(digits: &[u8], weights: &[u8]) -> u8 {
917 let sum: u32 = digits
918 .iter()
919 .zip(weights)
920 .map(|(digit, weight)| u32::from(*digit) * u32::from(*weight))
921 .sum();
922 let remainder = sum % 11;
923 if remainder < 2 {
924 0
925 } else {
926 (11 - remainder) as u8
927 }
928}
929
930#[derive(Debug, Clone, PartialEq, Eq)]
932#[non_exhaustive]
933pub struct Detection {
934 pub span: Range<usize>,
936 pub class: PiiClass,
938 pub source: String,
940}
941
942impl Detection {
943 pub fn new(span: Range<usize>, class: PiiClass, source: impl Into<String>) -> Self {
945 Self {
946 span,
947 class,
948 source: source.into(),
949 }
950 }
951}
952
953pub trait SafetyNet: Send + Sync {
967 fn id(&self) -> &str;
969
970 fn supported_locales(&self) -> &[LocaleTag];
972
973 fn check(
975 &self,
976 clean_text: &str,
977 context: SafetyNetContext<'_>,
978 ) -> Result<Vec<LeakSuspect>, SafetyNetError>;
979}
980
981#[derive(Debug, Clone, Copy)]
983#[non_exhaustive]
984pub struct SafetyNetContext<'a> {
985 pub manifest: &'a Manifest,
987 pub locale_chain: &'a [LocaleTag],
991 pub document_kind: DocumentKind,
993 pub session_id: Option<&'a str>,
995 pub field_path: Option<&'a str>,
997}
998
999impl<'a> SafetyNetContext<'a> {
1000 pub fn new(
1002 manifest: &'a Manifest,
1003 locale_chain: &'a [LocaleTag],
1004 document_kind: DocumentKind,
1005 session_id: Option<&'a str>,
1006 field_path: Option<&'a str>,
1007 ) -> Self {
1008 Self {
1009 manifest,
1010 locale_chain,
1011 document_kind,
1012 session_id,
1013 field_path,
1014 }
1015 }
1016}
1017
1018#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1020#[non_exhaustive]
1021pub struct EmittedTokenSpan {
1022 pub clean_span: Range<usize>,
1024 pub raw_span: Range<usize>,
1026 pub class: PiiClass,
1028}
1029
1030impl EmittedTokenSpan {
1031 pub fn new(clean_span: Range<usize>, raw_span: Range<usize>, class: PiiClass) -> Self {
1033 Self {
1034 clean_span,
1035 raw_span,
1036 class,
1037 }
1038 }
1039}
1040
1041#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1043#[non_exhaustive]
1044pub struct Manifest {
1045 pub spans: Vec<EmittedTokenSpan>,
1047}
1048
1049impl Manifest {
1050 pub fn from_spans(mut spans: Vec<EmittedTokenSpan>) -> Self {
1052 spans.sort_by_key(|span| (span.clean_span.start, span.clean_span.end));
1053 Self { spans }
1054 }
1055
1056 pub fn diff_against(
1064 &self,
1065 suspect_span: &Range<usize>,
1066 suspect_class: &PiiClass,
1067 ) -> Option<LeakKind> {
1068 if suspect_span.is_empty() {
1069 return None;
1070 }
1071
1072 let start_idx = self
1073 .spans
1074 .partition_point(|span| span.clean_span.end <= suspect_span.start);
1075 let overlapping = self.spans[start_idx..]
1076 .iter()
1077 .take_while(|span| span.clean_span.start < suspect_span.end)
1078 .filter(|span| ranges_overlap(&span.clean_span, suspect_span))
1079 .collect::<Vec<_>>();
1080
1081 if overlapping.is_empty() {
1082 return Some(LeakKind::Uncovered);
1083 }
1084
1085 let mut cursor = suspect_span.start;
1086 let mut first_mismatch = None::<&EmittedTokenSpan>;
1087 for span in overlapping {
1088 if span.clean_span.start > cursor {
1089 return Some(LeakKind::PartialBleed {
1090 uncovered: cursor..span.clean_span.start.min(suspect_span.end),
1091 });
1092 }
1093
1094 if span.clean_span.end > cursor {
1095 if first_mismatch.is_none() && &span.class != suspect_class {
1096 first_mismatch = Some(span);
1097 }
1098 cursor = cursor.max(span.clean_span.end.min(suspect_span.end));
1099 if cursor >= suspect_span.end {
1100 break;
1101 }
1102 }
1103 }
1104
1105 if cursor < suspect_span.end {
1106 return Some(LeakKind::PartialBleed {
1107 uncovered: cursor..suspect_span.end,
1108 });
1109 }
1110
1111 first_mismatch.map(|span| LeakKind::ClassMismatch {
1112 pipeline_class: span.class.clone(),
1113 safety_net_class: suspect_class.clone(),
1114 })
1115 }
1116}
1117
1118fn ranges_overlap(left: &Range<usize>, right: &Range<usize>) -> bool {
1119 left.start < right.end && right.start < left.end
1120}
1121
1122#[derive(Debug, Clone, PartialEq)]
1124#[non_exhaustive]
1125pub struct LeakSuspect {
1126 pub span: Range<usize>,
1128 pub class: PiiClass,
1130 pub safety_net_id: String,
1132 pub score: Option<f32>,
1134 pub kind: LeakKind,
1136 pub raw_label: String,
1138 pub field_path: Option<String>,
1140}
1141
1142impl LeakSuspect {
1143 pub fn new(
1145 span: Range<usize>,
1146 class: PiiClass,
1147 safety_net_id: impl Into<String>,
1148 score: Option<f32>,
1149 kind: LeakKind,
1150 raw_label: impl Into<String>,
1151 field_path: Option<String>,
1152 ) -> Self {
1153 Self {
1154 span,
1155 class,
1156 safety_net_id: safety_net_id.into(),
1157 score,
1158 kind,
1159 raw_label: raw_label.into(),
1160 field_path,
1161 }
1162 }
1163}
1164
1165#[derive(Debug, Clone, PartialEq, Eq)]
1169#[non_exhaustive]
1170pub enum LeakKind {
1171 Uncovered,
1173 PartialBleed {
1175 uncovered: Range<usize>,
1177 },
1178 ClassMismatch {
1180 pipeline_class: PiiClass,
1182 safety_net_class: PiiClass,
1184 },
1185}
1186
1187#[derive(Debug, Clone, PartialEq, Eq)]
1189#[non_exhaustive]
1190pub enum LeakReportTelemetry {
1191 LocaleSkipped {
1193 safety_net_id: String,
1195 document_kind: DocumentKind,
1197 field_path: Option<String>,
1199 },
1200}
1201
1202#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1204#[non_exhaustive]
1205pub struct LeakReportStats {
1206 pub suspect_count: usize,
1208 pub uncovered_count: usize,
1210 pub partial_bleed_count: usize,
1212 pub class_mismatch_count: usize,
1214 pub locale_skipped_count: usize,
1216}
1217
1218#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1225#[non_exhaustive]
1226pub struct DocumentExtension {
1227 pub schema_version: u16,
1229 pub clean_md_sha256: [u8; 32],
1231 pub layout_json_sha256: [u8; 32],
1233 pub report_json_sha256: [u8; 32],
1235 #[serde(default, skip_serializing_if = "Option::is_none")]
1237 pub preview_png_sha256: Option<[u8; 32]>,
1238 pub page_count: u32,
1240 pub audit_session_id: String,
1242 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1244 pub clean_spans: Vec<EmittedTokenSpan>,
1245 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1247 pub codec_audit: Vec<CodecAuditRow>,
1248}
1249
1250impl DocumentExtension {
1251 pub fn builder(schema_version: u16) -> DocumentExtensionBuilder {
1253 DocumentExtensionBuilder {
1254 schema_version,
1255 clean_md_sha256: None,
1256 layout_json_sha256: None,
1257 report_json_sha256: None,
1258 preview_png_sha256: None,
1259 page_count: None,
1260 audit_session_id: None,
1261 clean_spans: Vec::new(),
1262 codec_audit: Vec::new(),
1263 }
1264 }
1265}
1266
1267#[derive(Debug, Clone)]
1269#[must_use]
1270pub struct DocumentExtensionBuilder {
1271 schema_version: u16,
1272 clean_md_sha256: Option<[u8; 32]>,
1273 layout_json_sha256: Option<[u8; 32]>,
1274 report_json_sha256: Option<[u8; 32]>,
1275 preview_png_sha256: Option<[u8; 32]>,
1276 page_count: Option<u32>,
1277 audit_session_id: Option<String>,
1278 clean_spans: Vec<EmittedTokenSpan>,
1279 codec_audit: Vec<CodecAuditRow>,
1280}
1281
1282impl DocumentExtensionBuilder {
1283 pub fn clean_md_sha256(mut self, hash: [u8; 32]) -> Self {
1284 self.clean_md_sha256 = Some(hash);
1285 self
1286 }
1287
1288 pub fn layout_json_sha256(mut self, hash: [u8; 32]) -> Self {
1289 self.layout_json_sha256 = Some(hash);
1290 self
1291 }
1292
1293 pub fn report_json_sha256(mut self, hash: [u8; 32]) -> Self {
1294 self.report_json_sha256 = Some(hash);
1295 self
1296 }
1297
1298 pub fn preview_png_sha256(mut self, hash: [u8; 32]) -> Self {
1299 self.preview_png_sha256 = Some(hash);
1300 self
1301 }
1302
1303 pub fn page_count(mut self, page_count: u32) -> Self {
1304 self.page_count = Some(page_count);
1305 self
1306 }
1307
1308 pub fn audit_session_id(mut self, audit_session_id: impl Into<String>) -> Self {
1309 self.audit_session_id = Some(audit_session_id.into());
1310 self
1311 }
1312
1313 pub fn clean_spans(mut self, clean_spans: Vec<EmittedTokenSpan>) -> Self {
1314 self.clean_spans = clean_spans;
1315 self
1316 }
1317
1318 pub fn codec_audit(mut self, codec_audit: Vec<CodecAuditRow>) -> Self {
1319 self.codec_audit = codec_audit;
1320 self
1321 }
1322
1323 pub fn build(self) -> Result<DocumentExtension, DocumentExtensionError> {
1324 Ok(DocumentExtension {
1325 schema_version: self.schema_version,
1326 clean_md_sha256: self
1327 .clean_md_sha256
1328 .ok_or(DocumentExtensionError::MissingField("clean_md_sha256"))?,
1329 layout_json_sha256: self
1330 .layout_json_sha256
1331 .ok_or(DocumentExtensionError::MissingField("layout_json_sha256"))?,
1332 report_json_sha256: self
1333 .report_json_sha256
1334 .ok_or(DocumentExtensionError::MissingField("report_json_sha256"))?,
1335 preview_png_sha256: self.preview_png_sha256,
1336 page_count: self
1337 .page_count
1338 .ok_or(DocumentExtensionError::MissingField("page_count"))?,
1339 audit_session_id: self
1340 .audit_session_id
1341 .ok_or(DocumentExtensionError::MissingField("audit_session_id"))?,
1342 clean_spans: self.clean_spans,
1343 codec_audit: self.codec_audit,
1344 })
1345 }
1346}
1347
1348#[derive(Debug, Clone, PartialEq, Eq, Error)]
1350#[non_exhaustive]
1351pub enum DocumentExtensionError {
1352 #[error("missing document extension field: {0}")]
1353 MissingField(&'static str),
1354}
1355
1356#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1358#[serde(rename_all = "snake_case")]
1359#[non_exhaustive]
1360pub enum TextOrigin {
1361 Ocr,
1363 EmbeddedText,
1365 Transcript,
1367 Hybrid,
1369}
1370
1371#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1373#[non_exhaustive]
1374pub struct CodecCapabilitySet {
1375 pub text: bool,
1377 pub layout: bool,
1379 pub confidence: bool,
1381 pub timestamps: bool,
1383}
1384
1385impl CodecCapabilitySet {
1386 pub const TEXT_ONLY: Self = Self {
1388 text: true,
1389 layout: false,
1390 confidence: false,
1391 timestamps: false,
1392 };
1393
1394 pub const fn new(text: bool, layout: bool, confidence: bool, timestamps: bool) -> Self {
1396 Self {
1397 text,
1398 layout,
1399 confidence,
1400 timestamps,
1401 }
1402 }
1403
1404 pub fn contains(self, requested: Self) -> bool {
1406 (!requested.text || self.text)
1407 && (!requested.layout || self.layout)
1408 && (!requested.confidence || self.confidence)
1409 && (!requested.timestamps || self.timestamps)
1410 }
1411}
1412
1413#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1415#[serde(rename_all = "snake_case")]
1416#[non_exhaustive]
1417pub enum ExtractionDensityPolicy {
1418 Required(f32),
1420 Exempt { reason: String },
1422}
1423
1424impl Default for ExtractionDensityPolicy {
1425 fn default() -> Self {
1426 Self::Exempt {
1427 reason: "calibration_pending".to_string(),
1428 }
1429 }
1430}
1431
1432#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1434#[non_exhaustive]
1435pub struct CodecAuditRow {
1436 pub codec_id: String,
1438 pub codec_version: String,
1440 pub accepted_mime: String,
1442 pub advertised: CodecCapabilitySet,
1444 pub delivered: CodecCapabilitySet,
1446 pub text_origin: TextOrigin,
1448 pub codec_output_schema_version: u16,
1450 #[serde(default, skip_serializing_if = "Option::is_none")]
1452 pub options_hash_hex: Option<String>,
1453 #[serde(default, skip_serializing_if = "Option::is_none")]
1455 pub engine_provenance: Option<String>,
1456 pub extraction_density_policy: ExtractionDensityPolicy,
1458}
1459
1460impl CodecAuditRow {
1461 pub fn new(
1463 codec_id: impl Into<String>,
1464 codec_version: impl Into<String>,
1465 accepted_mime: impl Into<String>,
1466 text_origin: TextOrigin,
1467 ) -> Self {
1468 Self {
1469 codec_id: codec_id.into(),
1470 codec_version: codec_version.into(),
1471 accepted_mime: accepted_mime.into(),
1472 advertised: CodecCapabilitySet::default(),
1473 delivered: CodecCapabilitySet::default(),
1474 text_origin,
1475 codec_output_schema_version: 1,
1476 options_hash_hex: None,
1477 engine_provenance: None,
1478 extraction_density_policy: ExtractionDensityPolicy::default(),
1479 }
1480 }
1481}
1482
1483#[derive(Debug, Clone, Default, PartialEq)]
1489#[non_exhaustive]
1490pub struct LeakReport {
1491 pub suspects: Vec<LeakSuspect>,
1493 pub telemetry: Vec<LeakReportTelemetry>,
1495 pub stats: LeakReportStats,
1497 pub replay_hash: Option<String>,
1502}
1503
1504impl LeakReport {
1505 pub fn from_parts(
1507 suspects: Vec<LeakSuspect>,
1508 telemetry: Vec<LeakReportTelemetry>,
1509 ) -> LeakReport {
1510 let mut stats = LeakReportStats {
1511 suspect_count: suspects.len(),
1512 locale_skipped_count: telemetry
1513 .iter()
1514 .filter(|event| matches!(event, LeakReportTelemetry::LocaleSkipped { .. }))
1515 .count(),
1516 ..LeakReportStats::default()
1517 };
1518 for suspect in &suspects {
1519 match suspect.kind {
1520 LeakKind::Uncovered => stats.uncovered_count += 1,
1521 LeakKind::PartialBleed { .. } => stats.partial_bleed_count += 1,
1522 LeakKind::ClassMismatch { .. } => stats.class_mismatch_count += 1,
1523 }
1524 }
1525 LeakReport {
1526 suspects,
1527 telemetry,
1528 stats,
1529 replay_hash: None,
1530 }
1531 }
1532
1533 pub fn extend(&mut self, other: LeakReport) {
1535 self.suspects.extend(other.suspects);
1536 self.telemetry.extend(other.telemetry);
1537 *self = LeakReport::from_parts(
1538 std::mem::take(&mut self.suspects),
1539 std::mem::take(&mut self.telemetry),
1540 );
1541 }
1542}
1543
1544#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1546#[non_exhaustive]
1547pub enum OpenAiPrivateLabel {
1548 PrivatePerson,
1550 PrivateAddress,
1552 PrivateEmail,
1554 PrivatePhone,
1556 PrivateUrl,
1558 PrivateDate,
1560 AccountNumber,
1562 Secret,
1564}
1565
1566impl OpenAiPrivateLabel {
1567 pub fn as_str(self) -> &'static str {
1569 match self {
1570 Self::PrivatePerson => "private_person",
1571 Self::PrivateAddress => "private_address",
1572 Self::PrivateEmail => "private_email",
1573 Self::PrivatePhone => "private_phone",
1574 Self::PrivateUrl => "private_url",
1575 Self::PrivateDate => "private_date",
1576 Self::AccountNumber => "account_number",
1577 Self::Secret => "secret",
1578 }
1579 }
1580}
1581
1582#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1584#[non_exhaustive]
1585pub enum SafetyNetPiiClass {
1586 Email,
1588 Name,
1590 Location,
1592 Phone,
1594 Url,
1596 Date,
1598 AccountNumber,
1600 Secret,
1602}
1603
1604impl SafetyNetPiiClass {
1605 pub fn to_pii_class(self) -> PiiClass {
1607 match self {
1608 Self::Email => PiiClass::Email,
1609 Self::Name => PiiClass::Name,
1610 Self::Location => PiiClass::Location,
1611 Self::Phone => PiiClass::custom("phone"),
1612 Self::Url => PiiClass::custom("url"),
1613 Self::Date => PiiClass::custom("date"),
1614 Self::AccountNumber => PiiClass::custom("account_number"),
1615 Self::Secret => PiiClass::custom("secret"),
1616 }
1617 }
1618}
1619
1620#[derive(Debug, Clone, PartialEq, Eq, Error)]
1622#[non_exhaustive]
1623pub enum SafetyNetError {
1624 #[error("safety net unavailable: {reason}")]
1626 Unavailable {
1627 reason: String,
1629 },
1630 #[error("safety net weights missing: {path}")]
1632 WeightsMissing {
1633 path: String,
1635 },
1636 #[error("safety net model unavailable: {reason}")]
1638 ModelUnavailable {
1639 reason: String,
1641 },
1642 #[error("safety net model integrity mismatch: expected={expected}, actual={actual}")]
1644 ModelIntegrityMismatch {
1645 expected: String,
1647 actual: String,
1649 },
1650 #[error("safety net input too large: limit={limit}, actual={actual}")]
1652 InputTooLarge {
1653 limit: usize,
1655 actual: usize,
1657 },
1658 #[error("safety net runtime failed: {message}")]
1660 Runtime {
1661 message: String,
1663 },
1664 #[error("safety net invalid output: {message}")]
1666 InvalidOutput {
1667 message: String,
1669 },
1670}
1671
1672#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1686#[non_exhaustive]
1687pub enum Action {
1688 Tokenize,
1690 Redact,
1692 FormatPreserve,
1694 Generalize,
1696 Preserve,
1698}
1699
1700#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1702#[non_exhaustive]
1703pub enum ConflictTier {
1704 None,
1706 ClassPriority,
1708 RulePriority,
1710 Score,
1712 SpanLength,
1714 Validator,
1716 ValidatorVeto,
1718 CollisionPolicy,
1720 AnchoredContext,
1722 RecognizerId,
1724 Merged,
1726 Redact,
1728 Resolve,
1730 Fallback,
1732}
1733
1734#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1736#[non_exhaustive]
1737pub enum FallbackReason {
1738 OverlapConflict,
1740 ValidatorVeto,
1742 AnchorMissing,
1744 ResidualSuspect,
1746}
1747
1748#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1750#[non_exhaustive]
1751pub enum DocumentKind {
1752 Structured,
1754 Text,
1756}
1757
1758#[derive(Debug, Clone, PartialEq, Eq)]
1768#[non_exhaustive]
1769pub struct RedactionEntry {
1770 pub source: String,
1772 pub recognizer_id: Option<String>,
1774 pub recognizer_version_id: Option<String>,
1776 pub class: PiiClass,
1778 pub action: Action,
1780 pub field_name: Option<String>,
1782 pub document_kind: DocumentKind,
1784 pub conflict_loser: bool,
1786 pub decided_by: ConflictTier,
1788 pub created_at: i64,
1790 pub session_id: Option<String>,
1792 pub validator_fail_reason: Option<ValidatorFailReason>,
1794 pub ambiguity_record: Option<AmbiguityRecord>,
1796 pub collision_family: Option<String>,
1798 pub collision_variant: Option<String>,
1800 pub fallback_triggered: Option<FallbackReason>,
1802}
1803
1804impl Serialize for RedactionEntry {
1805 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1806 where
1807 S: serde::Serializer,
1808 {
1809 use serde::ser::SerializeStruct;
1810
1811 let mut len = 14;
1812 if self.recognizer_id.is_some() {
1813 len += 1;
1814 }
1815 if self.recognizer_version_id.is_some() {
1816 len += 1;
1817 }
1818 let mut state = serializer.serialize_struct("RedactionEntry", len)?;
1819 state.serialize_field("source", &self.source)?;
1820 if let Some(recognizer_id) = &self.recognizer_id {
1821 state.serialize_field("recognizer_id", recognizer_id)?;
1822 }
1823 if let Some(recognizer_version_id) = &self.recognizer_version_id {
1824 state.serialize_field("recognizer_version_id", recognizer_version_id)?;
1825 }
1826 state.serialize_field("class", &self.class.to_canonical_str())?;
1827 state.serialize_field("action", redaction_action_as_str(self.action))?;
1828 state.serialize_field("field_name", &self.field_name)?;
1829 state.serialize_field(
1830 "document_kind",
1831 redaction_document_kind_as_str(self.document_kind),
1832 )?;
1833 state.serialize_field("conflict_loser", &self.conflict_loser)?;
1834 state.serialize_field(
1835 "decided_by",
1836 redaction_conflict_tier_as_str(self.decided_by),
1837 )?;
1838 state.serialize_field("created_at", &self.created_at)?;
1839 state.serialize_field("session_id", &self.session_id)?;
1840 state.serialize_field("validator_fail_reason", &self.validator_fail_reason)?;
1841 state.serialize_field("ambiguity_record", &self.ambiguity_record)?;
1842 state.serialize_field("collision_family", &self.collision_family)?;
1843 state.serialize_field("collision_variant", &self.collision_variant)?;
1844 state.serialize_field("fallback_triggered", &self.fallback_triggered)?;
1845 state.end()
1846 }
1847}
1848
1849fn redaction_action_as_str(action: Action) -> &'static str {
1850 match action {
1851 Action::Tokenize => "tokenize",
1852 Action::Redact => "redact",
1853 Action::FormatPreserve => "format_preserve",
1854 Action::Generalize => "generalize",
1855 Action::Preserve => "preserve",
1856 }
1857}
1858
1859fn redaction_document_kind_as_str(kind: DocumentKind) -> &'static str {
1860 match kind {
1861 DocumentKind::Structured => "structured",
1862 DocumentKind::Text => "text",
1863 }
1864}
1865
1866fn redaction_conflict_tier_as_str(tier: ConflictTier) -> &'static str {
1867 match tier {
1868 ConflictTier::None => "none",
1869 ConflictTier::ClassPriority => "class_priority",
1870 ConflictTier::RulePriority => "rule_priority",
1871 ConflictTier::Score => "score",
1872 ConflictTier::SpanLength => "span_length",
1873 ConflictTier::Validator => "validator",
1874 ConflictTier::ValidatorVeto => "validator_veto",
1875 ConflictTier::CollisionPolicy => "collision_policy",
1876 ConflictTier::AnchoredContext => "anchored_context",
1877 ConflictTier::RecognizerId => "recognizer_id",
1878 ConflictTier::Merged => "merged",
1879 ConflictTier::Redact => "redact",
1880 ConflictTier::Resolve => "resolve",
1881 ConflictTier::Fallback => "fallback",
1882 }
1883}
1884
1885impl RedactionEntry {
1886 #[allow(clippy::too_many_arguments)]
1888 pub fn new(
1889 source: impl Into<String>,
1890 class: PiiClass,
1891 action: Action,
1892 field_name: Option<String>,
1893 document_kind: DocumentKind,
1894 conflict_loser: bool,
1895 decided_by: ConflictTier,
1896 created_at: i64,
1897 session_id: Option<String>,
1898 ) -> Self {
1899 Self {
1900 source: source.into(),
1901 class,
1902 action,
1903 field_name,
1904 document_kind,
1905 conflict_loser,
1906 decided_by,
1907 created_at,
1908 session_id,
1909 recognizer_id: None,
1910 recognizer_version_id: None,
1911 validator_fail_reason: None,
1912 ambiguity_record: None,
1913 collision_family: None,
1914 collision_variant: None,
1915 fallback_triggered: None,
1916 }
1917 }
1918
1919 pub fn with_validator_fail_reason(mut self, reason: ValidatorFailReason) -> Self {
1921 self.validator_fail_reason = Some(reason);
1922 self
1923 }
1924
1925 pub fn with_ambiguity_record(mut self, record: AmbiguityRecord) -> Self {
1927 self.ambiguity_record = Some(record);
1928 self
1929 }
1930
1931 pub fn with_collision_metadata(
1933 mut self,
1934 family: Option<String>,
1935 variant: Option<String>,
1936 ) -> Self {
1937 self.collision_family = family;
1938 self.collision_variant = variant;
1939 self
1940 }
1941
1942 pub fn with_fallback_triggered(mut self, reason: FallbackReason) -> Self {
1944 self.fallback_triggered = Some(reason);
1945 self
1946 }
1947
1948 pub fn with_recognizer_metadata(
1950 mut self,
1951 recognizer_id: Option<String>,
1952 recognizer_version_id: Option<String>,
1953 ) -> Self {
1954 self.recognizer_id = recognizer_id;
1955 self.recognizer_version_id = recognizer_version_id;
1956 self
1957 }
1958}
1959
1960#[derive(Debug, Clone, PartialEq, Eq, Error)]
1962#[non_exhaustive]
1963pub enum RedactionLogError {
1964 #[error("sqlite redaction log error: {0}")]
1966 Sqlite(String),
1967 #[error("backend redaction log error: {0}")]
1969 Backend(String),
1970}
1971
1972pub trait RedactionLogger: Send + Sync {
2002 fn log(&self, entry: &RedactionEntry) -> Result<(), RedactionLogError>;
2004}
2005
2006#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
2008#[non_exhaustive]
2009pub enum SafetyTier {
2010 #[default]
2012 SafeDefault,
2013 LocaleGated,
2015 OptIn,
2017}
2018
2019#[derive(Debug, Clone, PartialEq, Eq)]
2021#[non_exhaustive]
2022pub struct SafetyTierParseError {
2023 value: String,
2024}
2025
2026impl SafetyTier {
2027 pub fn parse(value: &str) -> Result<Self, SafetyTierParseError> {
2029 match value {
2030 "safe_default" => Ok(Self::SafeDefault),
2031 "locale_gated" => Ok(Self::LocaleGated),
2032 "opt_in" => Ok(Self::OptIn),
2033 other => Err(SafetyTierParseError {
2034 value: other.to_string(),
2035 }),
2036 }
2037 }
2038
2039 pub fn as_str(self) -> &'static str {
2041 match self {
2042 Self::SafeDefault => "safe_default",
2043 Self::LocaleGated => "locale_gated",
2044 Self::OptIn => "opt_in",
2045 }
2046 }
2047}
2048
2049impl SafetyTierParseError {
2050 pub fn value(&self) -> &str {
2052 &self.value
2053 }
2054}
2055
2056impl fmt::Display for SafetyTierParseError {
2057 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2058 write!(f, "unsupported safety_tier '{}'", self.value)
2059 }
2060}
2061
2062impl std::error::Error for SafetyTierParseError {}
2063
2064#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2066#[non_exhaustive]
2067pub enum LocaleTag {
2068 Global,
2070 DeDe,
2072 DeAt,
2074 DeCh,
2076 EnUs,
2078 EnGb,
2080 EnIe,
2082 EnAu,
2084 EnCa,
2086 Other(String),
2088}
2089
2090#[derive(Debug, Clone, PartialEq, Eq)]
2092#[non_exhaustive]
2093pub enum LocaleError {
2094 Unsupported,
2096}
2097
2098impl fmt::Display for LocaleError {
2099 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2100 match self {
2101 LocaleError::Unsupported => f.write_str("unsupported locale"),
2102 }
2103 }
2104}
2105
2106impl std::error::Error for LocaleError {}
2107
2108#[derive(Debug, Clone, PartialEq, Eq)]
2110pub struct LocaleChain(Vec<LocaleTag>);
2111
2112impl LocaleTag {
2113 pub const GLOBAL: LocaleTag = LocaleTag::Global;
2115
2116 pub fn parse(s: &str) -> Result<LocaleTag, LocaleError> {
2118 let raw = s.trim().replace('_', "-");
2119 let normalized = raw.to_ascii_lowercase();
2120 match normalized.as_str() {
2121 "global" | "*" => Ok(LocaleTag::Global),
2122 "de-de" => Ok(LocaleTag::DeDe),
2123 "de-at" => Ok(LocaleTag::DeAt),
2124 "de-ch" => Ok(LocaleTag::DeCh),
2125 "en-us" => Ok(LocaleTag::EnUs),
2126 "en-gb" => Ok(LocaleTag::EnGb),
2127 "en-ie" => Ok(LocaleTag::EnIe),
2128 "en-au" => Ok(LocaleTag::EnAu),
2129 "en-ca" => Ok(LocaleTag::EnCa),
2130 "" => Err(LocaleError::Unsupported),
2131 _ if is_bcp47_parseable(&raw) => Ok(LocaleTag::Other(canonical_other(&raw))),
2132 _ => Err(LocaleError::Unsupported),
2133 }
2134 }
2135
2136 pub fn as_str(&self) -> &str {
2138 match self {
2139 LocaleTag::Global => "global",
2140 LocaleTag::DeDe => "de-DE",
2141 LocaleTag::DeAt => "de-AT",
2142 LocaleTag::DeCh => "de-CH",
2143 LocaleTag::EnUs => "en-US",
2144 LocaleTag::EnGb => "en-GB",
2145 LocaleTag::EnIe => "en-IE",
2146 LocaleTag::EnAu => "en-AU",
2147 LocaleTag::EnCa => "en-CA",
2148 LocaleTag::Other(tag) => tag.as_str(),
2149 }
2150 }
2151}
2152
2153impl LocaleChain {
2154 pub fn from_tags(mut tags: Vec<LocaleTag>) -> LocaleChain {
2156 ensure_global(&mut tags);
2157 LocaleChain(tags)
2158 }
2159
2160 pub fn from_cli(raw: &str) -> Result<LocaleChain, LocaleError> {
2162 let tags = raw
2163 .split(',')
2164 .map(LocaleTag::parse)
2165 .collect::<Result<Vec<_>, _>>()?;
2166 Ok(LocaleChain::from_tags(tags))
2167 }
2168
2169 pub fn merge_policy_and_cli(
2171 policy: Option<&[LocaleTag]>,
2172 cli: Option<&[LocaleTag]>,
2173 ) -> LocaleChain {
2174 Self::merge_cli_policy_rulepack_default(cli, policy, None)
2175 }
2176
2177 pub fn merge_cli_policy_rulepack_default(
2179 cli: Option<&[LocaleTag]>,
2180 policy: Option<&[LocaleTag]>,
2181 rulepack_defaults: Option<&[LocaleTag]>,
2182 ) -> LocaleChain {
2183 let tags = cli
2184 .filter(|tags| !tags.is_empty())
2185 .or_else(|| policy.filter(|tags| !tags.is_empty()))
2186 .or_else(|| rulepack_defaults.filter(|tags| !tags.is_empty()))
2187 .map(|tags| tags.to_vec())
2188 .unwrap_or_else(|| vec![LocaleTag::Global]);
2189 LocaleChain::from_tags(tags)
2190 }
2191
2192 pub fn intersects(&self, recognizer_locales: &[LocaleTag]) -> bool {
2194 if recognizer_locales.is_empty() {
2195 return true;
2196 }
2197 recognizer_locales.iter().any(|recognizer_locale| {
2198 *recognizer_locale == LocaleTag::Global
2199 || self.0.iter().any(|active| active == recognizer_locale)
2200 })
2201 }
2202
2203 pub fn as_slice(&self) -> &[LocaleTag] {
2205 &self.0
2206 }
2207
2208 pub fn to_strings(&self) -> Vec<String> {
2210 self.0.iter().map(ToString::to_string).collect()
2211 }
2212}
2213
2214impl From<&[LocaleTag]> for LocaleChain {
2215 fn from(tags: &[LocaleTag]) -> Self {
2216 let mut owned = tags.to_vec();
2217 ensure_global(&mut owned);
2218 LocaleChain(owned)
2219 }
2220}
2221
2222impl fmt::Display for LocaleTag {
2223 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2224 f.write_str(self.as_str())
2225 }
2226}
2227
2228#[derive(Debug, Clone)]
2238#[non_exhaustive]
2239pub enum RawDocument {
2240 Structured(BTreeMap<String, Value>),
2242 Text(String),
2244}
2245
2246#[derive(Debug, Clone, Serialize)]
2265#[serde(untagged)]
2266#[non_exhaustive]
2267pub enum CleanDocument {
2268 Structured(BTreeMap<String, Value>),
2270 Text(String),
2272}
2273
2274#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2276#[serde(untagged)]
2277#[non_exhaustive]
2278pub enum Value {
2279 Null,
2281 Bool(bool),
2283 String(String),
2285 I64(i64),
2287 Array(Vec<Value>),
2289 Object(BTreeMap<String, Value>),
2291}
2292
2293impl Value {
2294 pub fn as_str(&self) -> Option<&str> {
2296 match self {
2297 Self::String(value) => Some(value.as_str()),
2298 Self::Null | Self::Bool(_) | Self::I64(_) | Self::Array(_) | Self::Object(_) => None,
2299 }
2300 }
2301
2302 pub fn scalar_to_safety_net_string(&self) -> Option<String> {
2304 match self {
2305 Self::String(value) if !value.is_empty() => Some(value.clone()),
2306 Self::String(_) | Self::Null | Self::Array(_) | Self::Object(_) => None,
2307 Self::Bool(value) => Some(value.to_string()),
2308 Self::I64(value) => Some(value.to_string()),
2309 }
2310 }
2311}
2312
2313impl PartialEq<&str> for Value {
2314 fn eq(&self, other: &&str) -> bool {
2315 self.as_str() == Some(*other)
2316 }
2317}
2318
2319#[derive(Debug, Clone, Default)]
2321pub struct DictionaryBundle {
2322 entries: HashMap<String, DictionaryEntry>,
2323}
2324
2325#[derive(Debug, Clone)]
2327pub struct DictionaryEntry {
2328 terms: Vec<String>,
2329 case_sensitive: bool,
2330 source: DictionarySource,
2331}
2332
2333#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2335#[non_exhaustive]
2336pub enum DictionarySource {
2337 Cli,
2339 Rulepack,
2341}
2342
2343#[derive(Debug, Clone, PartialEq, Eq)]
2345#[non_exhaustive]
2346pub struct DictionaryStats {
2347 pub name: String,
2349 pub term_count: usize,
2351 pub source: DictionarySource,
2353}
2354
2355impl DictionaryStats {
2356 pub fn new(name: impl Into<String>, term_count: usize, source: DictionarySource) -> Self {
2358 Self {
2359 name: name.into(),
2360 term_count,
2361 source,
2362 }
2363 }
2364}
2365
2366#[derive(Debug, Clone, PartialEq, Eq)]
2368#[non_exhaustive]
2369pub struct RulepackDict {
2370 pub name: String,
2372 pub terms: Vec<String>,
2374 pub case_sensitive: bool,
2376}
2377
2378impl RulepackDict {
2379 pub fn new(name: impl Into<String>, terms: Vec<String>, case_sensitive: bool) -> Self {
2381 Self {
2382 name: name.into(),
2383 terms,
2384 case_sensitive,
2385 }
2386 }
2387}
2388
2389#[derive(Debug, Clone, PartialEq, Eq)]
2391#[non_exhaustive]
2392pub enum DictionaryLoadError {
2393 Empty { name: String },
2395 UnicodeInsensitiveUnsupported { name: String },
2397}
2398
2399impl fmt::Display for DictionaryLoadError {
2400 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2401 match self {
2402 Self::Empty { name } => write!(f, "dictionary '{name}' has no terms"),
2403 Self::UnicodeInsensitiveUnsupported { name } => write!(
2404 f,
2405 "dictionary '{name}' uses unicode terms with case-insensitive matching, unsupported in v0.4.0; use case_sensitive = true"
2406 ),
2407 }
2408 }
2409}
2410
2411impl std::error::Error for DictionaryLoadError {}
2412
2413impl DictionaryBundle {
2414 pub fn from_rulepack_terms(terms: &[RulepackDict]) -> Self {
2416 let mut entries = HashMap::with_capacity(terms.len());
2417 for dictionary in terms {
2418 let entry = DictionaryEntry::new(
2419 &dictionary.name,
2420 dictionary.terms.clone(),
2421 dictionary.case_sensitive,
2422 DictionarySource::Rulepack,
2423 )
2424 .expect("Policy validates dictionary terms before bundle construction");
2425 entries.insert(dictionary.name.clone(), entry);
2426 }
2427 Self { entries }
2428 }
2429
2430 pub fn from_entries(entries: impl IntoIterator<Item = (String, DictionaryEntry)>) -> Self {
2432 Self {
2433 entries: entries.into_iter().collect(),
2434 }
2435 }
2436
2437 pub fn merge(a: Self, b: Self) -> Self {
2439 let mut entries = a.entries;
2440 entries.extend(b.entries);
2441 Self { entries }
2442 }
2443
2444 pub fn get(&self, name: &str) -> Option<&DictionaryEntry> {
2446 self.entries.get(name)
2447 }
2448
2449 pub fn stats(&self) -> Vec<DictionaryStats> {
2451 let mut stats = self
2452 .entries
2453 .iter()
2454 .map(|(name, entry)| DictionaryStats {
2455 name: name.clone(),
2456 term_count: entry.terms.len(),
2457 source: entry.source,
2458 })
2459 .collect::<Vec<_>>();
2460 stats.sort_by(|a, b| a.name.cmp(&b.name));
2461 stats
2462 }
2463}
2464
2465impl DictionaryEntry {
2466 pub fn new(
2468 name: &str,
2469 terms: Vec<String>,
2470 case_sensitive: bool,
2471 source: DictionarySource,
2472 ) -> Result<Self, DictionaryLoadError> {
2473 if terms.is_empty() {
2474 return Err(DictionaryLoadError::Empty {
2475 name: name.to_string(),
2476 });
2477 }
2478 if !case_sensitive && terms.iter().any(|term| !term.is_ascii()) {
2479 return Err(DictionaryLoadError::UnicodeInsensitiveUnsupported {
2480 name: name.to_string(),
2481 });
2482 }
2483 Ok(Self {
2484 terms,
2485 case_sensitive,
2486 source,
2487 })
2488 }
2489
2490 pub fn case_sensitive(&self) -> bool {
2492 self.case_sensitive
2493 }
2494
2495 pub fn terms(&self) -> &[String] {
2497 &self.terms
2498 }
2499}
2500
2501#[cfg(test)]
2502mod dictionary_tests {
2503 use super::*;
2504
2505 #[test]
2506 fn dictionary_entry_rejects_empty_terms() {
2507 let err = DictionaryEntry::new("empty", Vec::new(), true, DictionarySource::Cli)
2508 .expect_err("empty dictionaries must fail closed");
2509
2510 assert!(matches!(err, DictionaryLoadError::Empty { name } if name == "empty"));
2511 }
2512
2513 #[test]
2514 fn dictionary_entry_rejects_non_ascii_case_insensitive_terms() {
2515 let err = DictionaryEntry::new(
2516 "songs",
2517 vec!["Beyonce".to_string(), "Caf\u{00e9}".to_string()],
2518 false,
2519 DictionarySource::Cli,
2520 )
2521 .expect_err("unicode case-insensitive dictionaries must fail closed");
2522
2523 assert!(matches!(
2524 err,
2525 DictionaryLoadError::UnicodeInsensitiveUnsupported { name } if name == "songs"
2526 ));
2527 }
2528}
2529
2530#[cfg(test)]
2531mod redaction_logger_tests {
2532 use super::*;
2533
2534 struct CapturingLogger;
2535
2536 impl RedactionLogger for CapturingLogger {
2537 fn log(&self, _entry: &RedactionEntry) -> Result<(), RedactionLogError> {
2538 Ok(())
2539 }
2540 }
2541
2542 fn assert_send_sync<T: Send + Sync + ?Sized>() {}
2543
2544 #[test]
2545 fn redaction_log_error_display_is_stable() {
2546 assert_eq!(
2547 RedactionLogError::Sqlite("write failed".to_string()).to_string(),
2548 "sqlite redaction log error: write failed"
2549 );
2550 assert_eq!(
2551 RedactionLogError::Backend("sink failed".to_string()).to_string(),
2552 "backend redaction log error: sink failed"
2553 );
2554 }
2555
2556 #[test]
2557 fn redaction_logger_trait_object_is_send_sync() {
2558 assert_send_sync::<dyn RedactionLogger>();
2559 }
2560
2561 #[test]
2562 fn local_logger_can_implement_redaction_logger() {
2563 let logger = CapturingLogger;
2564 let entry = RedactionEntry {
2565 source: "unit-test".to_string(),
2566 recognizer_id: None,
2567 recognizer_version_id: None,
2568 class: PiiClass::Email,
2569 action: Action::Tokenize,
2570 field_name: None,
2571 document_kind: DocumentKind::Text,
2572 conflict_loser: false,
2573 decided_by: ConflictTier::None,
2574 created_at: 0,
2575 session_id: None,
2576 validator_fail_reason: None,
2577 ambiguity_record: None,
2578 collision_family: None,
2579 collision_variant: None,
2580 fallback_triggered: None,
2581 };
2582
2583 let trait_object: &dyn RedactionLogger = &logger;
2584 trait_object.log(&entry).expect("log entry");
2585 }
2586
2587 #[test]
2588 fn redaction_entry_json_shape_omits_absent_recognizer_lineage() {
2589 let entry = RedactionEntry::new(
2590 "email.global",
2591 PiiClass::Email,
2592 Action::Tokenize,
2593 None,
2594 DocumentKind::Text,
2595 false,
2596 ConflictTier::None,
2597 0,
2598 None,
2599 );
2600
2601 let rendered = serde_json::to_string(&entry).expect("serialize redaction entry");
2602
2603 assert_eq!(
2604 rendered,
2605 r#"{"source":"email.global","class":"email","action":"tokenize","field_name":null,"document_kind":"text","conflict_loser":false,"decided_by":"none","created_at":0,"session_id":null,"validator_fail_reason":null,"ambiguity_record":null,"collision_family":null,"collision_variant":null,"fallback_triggered":null}"#
2606 );
2607 }
2608
2609 #[test]
2610 fn redaction_entry_json_shape_includes_recognizer_lineage_when_present() {
2611 let entry = RedactionEntry::new(
2612 "ner/ort",
2613 PiiClass::Name,
2614 Action::Tokenize,
2615 None,
2616 DocumentKind::Text,
2617 false,
2618 ConflictTier::None,
2619 0,
2620 None,
2621 )
2622 .with_recognizer_metadata(
2623 Some("ner".to_string()),
2624 Some("ner.davlan-mbert.v1".to_string()),
2625 );
2626
2627 let value: serde_json::Value =
2628 serde_json::to_value(&entry).expect("serialize redaction entry");
2629
2630 assert_eq!(value["recognizer_id"], "ner");
2631 assert_eq!(value["recognizer_version_id"], "ner.davlan-mbert.v1");
2632 }
2633
2634 #[test]
2635 fn candidate_keeps_versioned_and_unversioned_recognizer_ids() {
2636 let unversioned = Candidate::new(
2637 0..5,
2638 PiiClass::Email,
2639 "email.global",
2640 0.9,
2641 10,
2642 None,
2643 "email",
2644 "email.global",
2645 ConflictTier::None,
2646 Vec::new(),
2647 );
2648 assert_eq!(unversioned.recognizer_id, "email.global");
2649 assert_eq!(unversioned.recognizer_version_id, None);
2650
2651 let versioned = unversioned
2652 .clone()
2653 .with_recognizer_version_id("email.global.v1");
2654 assert_eq!(versioned.recognizer_id, "email.global");
2655 assert_eq!(
2656 versioned.recognizer_version_id.as_deref(),
2657 Some("email.global.v1")
2658 );
2659 }
2660}
2661
2662#[cfg(test)]
2663mod safety_net_manifest_tests {
2664 use super::*;
2665
2666 fn span(start: usize, end: usize, class: PiiClass) -> EmittedTokenSpan {
2667 EmittedTokenSpan {
2668 clean_span: start..end,
2669 raw_span: start..end,
2670 class,
2671 }
2672 }
2673
2674 fn diff(manifest: Manifest, suspect: Range<usize>, class: PiiClass) -> Option<LeakKind> {
2675 manifest.diff_against(&suspect, &class)
2676 }
2677
2678 #[test]
2679 fn exact_same_class_coverage_is_not_a_leak() {
2680 let manifest = Manifest::from_spans(vec![span(0, 8, PiiClass::Email)]);
2681
2682 assert_eq!(diff(manifest, 0..8, PiiClass::Email), None);
2683 }
2684
2685 #[test]
2686 fn uncovered_outside_all_tokens_is_uncovered() {
2687 let manifest = Manifest::from_spans(vec![span(20, 30, PiiClass::Email)]);
2688
2689 assert_eq!(
2690 diff(manifest, 0..10, PiiClass::Email),
2691 Some(LeakKind::Uncovered)
2692 );
2693 }
2694
2695 #[test]
2696 fn single_internal_gap_returns_partial_bleed() {
2697 let manifest = Manifest::from_spans(vec![
2698 span(0, 5, PiiClass::Email),
2699 span(10, 15, PiiClass::Email),
2700 ]);
2701
2702 assert_eq!(
2703 diff(manifest, 0..15, PiiClass::Email),
2704 Some(LeakKind::PartialBleed { uncovered: 5..10 })
2705 );
2706 }
2707
2708 #[test]
2709 fn multi_gap_returns_deterministic_first_uncovered_gap() {
2710 let manifest = Manifest::from_spans(vec![
2711 span(0, 3, PiiClass::Email),
2712 span(5, 7, PiiClass::Email),
2713 span(9, 12, PiiClass::Email),
2714 ]);
2715
2716 assert_eq!(
2719 diff(manifest, 0..12, PiiClass::Email),
2720 Some(LeakKind::PartialBleed { uncovered: 3..5 })
2721 );
2722 }
2723
2724 #[test]
2725 fn multi_class_overlap_reports_first_mismatch_deterministically() {
2726 let manifest = Manifest::from_spans(vec![
2727 span(0, 4, PiiClass::Name),
2728 span(4, 8, PiiClass::Location),
2729 ]);
2730
2731 assert_eq!(
2732 diff(manifest, 0..8, PiiClass::Email),
2733 Some(LeakKind::ClassMismatch {
2734 pipeline_class: PiiClass::Name,
2735 safety_net_class: PiiClass::Email,
2736 })
2737 );
2738 }
2739
2740 #[test]
2741 fn adjacent_same_class_tokens_cover_continuously() {
2742 let manifest = Manifest::from_spans(vec![
2743 span(0, 5, PiiClass::Email),
2744 span(5, 10, PiiClass::Email),
2745 ]);
2746
2747 assert_eq!(diff(manifest, 0..10, PiiClass::Email), None);
2748 }
2749
2750 #[test]
2751 fn partial_bleed_at_start_end_and_middle() {
2752 let manifest = Manifest::from_spans(vec![span(3, 8, PiiClass::Email)]);
2753
2754 assert_eq!(
2755 diff(manifest.clone(), 0..8, PiiClass::Email),
2756 Some(LeakKind::PartialBleed { uncovered: 0..3 })
2757 );
2758 assert_eq!(
2759 diff(manifest.clone(), 3..10, PiiClass::Email),
2760 Some(LeakKind::PartialBleed { uncovered: 8..10 })
2761 );
2762
2763 let with_gap = Manifest::from_spans(vec![
2764 span(0, 3, PiiClass::Email),
2765 span(6, 10, PiiClass::Email),
2766 ]);
2767 assert_eq!(
2768 diff(with_gap, 0..10, PiiClass::Email),
2769 Some(LeakKind::PartialBleed { uncovered: 3..6 })
2770 );
2771 }
2772
2773 #[test]
2774 fn byte_indices_are_not_character_indices() {
2775 let text = "ID: 😀 <Email_1>";
2776 let token_start = text.find("<Email_1>").expect("token start");
2777 assert_eq!(token_start, 9, "emoji is four bytes, not one char");
2778 let manifest = Manifest::from_spans(vec![span(token_start, text.len(), PiiClass::Email)]);
2779
2780 assert_eq!(
2781 diff(manifest, token_start..text.len(), PiiClass::Email),
2782 None
2783 );
2784 }
2785
2786 #[test]
2787 fn empty_suspect_range_is_not_a_leak() {
2788 let manifest = Manifest::default();
2789
2790 assert_eq!(diff(manifest, 3..3, PiiClass::Email), None);
2791 }
2792
2793 #[test]
2794 fn safety_net_error_display_is_variant_specific_and_bytes_free() {
2795 let cases = [
2796 SafetyNetError::Unavailable {
2797 reason: "not configured".to_string(),
2798 }
2799 .to_string(),
2800 SafetyNetError::WeightsMissing {
2801 path: "/models/opf".to_string(),
2802 }
2803 .to_string(),
2804 SafetyNetError::ModelUnavailable {
2805 reason: "load failed".to_string(),
2806 }
2807 .to_string(),
2808 SafetyNetError::ModelIntegrityMismatch {
2809 expected: "e3b0c44298fc1c149afbf4c8996fb924".to_string(),
2810 actual: "4e07408562bedb8b60ce05c1decfe3ad".to_string(),
2811 }
2812 .to_string(),
2813 SafetyNetError::InputTooLarge {
2814 limit: 1024,
2815 actual: 2048,
2816 }
2817 .to_string(),
2818 SafetyNetError::Runtime {
2819 message: "timeout".to_string(),
2820 }
2821 .to_string(),
2822 SafetyNetError::InvalidOutput {
2823 message: "bad json".to_string(),
2824 }
2825 .to_string(),
2826 ];
2827
2828 for rendered in cases {
2829 assert!(!rendered.contains("alice@example.invalid"));
2830 }
2831 }
2832}
2833
2834pub trait Recognizer: Send + Sync {
2836 fn id(&self) -> &str;
2838 fn supported_class(&self) -> &PiiClass;
2840 fn detect(&self, input: &str, ctx: &DetectContext<'_>) -> Vec<Candidate>;
2842 fn token_family(&self) -> &str;
2844 fn validator_kind(&self) -> Option<ValidatorKind> {
2846 None
2847 }
2848 fn locales(&self) -> &[LocaleTag] {
2850 &[LocaleTag::Global]
2851 }
2852}
2853
2854#[derive(Debug, Clone, PartialEq)]
2856#[non_exhaustive]
2857pub struct Candidate {
2858 pub span: Range<usize>,
2860 pub class: PiiClass,
2862 pub recognizer_id: String,
2864 pub recognizer_version_id: Option<String>,
2866 pub score: f32,
2868 pub priority: i32,
2870 pub canonical_form: Option<String>,
2872 pub token_family: String,
2874 pub source: String,
2876 pub decided_by: ConflictTier,
2878 pub merged_sources: Vec<String>,
2880}
2881
2882impl Candidate {
2883 #[allow(clippy::too_many_arguments)]
2885 pub fn new(
2886 span: Range<usize>,
2887 class: PiiClass,
2888 recognizer_id: impl Into<String>,
2889 score: f32,
2890 priority: i32,
2891 canonical_form: Option<String>,
2892 token_family: impl Into<String>,
2893 source: impl Into<String>,
2894 decided_by: ConflictTier,
2895 merged_sources: Vec<String>,
2896 ) -> Self {
2897 Self {
2898 span,
2899 class,
2900 recognizer_id: recognizer_id.into(),
2901 recognizer_version_id: None,
2902 score,
2903 priority,
2904 canonical_form,
2905 token_family: token_family.into(),
2906 source: source.into(),
2907 decided_by,
2908 merged_sources,
2909 }
2910 }
2911
2912 pub fn with_span(mut self, span: Range<usize>) -> Self {
2914 self.span = span;
2915 self
2916 }
2917
2918 pub fn with_recognizer_version_id(mut self, recognizer_version_id: impl Into<String>) -> Self {
2920 self.recognizer_version_id = Some(recognizer_version_id.into());
2921 self
2922 }
2923}
2924
2925#[non_exhaustive]
2927pub struct DetectContext<'a> {
2928 pub locale_chain: &'a [LocaleTag],
2930 pub dictionaries: &'a DictionaryBundle,
2932 pub fields: &'a (),
2934 pub degraded: Cell<bool>,
2936}
2937
2938impl<'a> DetectContext<'a> {
2939 pub fn new(locale_chain: &'a [LocaleTag], dictionaries: &'a DictionaryBundle) -> Self {
2941 Self {
2942 locale_chain,
2943 dictionaries,
2944 fields: &(),
2945 degraded: Cell::new(false),
2946 }
2947 }
2948}
2949
2950fn ensure_global(tags: &mut Vec<LocaleTag>) {
2951 if !tags.contains(&LocaleTag::Global) {
2952 tags.push(LocaleTag::Global);
2953 }
2954}
2955
2956fn is_bcp47_parseable(raw: &str) -> bool {
2957 let mut parts = raw.split('-');
2958 let Some(language) = parts.next() else {
2959 return false;
2960 };
2961 if !(2..=8).contains(&language.len()) || !language.chars().all(|ch| ch.is_ascii_alphabetic()) {
2962 return false;
2963 }
2964 parts.all(|part| {
2965 (2..=8).contains(&part.len()) && part.chars().all(|ch| ch.is_ascii_alphanumeric())
2966 })
2967}
2968
2969fn canonical_other(raw: &str) -> String {
2970 let mut parts = raw.split('-');
2971 let language = parts.next().unwrap_or_default().to_ascii_lowercase();
2972 let rest = parts.map(|part| {
2973 if part.len() == 2 && part.chars().all(|ch| ch.is_ascii_alphabetic()) {
2974 part.to_ascii_uppercase()
2975 } else {
2976 part.to_ascii_lowercase()
2977 }
2978 });
2979 std::iter::once(language)
2980 .chain(rest)
2981 .collect::<Vec<_>>()
2982 .join("-")
2983}