AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

PIIMiddleware Credit_card Detector Only Matches 16-Digit Cards, Missing Amex, Diners Club And 13-Digit Visa

The credit card detector in PIIMiddleware uses a regex that only matches 16-digit card numbers, so valid 13-15 digit cards (Amex, Diners Club, legacy Visa) pass through undetected, potentially leaking PII to the model.

highConfidence 95%LangchainAffected V1.3.18

Origin Analysis

The detector's regex `\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b` is hardcoded to 16 digits in four groups; the Luhn validator `_passes_luhn` accepts 13-19 digits, but the narrow pattern prevents it from ever receiving shorter card numbers, creating a mismatch between validation range and detection scope.
Run the following Python code: ```python from langchain.agents.middleware._redaction import detect_credit_card, _passes_luhn cards = { 'Visa (16)': '4111111111111111', 'Mastercard (16)': '5555555555554444', 'Amex (15)': '378282246310005', 'Amex (15)': '371449635398431', 'Diners Club (14)': '30569309025904', 'Diners Club (14)': '38520000023237', 'Visa legacy (13)': '4222222222222', } for label, number in cards.items(): print(f'{label:<20} luhn={_passes_luhn(number)!s:<6} detected={bool(detect_credit_card(number))}') ``` Observe that Amex, Diners Club, and Visa legacy numbers are Luhn-valid but not detected.

Fixing Code Block

Edge Case Audit

The wider pattern may introduce false positives for long numeric strings that pass Luhn but are not credit cards (e.g., some national ID numbers, invoice numbers). However, the issue reports that precision was tested and unchanged. Caution: In multi-threaded environments, ensure the regex is thread-safe (it is, since local). Upgrading to a version without this fix will reintroduce the vulnerability; rollback should be avoided. The new pattern may not handle card numbers formatted with multiple spaces or tabs; ensure input normalization. Test thoroughly with card numbers containing separators.

Ecosystem Topology