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
143 changes: 142 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,9 @@
//! * detection is deterministic + offline (no external egress on classify),
//! * category identifiers serialize to stable snake_case strings.

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

// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -47,6 +49,43 @@ fn detects_valid_credit_card() {
}
}

#[test]
fn detects_card_with_adjacent_cvv_group() {
// A CVV is often written right after the card, with the same separator.
// The run is PAN + CVV; the PAN still has to pass Luhn on its own.
for raw in [
"4111 1111 1111 1111 123",
"4111-1111-1111-1111-123",
"card 4111 1111 1111 1111 1234 exp 12/26",
] {
let r = scan(raw);
assert!(r.has_category(PiiCategory::CreditCard), "missed in {raw:?}");
assert_eq!(r.level, RiskLevel::High, "{raw:?}");
assert_eq!(
r.hits,
vec![CategoryHit {
category: PiiCategory::CreditCard,
count: 1
}],
"{raw:?}"
);
}
}

#[test]
fn detects_card_with_labelled_cvv() {
// A label between the card and its CVV ends the run at the card, so the
// PAN is judged on its own and counted once.
let r = scan("card 4111 1111 1111 1111 cvv 123");
assert_eq!(
r.hits,
vec![CategoryHit {
category: PiiCategory::CreditCard,
count: 1
}]
);
}

#[test]
fn detects_iban_bank_account() {
let r = scan("transfer to GB82WEST12345698765432 please");
Expand Down Expand Up @@ -297,6 +336,25 @@ fn luhn_invalid_number_is_not_a_card() {
);
}

#[test]
fn a_run_that_starts_with_a_card_is_a_card() {
// A Luhn-valid PAN followed by more digits is still a card: the run is
// flagged whole rather than passed over because it is longer than one.
for raw in [
"4111 1111 1111 1111 003-1",
"4111 1111 1111 1111 1111 1111",
"4111 1111 1111 1111 12",
] {
let r = scan(raw);
assert!(r.has_category(PiiCategory::CreditCard), "missed in {raw:?}");
assert_eq!(r.level, RiskLevel::High, "{raw:?}");
}
// With no separator there is no head to try: an overlong run of digits is
// judged whole and is not a card.
let r = scan("41111111111111110031");
assert!(!r.has_category(PiiCategory::CreditCard), "{r:?}");
}

