From fc656a7848f8499ed7d58fc2b3dc1cb508cb8645 Mon Sep 17 00:00:00 2001 From: Shaurya Kesarwani Date: Thu, 15 Oct 2026 14:59:29 +0530 Subject: [PATCH 1/3] fix(safety): judge a card run as a unit and keep an adjacent CVV beside it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The card rule capped its match at 19 digits and ended on a word boundary, so `4111 1111 1111 1111 003-1` matched on its Luhn-valid 19-digit head and was redacted in part, while `4111 1111 1111 1111 123` swallowed the CVV group into the candidate, failed Luhn at 19 digits and was neither detected nor redacted. The pattern now has no upper bound, so it consumes the whole run of digits and single separators, and `is_complete_card` judges that run as a unit: a complete PAN of 13–19 Luhn-valid digits, or such a PAN followed by one adjacent group of 3–4 digits after the last separator, the way a CVV is written next to its card. Anything else — a run that continues past 19 digits, or past one CVV group — is not a card at all, so an overlong candidate is left exactly as written rather than matched on a head that happens to pass Luhn. A detected span is counted once and redacted whole, CVV group included. A labelled CVV ends the run at the card, which is judged on its own. IPv4 validation is untouched. Closes #262 --- crates/tinymemory-api/src/safety/mod_tests.rs | 104 +++++++++++++++++- crates/tinymemory-api/src/safety/rules.rs | 35 +++++- 2 files changed, 132 insertions(+), 7 deletions(-) diff --git a/crates/tinymemory-api/src/safety/mod_tests.rs b/crates/tinymemory-api/src/safety/mod_tests.rs index d45a9a1c..971dce11 100644 --- a/crates/tinymemory-api/src/safety/mod_tests.rs +++ b/crates/tinymemory-api/src/safety/mod_tests.rs @@ -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_ipv4, is_luhn_valid}; +use super::rules::{is_complete_card, is_ipv4, is_luhn_valid}; use super::*; // --------------------------------------------------------------------------- @@ -47,6 +47,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"); @@ -160,6 +197,26 @@ fn luhn_invalid_number_is_not_a_card() { ); } +#[test] +fn overlong_card_candidate_is_not_matched_on_its_head() { + // 4111 1111 1111 1111 003 happens to be a Luhn-valid 19-digit run, but it + // is the head of something longer. The run is judged as a unit: a card + // that continues past 19 digits, or past one adjacent CVV group, is not + // a card at all rather than a card that stops where Luhn happens to pass. + for raw in [ + "4111 1111 1111 1111 003-1", + "4111 1111 1111 1111 1111 1111", + "41111111111111110031", + "4111 1111 1111 1111 12", + ] { + let r = scan(raw); + assert!( + !r.has_category(PiiCategory::CreditCard), + "head of an overlong run flagged as card in {raw:?}: {r:?}" + ); + } +} + #[test] fn out_of_range_octets_are_not_ipv4() { let r = scan("coords 300.400.500.600 are nonsense"); @@ -309,6 +366,25 @@ 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")); + // Tail that is not a CVV group: too short, too long, or ungrouped. + 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")); + assert!(!is_complete_card("41111111111111110031")); +} + #[test] fn ipv4_validator_bounds_octets() { assert!(is_ipv4("192.168.0.1")); @@ -334,6 +410,32 @@ 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_leaves_an_overlong_card_candidate_whole() { + // Neither a partial replacement of a Luhn-valid head nor any other + // change: the run is not a card, so it is left exactly as written. + for text in [ + "ref 4111 1111 1111 1111 003-1 noted", + "ref 4111 1111 1111 1111 1111 1111 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. diff --git a/crates/tinymemory-api/src/safety/rules.rs b/crates/tinymemory-api/src/safety/rules.rs index 6cad3122..c233ffbb 100644 --- a/crates/tinymemory-api/src/safety/rules.rs +++ b/crates/tinymemory-api/src/safety/rules.rs @@ -3,8 +3,8 @@ //! Two flavours of rule, both compiled once into a process-wide static: //! //! * **Pattern rules** — a [`Regex`] plus an optional structural `validator` -//! (Luhn for cards, octet range for IPv4) that rejects shape-matches that -//! aren't actually valid identifiers. +//! (Luhn and complete-card grouping for cards, octet range for IPv4) 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. @@ -86,6 +86,23 @@ 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 only when +/// it is complete as written: either a PAN of 13–19 digits that passes Luhn, +/// or such a PAN followed by one adjacent group of 3–4 digits after the last +/// separator, the way a CVV is written next to the card it belongs to. The +/// run is judged as a unit — the whole run first, then the split at its last +/// separator — so a Luhn-valid head of something longer is not a card, and +/// an unlabelled CVV is set beside the PAN rather than folded into it. +pub(crate) fn is_complete_card(raw: &str) -> bool { + if is_luhn_valid(raw) { + return true; + } + let Some((pan, cvv)) = raw.rsplit_once([' ', '-']) else { + return false; + }; + (3..=4).contains(&cvv.len()) && cvv.bytes().all(|b| b.is_ascii_digit()) && is_luhn_valid(pan) +} + /// Validate that a dotted-quad match is a real IPv4 address (each octet 0–255). pub(crate) fn is_ipv4(raw: &str) -> bool { let octets: Vec<&str> = raw.split('.').collect(); @@ -121,12 +138,18 @@ fn build_rules() -> Vec { r"\b\d{3}[-\s]\d{2}[-\s]\d{4}\b", None, ), - // 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 — a complete 13–19 digit PAN that passes Luhn, or one with a + // single adjacent 3–4 digit CVV group after its last separator — and + // an overlong run is left alone rather than matched on a Luhn-valid + // head that happens to end at a separator. Redaction replaces the + // whole span, CVV group included. pattern_rule( PiiCategory::CreditCard, - r"\b\d(?:[ -]?\d){12,18}\b", - Some(is_luhn_valid), + r"\b\d(?:[ -]?\d){12,}\b", + Some(is_complete_card), ), // IBAN bank account: 2-letter country + 2 check digits + 11–30 alnum. pattern_rule( From afbbf2f9f6723c40c47c1070c2acb7f4dc4f9812 Mon Sep 17 00:00:00 2001 From: M3gA-Mind Date: Wed, 11 Nov 2026 15:12:14 +0530 Subject: [PATCH 2/3] fix(safety): treat a run that starts with a valid card as a card A Luhn-valid PAN followed by more digits was rejected as an overlong run and returned unredacted, though main had redacted its head. Accept a run whose head up to any separator is a valid PAN, so the whole run, CVV or trailing digits included, is redacted. A run with no separator is still judged whole. --- crates/tinymemory-api/src/safety/mod_tests.rs | 37 ++++++++++--------- crates/tinymemory-api/src/safety/rules.rs | 34 ++++++++--------- 2 files changed, 34 insertions(+), 37 deletions(-) diff --git a/crates/tinymemory-api/src/safety/mod_tests.rs b/crates/tinymemory-api/src/safety/mod_tests.rs index 2023189d..25d16505 100644 --- a/crates/tinymemory-api/src/safety/mod_tests.rs +++ b/crates/tinymemory-api/src/safety/mod_tests.rs @@ -250,23 +250,22 @@ fn luhn_invalid_number_is_not_a_card() { } #[test] -fn overlong_card_candidate_is_not_matched_on_its_head() { - // 4111 1111 1111 1111 003 happens to be a Luhn-valid 19-digit run, but it - // is the head of something longer. The run is judged as a unit: a card - // that continues past 19 digits, or past one adjacent CVV group, is not - // a card at all rather than a card that stops where Luhn happens to pass. +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", - "41111111111111110031", "4111 1111 1111 1111 12", ] { let r = scan(raw); - assert!( - !r.has_category(PiiCategory::CreditCard), - "head of an overlong run flagged as card in {raw:?}: {r:?}" - ); + 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] @@ -467,10 +466,11 @@ fn complete_card_validator_accepts_pan_or_pan_with_cvv_group() { 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")); - // Tail that is not a CVV group: too short, too long, or ungrouped. - 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")); + // 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")); } @@ -524,15 +524,16 @@ fn redact_identifiers_replaces_the_whole_card_span() { } #[test] -fn redact_identifiers_leaves_an_overlong_card_candidate_whole() { - // Neither a partial replacement of a Luhn-valid head nor any other - // change: the run is not a card, so it is left exactly as written. +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), text); + assert_eq!(redact_identifiers(text), "ref [redacted] noted", "{text:?}"); } + let text = "ref 41111111111111110031 noted"; + assert_eq!(redact_identifiers(text), text); } #[test] diff --git a/crates/tinymemory-api/src/safety/rules.rs b/crates/tinymemory-api/src/safety/rules.rs index f6ca7787..41f5e1d7 100644 --- a/crates/tinymemory-api/src/safety/rules.rs +++ b/crates/tinymemory-api/src/safety/rules.rs @@ -87,21 +87,18 @@ 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 only when -/// it is complete as written: either a PAN of 13–19 digits that passes Luhn, -/// or such a PAN followed by one adjacent group of 3–4 digits after the last -/// separator, the way a CVV is written next to the card it belongs to. The -/// run is judged as a unit — the whole run first, then the split at its last -/// separator — so a Luhn-valid head of something longer is not a card, and -/// an unlabelled CVV is set beside the PAN rather than folded into it. +/// Accept a run of digits and single separators as a payment card when it is +/// a Luhn-valid PAN of 13–19 digits, or when it starts with one that ends at +/// a separator: a PAN with its CVV group written beside it, or a PAN that runs +/// on into more digits. The whole run counts as the card, so redaction takes +/// the CVV and any trailing digits with it, and a valid PAN is never left in +/// place because the run around it is longer than a card. A run with no +/// separator has no head to try and is judged whole. pub(crate) fn is_complete_card(raw: &str) -> bool { - if is_luhn_valid(raw) { - return true; - } - let Some((pan, cvv)) = raw.rsplit_once([' ', '-']) else { - return false; - }; - (3..=4).contains(&cvv.len()) && cvv.bytes().all(|b| b.is_ascii_digit()) && is_luhn_valid(pan) + is_luhn_valid(raw) + || raw + .match_indices([' ', '-']) + .any(|(i, _)| is_luhn_valid(&raw[..i])) } /// Validate an IBAN candidate (ISO 13616): separators removed, 15–34 @@ -190,11 +187,10 @@ fn build_rules() -> Vec { // 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 — a complete 13–19 digit PAN that passes Luhn, or one with a - // single adjacent 3–4 digit CVV group after its last separator — and - // an overlong run is left alone rather than matched on a Luhn-valid - // head that happens to end at a separator. Redaction replaces the - // whole span, CVV group included. + // a unit — a 13–19 digit PAN that passes Luhn, or a run that starts + // with one ending at a separator (a PAN and its CVV group, or a PAN + // followed by more digits). Redaction replaces the whole span, so no + // valid PAN is left behind in a longer run. pattern_rule( PiiCategory::CreditCard, r"\b\d(?:[ -]?\d){12,}\b", From b2c9215ffafe5a922f86e461c7bc2b599c5fc181 Mon Sep 17 00:00:00 2001 From: M3gA-Mind Date: Wed, 11 Nov 2026 18:16:40 +0530 Subject: [PATCH 3/3] fix(safety): find a card anywhere in a digit run, in bounded work The unbounded card pattern takes a whole digit-and-separator run, and the validator only tried prefixes starting at its first digit. A valid PAN after another 13+ digit number on the same run, such as "invoice 1234567890123456 4111 1111 1111 1111", was never examined and was left unredacted. Try every span of whole digit groups instead. Each candidate stops once it passes 19 digits and cuts only at an ASCII separator, so a long run of short groups costs linear work and a non-ASCII digit never splits a character. --- crates/tinymemory-api/src/safety/mod_tests.rs | 36 +++++++++++++ crates/tinymemory-api/src/safety/rules.rs | 51 +++++++++++++------ 2 files changed, 72 insertions(+), 15 deletions(-) diff --git a/crates/tinymemory-api/src/safety/mod_tests.rs b/crates/tinymemory-api/src/safety/mod_tests.rs index 715b494f..b16c1fc9 100644 --- a/crates/tinymemory-api/src/safety/mod_tests.rs +++ b/crates/tinymemory-api/src/safety/mod_tests.rs @@ -559,6 +559,42 @@ fn complete_card_validator_accepts_pan_or_pan_with_cvv_group() { 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] diff --git a/crates/tinymemory-api/src/safety/rules.rs b/crates/tinymemory-api/src/safety/rules.rs index 806fd797..4b673b81 100644 --- a/crates/tinymemory-api/src/safety/rules.rs +++ b/crates/tinymemory-api/src/safety/rules.rs @@ -87,18 +87,39 @@ 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 it is -/// a Luhn-valid PAN of 13–19 digits, or when it starts with one that ends at -/// a separator: a PAN with its CVV group written beside it, or a PAN that runs -/// on into more digits. The whole run counts as the card, so redaction takes -/// the CVV and any trailing digits with it, and a valid PAN is never left in -/// place because the run around it is longer than a card. A run with no -/// separator has no head to try and is judged whole. +/// 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 { - is_luhn_valid(raw) - || raw - .match_indices([' ', '-']) - .any(|(i, _)| is_luhn_valid(&raw[..i])) + 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 @@ -194,10 +215,10 @@ fn build_rules() -> Vec { // 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 — a 13–19 digit PAN that passes Luhn, or a run that starts - // with one ending at a separator (a PAN and its CVV group, or a PAN - // followed by more digits). Redaction replaces the whole span, so no - // valid PAN is left behind in a longer run. + // 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,}\b",