Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 94 additions & 1 deletion crates/tinymemory-api/src/safety/mod_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
//! * detection is deterministic + offline (no external egress on classify),
//! * category identifiers serialize to stable snake_case strings.

use super::rules::{is_iban, is_ipv4, is_luhn_valid};
use super::rules::{has_international_phone_digit_count, is_iban, is_ipv4, is_luhn_valid};
use super::*;

// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -122,6 +122,91 @@ fn detects_phone_numbers_varied_formats() {
}
}

#[test]
fn international_phone_numbers_carry_seven_to_fifteen_digits() {
for raw in [
"+1234567",
"+123456789012345",
"+44 20 7946 0958",
"+1-415-555-0100",
] {
let r = scan(raw);
assert!(r.has_category(PiiCategory::PhoneNumber), "missed {raw:?}");
}
for raw in [
"+123456",
"+1234567890123456",
"+123456789012345678",
"+1 2",
] {
let r = scan(raw);
assert!(
!r.has_category(PiiCategory::PhoneNumber),
"flagged {raw:?}: {r:?}"
);
}
}

#[test]
fn an_overlong_number_is_not_matched_on_a_prefix() {
// 18 digits: no 15-digit (or shorter) head of it may count as a phone
// number, so the value is reported clean and left as written.
let text = "ref +123456789012345678 end";
assert_eq!(scan(text).level, RiskLevel::None);
assert_eq!(redact_identifiers(text), text);
}

#[test]
fn an_overlong_separated_number_is_not_matched_on_a_prefix() {
// 16 digits with a separator after the fifteenth: the rule must consume
// the whole run and reject it, not stop at the separator and accept the
// 15-digit head.
for text in [
"ref +123456789012345-6 end",
"ref +123456789012345 6 end",
"ref +1-234-567-890-123-456 end",
] {
assert_eq!(scan(text).level, RiskLevel::None, "flagged {text:?}");
assert_eq!(redact_identifiers(text), text);
}
}

#[test]
fn only_ascii_digits_make_up_an_international_phone_number() {
// Seven ASCII digits followed by nine Arabic-Indic ones: 16 digits in one
// run, past the 15-digit bound, so it is not a phone number.
let text = "ref +1234567\u{661}\u{662}\u{663}\u{664}\u{665}\u{666}\u{667}\u{668}\u{669} end";
assert!(
!scan(text).has_category(PiiCategory::PhoneNumber),
"flagged {text:?}"
);
}

#[test]
fn international_phone_separators_do_not_span_lines_or_tabs() {
// Only a space or a hyphen joins two digit groups. A newline or a tab
// ends the candidate, so two short runs on separate lines are not glued
// into one phone number.
for text in ["+1234\n567", "+1234\t567", "+123 456\n789 012"] {
assert!(
!scan(text).has_category(PiiCategory::PhoneNumber),
"flagged {text:?}"
);
}
}

#[test]
fn international_phone_redaction_covers_the_whole_number() {
assert_eq!(
redact_identifiers("call +44 20 7946 0958 now"),
"call [redacted] now"
);
assert_eq!(
redact_identifiers("call +123456789012345 now"),
"call [redacted] now"
);
}

#[test]
fn detects_ipv4_address() {
let r = scan("client connected from 192.168.10.24 last night");
Expand Down Expand Up @@ -398,6 +483,14 @@ fn luhn_validator_accepts_known_good_and_rejects_bad() {
assert!(!is_luhn_valid("12345")); // too short
}

#[test]
fn international_phone_validator_bounds_digit_count() {
assert!(has_international_phone_digit_count("+1234567"));
assert!(has_international_phone_digit_count("+1 234 567 890 123 45"));
assert!(!has_international_phone_digit_count("+123456"));
assert!(!has_international_phone_digit_count("+1234567890123456"));
}

#[test]
fn iban_validator_checks_the_mod_97_remainder() {
assert!(is_iban("GB82WEST12345698765432"));
Expand Down
28 changes: 23 additions & 5 deletions crates/tinymemory-api/src/safety/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
//! Two flavours of rule, both compiled once into a process-wide static:
//!
//! * **Pattern rules** — a [`Regex`] plus an optional structural `validator`
//! (Luhn for cards, mod-97 for IBANs, octet range for IPv4) that rejects
//! shape-matches that aren't actually valid identifiers.
//! (Luhn for cards, mod-97 for IBANs, octet range for IPv4, digit count for
//! international phone numbers) that rejects shape-matches that aren't
//! actually valid identifiers.
//! * **Keyword rules** — an alternation of domain terms wrapped in word
//! boundaries, used for the topical categories (medical / legal / financial /
//! family) where there is no single canonical value shape.
Expand Down Expand Up @@ -86,6 +87,13 @@ pub(crate) fn is_luhn_valid(raw: &str) -> bool {
sum.is_multiple_of(10)
}

/// Digit-count bounds for an international phone number: 7–15 digits once
/// separators are removed. E.164 allows at most 15, and nothing shorter than
/// 7 is a dialable subscriber number anywhere.
pub(crate) fn has_international_phone_digit_count(raw: &str) -> bool {
(7..=15).contains(&raw.bytes().filter(u8::is_ascii_digit).count())
}

/// Validate an IBAN candidate (ISO 13616): separators removed, 15–34
/// characters, a two-letter country code, two check digits, and a mod-97
/// remainder of 1 over the rearranged value with letters expanded to two
Expand Down Expand Up @@ -186,9 +194,19 @@ fn build_rules() -> Vec<Rule> {
r"(?:\+|\b)(?:1[-.\s]?)?\(?\d{3}\)?[-.\s]\d{3}[-.\s]\d{4}\b",
None,
),
// Legacy international phone-like pattern. Its repetition counts
// separators too; normalized digit bounds remain follow-up #263.
pattern_rule(PiiCategory::PhoneNumber, r"\+\d(?:[\d\s\-]{6,16}\d)", None),
// International phone number: `+` and 7–15 digits, with at most one
// space or hyphen between any two digits. The pattern has no upper
// bound on purpose: it consumes the whole digit-and-separator run, and
// the validator then rejects any run outside 7–15 digits, so an
// overlong value is left alone rather than matched on a 15-digit head
// that happens to end at a separator. Digits are ASCII only, the same
// set the validator counts; `\d` would also take other scripts' digits
// and let a run past 15 digits through.
pattern_rule(
PiiCategory::PhoneNumber,
r"\+[0-9](?:[ -]?[0-9]){6,}\b",
Some(has_international_phone_digit_count),
),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// IPv4 address (octet-validated).
pattern_rule(
PiiCategory::IpAddress,
Expand Down
Loading