#[test]
fn out_of_range_octets_are_not_ipv4() {
let r = scan("coords 300.400.500.600 are nonsense");
Expand Down Expand Up @@ -483,6 +541,62 @@ fn luhn_validator_accepts_known_good_and_rejects_bad() {
assert!(!is_luhn_valid("12345")); // too short
}

#[test]
fn complete_card_validator_accepts_pan_or_pan_with_cvv_group() {
// A complete PAN, grouped or not.
assert!(is_complete_card("4111111111111111"));
assert!(is_complete_card("4111 1111 1111 1111"));
// A complete PAN followed by one adjacent group of 3–4 digits.
assert!(is_complete_card("4111 1111 1111 1111 123"));
assert!(is_complete_card("4111-1111-1111-1111-1234"));
// The whole run is Luhn-valid at 19 digits: a complete PAN as written.
assert!(is_complete_card("4111 1111 1111 1111 003"));
// Luhn-invalid PAN with a CVV-shaped tail.
assert!(!is_complete_card("1234 5678 9012 3456 123"));
// A complete PAN followed by more digits: the run starts with a card.
assert!(is_complete_card("4111 1111 1111 1111 12"));
assert!(is_complete_card("4111 1111 1111 1111 12345"));
assert!(is_complete_card("4111 1111 1111 1111 003-1"));
// No separator, so no head to try, and 20 digits is not a PAN.
assert!(!is_complete_card("41111111111111110031"));
// A valid PAN after another number on the same run is still found.
assert!(is_complete_card("1234567890123456 4111 1111 1111 1111"));
assert!(is_complete_card("1234 5678 9012 3456 4111 1111 1111 1111"));
// A group of non-ASCII digits is skipped without panicking.
assert!(is_complete_card(
"\u{661}\u{662}\u{663}\u{664} 4111 1111 1111 1111"
));
}

#[test]
fn a_card_after_another_number_on_the_same_run_is_found_and_redacted() {
for (text, redacted) in [
(
"invoice 1234567890123456 4111 1111 1111 1111",
"invoice [redacted]",
),
(
"ids 1234 5678 9012 3456 4111 1111 1111 1111 end",
"ids [redacted] end",
),
] {
let r = scan(text);
assert!(
r.has_category(PiiCategory::CreditCard),
"missed in {text:?}"
);
assert_eq!(redact_identifiers(text), redacted, "{text:?}");
}
}

#[test]
fn a_long_separated_digit_run_is_judged_in_linear_work() {
// Every group start is tried, but each stops past 19 digits, so a long run
// of single-digit groups is cheap and is not a card.
let run = "1 ".repeat(20_000);
assert!(!is_complete_card(run.trim_end()));
}

#[test]
fn international_phone_validator_bounds_digit_count() {
assert!(has_international_phone_digit_count("+1234567"));
Expand Down Expand Up @@ -526,6 +640,33 @@ fn redact_identifiers_replaces_structured_values_only() {
assert!(out.contains("patient"), "{out}");
}

#[test]
fn redact_identifiers_replaces_the_whole_card_span() {
// An adjacent CVV group belongs to the card: the span is replaced whole.
assert_eq!(
redact_identifiers("pay with 4111 1111 1111 1111 123 today"),
"pay with [redacted] today"
);
// A labelled CVV ends the run at the card; only the card is structured.
assert_eq!(
redact_identifiers("card 4111 1111 1111 1111 cvv 123"),
"card [redacted] cvv 123"
);
}

#[test]
fn redact_identifiers_replaces_a_run_that_starts_with_a_card_whole() {
// The valid PAN at the head is not left in place: the whole run goes.
for text in [
"ref 4111 1111 1111 1111 003-1 noted",
"ref 4111 1111 1111 1111 1111 1111 noted",
] {
assert_eq!(redact_identifiers(text), "ref [redacted] noted", "{text:?}");
}
let text = "ref 41111111111111110031 noted";
assert_eq!(redact_identifiers(text), text);
}

#[test]
fn redact_identifiers_keeps_values_that_fail_validation() {
// Not a valid IPv4 address, not a Luhn-valid card: left as written.
Expand Down
54 changes: 47 additions & 7 deletions crates/tinymemory-api/src/safety/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +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, digit count for
//! international phone numbers) that rejects shape-matches that aren't
//! actually valid identifiers.
//! (Luhn and complete-card grouping 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 @@ -87,6 +87,41 @@ pub(crate) fn is_luhn_valid(raw: &str) -> bool {
sum.is_multiple_of(10)
}

/// Accept a run of digits and single separators as a payment card when any
/// span of whole digit groups in it is a Luhn-valid PAN of 13–19 digits: the
/// whole run, a PAN with its CVV group written beside it, a PAN that runs on
/// into more digits, or a PAN that follows another number on the same run. The
/// whole run counts as the card, so redaction takes all of it, and no valid
/// PAN is left in place because something else is written next to it. A run
/// with no separator has no inner span and is judged whole.
pub(crate) fn is_complete_card(raw: &str) -> bool {
Comment thread
M3gA-Mind marked this conversation as resolved.
Resolved
std::iter::once(0)
.chain(raw.match_indices([' ', '-']).map(|(i, _)| i + 1))
.any(|start| starts_with_card(&raw[start..]))
}

/// Whether some whole-group prefix of `run` is a Luhn-valid PAN. It stops
/// once the prefix passes 19 digits, so a long run costs linear work, and it
/// cuts only at an ASCII separator, never inside a multi-byte character.
fn starts_with_card(run: &str) -> bool {
let mut digits = 0;
for (i, b) in run.bytes().enumerate() {
if b.is_ascii_digit() {
digits += 1;
if digits > 19 {
return false;
}
} else if matches!(b, b' ' | b'-') {
if (13..=19).contains(&digits) && is_luhn_valid(&run[..i]) {
return true;
}
} else {
return false;
}
}
(13..=19).contains(&digits) && is_luhn_valid(run)
}

/// 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.
Expand Down Expand Up @@ -177,12 +212,17 @@ fn build_rules() -> Vec<Rule> {
r"\b[A-Za-z]{2}\d{2}(?:[A-Za-z0-9]{11,30}|(?:[ -][A-Za-z0-9]{4}){2,7}(?:[ -][A-Za-z0-9]{1,3})?)\b",
Some(is_iban),
),
// Payment card: 13–19 digits with optional single separators, then
// Luhn-validated so version strings / IDs don't false-positive.
// Payment card: a run of 13 or more digits with at most one space or
// hyphen between any two of them. The pattern has no upper bound on
// purpose: it consumes the whole run so the validator can judge it as
// a unit — it is a card when any span of whole digit groups in it is a
// 13–19 digit PAN that passes Luhn (a PAN and its CVV group, a PAN
// followed by more digits, or one after another number). Redaction
// replaces the whole span, so no valid PAN is left behind in a run.
pattern_rule(
PiiCategory::CreditCard,
r"\b\d(?:[ -]?\d){12,18}\b",
Some(is_luhn_valid),
r"\b\d(?:[ -]?\d){12,}\b",
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Some(is_complete_card),
),
// US-style phone number (3-3-4 groups, requires a separator so it
// doesn't swallow arbitrary 10-digit numbers). A leading `+1` is part
Expand Down
Loading