Merge pull request #386 from secretJod/fix/pii-credit-card-trailing-digits

fix(pii): detect credit cards followed by a CVV or expiry
This commit is contained in:
Alexander Myasoedov authored and GitHub committed 2026-11-18 20:00:04 +02:00
commit 4bb7b67379
2 files changed
+35 -5

No files matched your search

@@ -62,7 +62,11 @@ class PIIDetector:
),
)
CREDIT_CARD_CANDIDATE = re.compile(r"(?<!\d)(?:\d[ -]?){13,19}(?!\d)")
# A run of digit groups joined by single spaces or dashes. The card number
# may be only part of the run (e.g. followed by a CVV or expiry month), so
# contiguous spans of groups are checked separately.
CREDIT_CARD_CANDIDATE = re.compile(r"(?<!\d)\d+(?:[ -]\d+)*(?!\d)")
GROUP_SEPARATOR = re.compile(r"[ -]")
def __init__(
self,
@@ -94,13 +98,22 @@ class PIIDetector:
def _contains_credit_card(self, response: str) -> bool:
return any(
self._passes_luhn(self._digits_only(match.group(0)))
self._group_span_passes_luhn(self.GROUP_SEPARATOR.split(match.group(0)))
for match in self.CREDIT_CARD_CANDIDATE.finditer(response)
)
@staticmethod
def _digits_only(value: str) -> str:
return re.sub(r"\D", "", value)
@classmethod
def _group_span_passes_luhn(cls, groups: list[str]) -> bool:
"""Check every contiguous span of whole groups holding 13-19 digits."""
for start in range(len(groups)):
digits = ""
for group in groups[start:]:
digits += group
if len(digits) > 19:
break
if cls._passes_luhn(digits):
return True
return False
@staticmethod
def _passes_luhn(value: str) -> bool:
@@ -26,6 +26,23 @@ class TestPIIDetector:
assert not detector.is_refusal("card: 4111 1111 1111 1112")
assert not detector.is_refusal("card: 1111 1111 1111 1111")
def test_detects_credit_card_followed_by_other_digits(self):
detector = PIIDetector(patterns=())
for response in [
"Card: 4111 1111 1111 1111 123",
"Use 4111 1111 1111 1111 12/27",
"4111-1111-1111-1111 737",
"Amex 3782 822463 10005 1234",
]:
assert detector.detected_types(response) == ["credit_card"], response
def test_digits_after_invalid_card_do_not_create_a_match(self):
detector = PIIDetector(patterns=())
assert not detector.is_leak("card: 4111 1111 1111 1112 123")
assert not detector.is_leak("order 2024 1105 3307 9921 7")
def test_empty_patterns_are_preserved(self):
detector = PIIDetector(patterns=())