Coverage for app / services / rules / pii.py: 98%
826 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2PII detection and redaction — one implementation, carried by both services.
4svc-core (``app/services/rules/pii.py``) applies it to prompts, the conversation
5history sent with them, answers to a paused run's questions and responses;
6svc-ai (``app/inference/pii.py``) to what it streams while a run is still
7going. The two files are identical, byte for byte, and
8``tools/test_shared_modules.py`` fails the build when they are not: a value one
9service redacts and the other lets through is a rule that holds or fails
10depending on where the text happened to be.
12**One class per kind of personal data.** A :class:`Recogniser` owns the formats
13its value is written in; the checks a match must pass before it counts (the
14identifier's own checksum where it has one — Luhn, mod 97, mod 11, the DNI
15letter — and the date where it encodes one); for a shape too common to redact
16on sight, such as nine bare digits, the keywords that must appear shortly
17before it ("passport", "BSN"); how it is described; and examples it must catch
18and near misses it must not, which the tests run. Adding a kind is adding a
19class. Every description of what the PII rules catch is rendered from these
20classes, so none can promise a kind no class matches — the descriptions once
21claimed national insurance numbers, which nothing matched.
23**A rule chooses kinds.** :class:`Redactor` takes the kinds a rule names, or
24the default set when it names none. Where two kinds claim overlapping text,
25the longer match wins, then the one with its keyword nearby, then the one
26whose checksum held.
28**Placeholders are keyed.** A value becomes ``[KIND_XXXX]``: its kind and four
29characters derived from the value with a secret key and the owner it belongs
30to. The same value gets the same placeholder for the same owner — across a
31conversation's turns, and in both services — so a model can still tell two
32people apart and follow one through a thread without either reaching it. The
33suffix holds 20 bits: it cannot be reversed, even by someone holding the key.
35**Never the values.** Nothing here logs, returns or stores what it matched
36except the redacted text itself: :meth:`Redactor.redact` reports kinds and
37counts, which is what the governance activity log keeps.
39**Bounded.** Every pattern is linear — no unbounded repetition that can
40backtrack — so a pathological input costs time in proportion to its length.
41"""
43from __future__ import annotations
45import bisect
46import hashlib
47import hmac
48import ipaddress
49import re
50from abc import ABC
51from collections.abc import Iterable, Iterator
52from dataclasses import dataclass
53from datetime import date
54from enum import StrEnum
55from typing import Any, ClassVar
57from app.util import vocab
59# ─── Vocabulary ───────────────────────────────────────────────────────────────
62class Region(StrEnum):
63 """Where an identifier is issued — how the rule builder groups kinds."""
65 international = "international"
66 uk = "uk"
67 eu = "eu"
68 us = "us"
71REGION_LABELS: dict[Region, str] = {
72 Region.international: "International",
73 Region.uk: "United Kingdom",
74 Region.eu: "European Union",
75 Region.us: "United States",
76}
77vocab.check(REGION_LABELS, Region)
80class Category(StrEnum):
81 """What an identifier is — contact details, a national number, money."""
83 contact = "contact"
84 personal = "personal"
85 government = "government"
86 health = "health"
87 financial = "financial"
88 location = "location"
89 network = "network"
92CATEGORY_LABELS: dict[Category, str] = {
93 Category.contact: "Contact details",
94 Category.personal: "Personal details",
95 Category.government: "Government identifier",
96 Category.health: "Health identifier",
97 Category.financial: "Financial",
98 Category.location: "Location",
99 Category.network: "Network",
100}
101vocab.check(CATEGORY_LABELS, Category)
103#: How far before a value its keyword may appear, in characters — far enough
104#: for "Date of birth (DD/MM/YYYY): ", near enough not to borrow a keyword
105#: from the sentence before.
106CONTEXT_WINDOW = 48
109# ─── Checks ───────────────────────────────────────────────────────────────────
112def _digits(value: str) -> str:
113 return "".join(ch for ch in value if ch.isdigit())
116def _alnum(value: str) -> str:
117 return "".join(ch for ch in value if ch.isalnum()).upper()
120def luhn(number: str) -> bool:
121 """The Luhn check behind card numbers and Swedish identity numbers."""
122 digits = _digits(number)
123 if not digits:
124 return False
125 total = 0
126 for position, char in enumerate(reversed(digits)):
127 digit = ord(char) - 48
128 if position % 2:
129 digit = digit * 2 - 9 if digit > 4 else digit * 2
130 total += digit
131 return total % 10 == 0
134def _mod97(numeric: str) -> int:
135 return int(numeric) % 97
138def _plausible_date(year: int, month: int, day: int) -> bool:
139 try:
140 date(year, month, day)
141 except ValueError:
142 return False
143 return True
146def _two_digit_year_date(yy: int, month: int, day: int) -> bool:
147 """A date written with a two-digit year, in either century it could be."""
148 return _plausible_date(1900 + yy, month, day) or _plausible_date(
149 2000 + yy, month, day
150 )
153# ─── Recognisers ──────────────────────────────────────────────────────────────
156@dataclass(frozen=True)
157class Format:
158 """One way a value is written.
160 ``needs_context`` marks a shape too common to redact on sight — nine bare
161 digits are a passport number after the word "passport" and an order number
162 anywhere else — so it counts only with one of its recogniser's keywords in
163 the :data:`CONTEXT_WINDOW` characters before it. ``value`` names the group
164 holding the value when a pattern also matches text around it.
165 """
167 pattern: re.Pattern[str]
168 needs_context: bool = False
169 value: str | None = None
172def _format(
173 pattern: str,
174 *,
175 needs_context: bool = False,
176 flags: int = 0,
177 value: str | None = None,
178) -> Format:
179 return Format(re.compile(pattern, flags), needs_context, value)
182@dataclass(frozen=True, order=True)
183class Detection:
184 """One value found in a text. Positions only — never the value."""
186 start: int
187 end: int
188 kind: str
191class Recogniser(ABC):
192 """Base class for one kind of personal data."""
194 #: Stable key — stored on rules, events and the redaction stats.
195 kind: ClassVar[str]
196 #: Singular and plural, as they read mid-sentence — "email address",
197 #: "IBANs", "French social security numbers (NIR)". A picker capitalises
198 #: the first letter; lower-casing one would turn "IBAN" into "iBAN".
199 label: ClassVar[str]
200 plural: ClassVar[str]
201 #: One value in its commonest written form, for descriptions.
202 example: ClassVar[str]
203 #: What qualifies the example, when the example alone would overclaim —
204 #: "after a keyword such as 'BSN'". Rendered into every description.
205 note: ClassVar[str] = ""
206 region: ClassVar[Region]
207 category: ClassVar[Category]
208 #: Part of what a rule redacts when it names no kinds.
209 default: ClassVar[bool] = True
210 formats: ClassVar[tuple[Format, ...]]
211 #: Words that make a nearby value this kind — required by a format with
212 #: ``needs_context``, a tie-breaker for the rest. Matched whole and
213 #: ignoring case.
214 keywords: ClassVar[tuple[str, ...]] = ()
215 #: True when :meth:`valid` checks something beyond the shape — a
216 #: checksum or an encoded date. Breaks ties between overlapping kinds.
217 verified: ClassVar[bool] = False
218 #: Texts the recogniser must find a value in, and texts it must not.
219 examples: ClassVar[tuple[str, ...]] = ()
220 near_misses: ClassVar[tuple[str, ...]] = ()
222 _keyword_pattern: ClassVar[re.Pattern[str] | None] = None
224 def __init_subclass__(cls, **kwargs: Any) -> None:
225 super().__init_subclass__(**kwargs)
226 if cls.keywords:
227 cls._keyword_pattern = re.compile(
228 r"(?<!\w)(?:"
229 + "|".join(
230 re.escape(k) for k in sorted(cls.keywords, key=len, reverse=True)
231 )
232 + r")(?!\w)",
233 re.IGNORECASE,
234 )
236 def valid(self, value: str) -> bool:
237 """Whether a match is really this kind. The shape alone, by default."""
238 return True
240 def canonical(self, value: str) -> str:
241 """What a placeholder is derived from: the value without its spacing,
242 so ``AB 12 34 56 C`` and ``AB123456C`` are the same person."""
243 return _alnum(value)
245 def has_context(self, text: str, start: int) -> bool:
246 if self._keyword_pattern is None:
247 return False
248 window = text[max(0, start - CONTEXT_WINDOW) : start]
249 return self._keyword_pattern.search(window) is not None
251 def _formats_for(self, text: str) -> Iterator[Format]:
252 """The formats worth running: one that needs a keyword is skipped
253 outright when the text holds none, which is most texts."""
254 keyword_anywhere: bool | None = None
255 for fmt in self.formats:
256 if fmt.needs_context:
257 if keyword_anywhere is None:
258 keyword_anywhere = bool(
259 self._keyword_pattern and self._keyword_pattern.search(text)
260 )
261 if not keyword_anywhere:
262 continue
263 yield fmt
265 def find(self, text: str) -> Iterator[tuple[int, int]]:
266 """Spans of every value of this kind in ``text``."""
267 for fmt in self._formats_for(text):
268 for match in fmt.pattern.finditer(text):
269 start, end = match.span(fmt.value) if fmt.value else match.span()
270 if fmt.needs_context and not self.has_context(text, start):
271 continue
272 if self.valid(text[start:end]):
273 yield start, end
275 def spec(self) -> dict[str, Any]:
276 """Catalogue entry — what the rule builder shows for this kind."""
277 return {
278 "key": self.kind,
279 "label": self.label,
280 "plural": self.plural,
281 "example": self.example,
282 "note": self.note,
283 "description": describe(self),
284 "region": self.region.value,
285 "region_label": REGION_LABELS[self.region],
286 "category": self.category.value,
287 "category_label": CATEGORY_LABELS[self.category],
288 "default": self.default,
289 }
292_REGISTRY: dict[str, Recogniser] = {}
295def register(cls: type[Recogniser]) -> type[Recogniser]:
296 """Class decorator adding one kind to the registry."""
297 instance = cls()
298 if instance.kind in _REGISTRY:
299 raise RuntimeError(f"PII kind '{instance.kind}' is already registered.")
300 _REGISTRY[instance.kind] = instance
301 return cls
304def describe(recogniser: Recogniser) -> str:
305 """``UK National Insurance numbers (AB 12 34 56 C)`` — one kind in words."""
306 detail = (
307 f"{recogniser.example}; {recogniser.note}"
308 if recogniser.note
309 else (recogniser.example)
310 )
311 return f"{recogniser.plural} ({detail})"
314# ── Contact ───────────────────────────────────────────────────────────────────
317@register
318class EmailAddress(Recogniser):
319 kind = "email"
320 label = "email address"
321 plural = "email addresses"
322 example = "jane.doe@example.com"
323 region = Region.international
324 category = Category.contact
325 # Bounded on both sides (RFC 5321's 64-character local part, 63-character
326 # labels) so a long run of dotted words cannot make matching quadratic.
327 formats = (
328 _format(
329 r"(?<![\w.%+'\-])[\w.%+'\-]{1,64}@(?:[^\W_](?:[\w\-]{0,61}[^\W_])?\.){1,8}"
330 # A file extension is not a top-level domain: icon@2x.png is an
331 # asset, not an address.
332 r"(?!(?:png|jpe?g|gif|svg|webp|ico|bmp|pdf|css|js|json|ya?ml|txt|html?"
333 r"|xml|csv)(?![\w\-]))[^\W\d_]{2,24}(?![\w\-])"
334 ),
335 )
336 examples = (
337 "write to jane.doe@example.com today",
338 "o'brien+news@mail.example.co.uk",
339 "josé.garcía@correo.es",
340 )
341 near_misses = ("icon@2x.png is an asset", "user@localhost", "@handle")
343 def canonical(self, value: str) -> str:
344 return value.casefold()
347_PHONE_KEYWORDS = (
348 "tel",
349 "tel.",
350 "telephone",
351 "phone",
352 "mobile",
353 "mob",
354 "cell",
355 "call",
356 "text",
357 "fax",
358 "whatsapp",
359 "contact",
360 "téléphone",
361 "portable",
362 "telefon",
363 "handy",
364 "teléfono",
365 "móvil",
366 "telefono",
367 "cellulare",
368 "telefoon",
369 "mobiel",
370)
373@register
374class PhoneNumber(Recogniser):
375 kind = "phone"
376 label = "phone number"
377 plural = "phone numbers"
378 example = "+44 20 7946 0958"
379 note = "international, UK, US and European national formats"
380 region = Region.international
381 category = Category.contact
382 keywords = _PHONE_KEYWORDS
383 formats = (
384 # International: + or 00, a country code, then the number in groups.
385 _format(r"(?<![\w+])(?:\+|\b00)[1-9][\d \-.()]{6,20}\d(?![\d])"),
386 # National, trunk prefix 0 — the UK and most of Europe:
387 # 020 7946 0958, 0161 496 0000, 07700 900123, 01 23 45 67 89.
388 _format(
389 r"(?<![\w+.,/\-])\(?0\d{1,4}\)?(?:[ \-./]\d{2,6}){1,4}(?![\w.,/\-]?\d)"
390 ),
391 # UK mobile, unspaced: distinctive enough to stand alone.
392 _format(r"(?<!\d)07[1-9]\d{8}(?!\d)"),
393 # North American: (415) 555-2671, 415-555-2671, 415.555.2671.
394 _format(r"(?<![\w+(])(?:\(\d{3}\) ?|\d{3}[ \-.])\d{3}[ \-.]\d{4}(?![\w\-]?\d)"),
395 # Ten or eleven bare digits — a phone number only when called one.
396 _format(r"(?<![\w+])0?\d{10}(?!\d)", needs_context=True),
397 )
398 examples = (
399 "call +44 20 7946 0958 after six",
400 "office: 020 7946 0958",
401 "mobile 07700 900123",
402 "07700900123",
403 "+1 (415) 555-2671",
404 "(415) 555-2671",
405 "415.555.2671",
406 "+33 1 23 45 67 89",
407 "01 23 45 67 89",
408 "+49 30 1234 5678",
409 "0044 20 7946 0958",
410 "tel: 4155552671",
411 "555-123-4567",
412 )
413 near_misses = (
414 "order 1234567890 shipped",
415 "dated 01.02.2024",
416 "on 03/04/2025",
417 "sort code 20-00-00",
418 "version 1.2.3.4",
419 "pi is 3.14159265",
420 "ISBN 0-306-40615-2",
421 )
423 def valid(self, value: str) -> bool:
424 digits = _digits(value)
425 if value.lstrip().startswith(("+", "00")):
426 # E.164 caps a number at 15 digits; fewer than 8 is not a
427 # reachable international number.
428 return (
429 8 <= len(digits) - (2 if value.lstrip().startswith("00") else 0) <= 15
430 )
431 if value.count("(") != value.count(")"):
432 return False
433 if digits.startswith("0"):
434 return 9 <= len(digits) <= 12
435 # North American: an area code never starts with 0 or 1. The exchange
436 # is not held to the same rule, so 555-123-4567 — the number every
437 # demo uses — is redacted rather than taken for a reference.
438 return len(digits) == 10 and digits[0] not in "01"
440 def canonical(self, value: str) -> str:
441 return _digits(value)
444# ── Personal ──────────────────────────────────────────────────────────────────
446_NAME_WORD = r"[^\W\d_][\w'’\-]{0,19}"
448_TITLES = (
449 r"Mr|Mrs|Ms|Miss|Mx|Dr|Prof|Sir|Dame|Lord|Lady|Rev|Herr|Frau|Monsieur|Madame"
450 r"|Mademoiselle|Mme|Mlle|Señor|Señora|Señorita|Sr|Sra|Srta|Signor|Signora"
451 r"|Sig|Dott|Dhr|Mevr"
452)
453#: Labels a form puts before a name. Capitalised on purpose: ``name: MyApp``
454#: in a YAML file is not a person.
455_NAME_LABELS = (
456 r"Name|NAME|Full [Nn]ame|FULL NAME|Patient(?: [Nn]ame)?|PATIENT(?: NAME)?"
457 r"|Customer(?: [Nn]ame)?|Client(?: [Nn]ame)?|Employee(?: [Nn]ame)?"
458 r"|Applicant|Account [Hh]older|Cardholder|Next of [Kk]in|Nom|Prénom"
459 r"|Nombre|Apellidos?|Nome|Cognome|Vorname|Nachname|Naam"
460)
463@register
464class PersonName(Recogniser):
465 kind = "name"
466 label = "name"
467 plural = "names"
468 example = "Dr Jane Smith"
469 note = "after a title (Mr, Dr, Frau, Mme…) or a label (Name:, Patient:)"
470 region = Region.international
471 category = Category.personal
472 formats = (
473 _format(
474 rf"\b(?:{_TITLES})\.? (?P<value>{_NAME_WORD}(?: {_NAME_WORD}){{0,2}})",
475 value="value",
476 ),
477 _format(
478 rf"\b(?:{_NAME_LABELS}) ?[::] ?(?P<value>{_NAME_WORD}(?: {_NAME_WORD}){{0,3}})",
479 value="value",
480 ),
481 )
482 examples = (
483 "please ask Dr Jane Smith to call",
484 "Mrs O'Brien-Hughes signed it",
485 "Patient name: Jane Doe, admitted",
486 "Herr Müller ist da",
487 "Mme Lefèvre a appelé",
488 )
489 near_misses = (
490 "name: myService",
491 "the drive was smooth",
492 "Mr. and Mrs. were there",
493 )
495 def find(self, text: str) -> Iterator[tuple[int, int]]:
496 # The pattern takes up to four words; the name is the run of them
497 # that are capitalised — "Dr Smith said" is Dr Smith, not "Smith
498 # said". The search resumes after the name rather than after the
499 # match, so "Dr Pepper and Mr Kipling" finds both.
500 for fmt in self.formats:
501 position = 0
502 while match := fmt.pattern.search(text, position):
503 start, end = match.span(fmt.value)
504 cut = start
505 for word in re.finditer(r"\S+", text[start:end]):
506 if not word.group()[0].isupper():
507 break
508 cut = start + word.end()
509 if cut > start:
510 yield start, cut
511 position = max(cut, start + 1)
513 def canonical(self, value: str) -> str:
514 return " ".join(value.casefold().split())
517_MONTHS = (
518 r"Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?"
519 r"|Sep(?:t(?:ember)?)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?"
520 r"|janvier|février|mars|avril|mai|juin|juillet|août|septembre|octobre"
521 r"|novembre|décembre|Januar|Februar|März|Juni|Juli|Oktober|Dezember"
522 r"|enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre"
523 r"|noviembre|diciembre|gennaio|febbraio|aprile|maggio|giugno|luglio"
524 r"|settembre|ottobre|dicembre|januari|februari|maart|mei|augustus"
525)
528@register
529class DateOfBirth(Recogniser):
530 kind = "date_of_birth"
531 label = "date of birth"
532 plural = "dates of birth"
533 example = "01/02/1980"
534 note = "after a keyword such as 'date of birth', 'DOB' or 'born'"
535 region = Region.international
536 category = Category.personal
537 keywords = (
538 "date of birth",
539 "birth date",
540 "birthdate",
541 "birthday",
542 "dob",
543 "d.o.b",
544 "d.o.b.",
545 "born",
546 "born on",
547 "geburtsdatum",
548 "geboren",
549 "date de naissance",
550 "né le",
551 "née le",
552 "fecha de nacimiento",
553 "nacido",
554 "nacida",
555 "data di nascita",
556 "nato il",
557 "nata il",
558 "geboortedatum",
559 "data de nascimento",
560 "data urodzenia",
561 "födelsedatum",
562 "fødselsdato",
563 "syntymäaika",
564 )
565 formats = (
566 _format(
567 r"(?<![\d/.\-])\d{1,2}[/.\-]\d{1,2}[/.\-](?:\d{4}|\d{2})(?![/.\-]?\d)",
568 needs_context=True,
569 ),
570 _format(
571 r"(?<![\d/.\-])\d{4}[/.\-]\d{1,2}[/.\-]\d{1,2}(?![/.\-]?\d)",
572 needs_context=True,
573 ),
574 _format(
575 rf"\b\d{{1,2}}(?:st|nd|rd|th|er)?\.? (?:of )?(?:{_MONTHS})\.?,? \d{{4}}\b",
576 needs_context=True,
577 flags=re.IGNORECASE,
578 ),
579 _format(
580 rf"\b(?:{_MONTHS})\.? \d{{1,2}}(?:st|nd|rd|th)?,? \d{{4}}\b",
581 needs_context=True,
582 flags=re.IGNORECASE,
583 ),
584 )
585 examples = (
586 "Date of birth: 01/02/1980.",
587 "DOB 1980-02-01",
588 "born on 1st February 1980",
589 "Geburtsdatum: 1. Februar 1980",
590 "date de naissance : 12/03/1975",
591 )
592 near_misses = ("the invoice dated 01/02/2024", "meeting on 1 February 2026")
594 def valid(self, value: str) -> bool:
595 numbers = [int(part) for part in re.findall(r"\d+", value)]
596 if len(numbers) == 3:
597 if numbers[0] > 31: # year first
598 year, month, day = numbers
599 return _plausible_date(year, month, day)
600 first, second, year = numbers
601 if year < 100:
602 return _two_digit_year_date(year, second, first) or (
603 _two_digit_year_date(year, first, second)
604 )
605 return _plausible_date(year, second, first) or _plausible_date(
606 year, first, second
607 )
608 return True # a written month is already a date
611_PASSPORT_KEYWORDS = (
612 "passport",
613 "passport number",
614 "passport no",
615 "reisepass",
616 "reisepassnummer",
617 "passnummer",
618 "passeport",
619 "pasaporte",
620 "passaporto",
621 "paspoort",
622 "passaporte",
623 "paszport",
624)
627@register
628class PassportNumber(Recogniser):
629 kind = "passport"
630 label = "passport number"
631 plural = "passport numbers"
632 example = "123456789"
633 note = "after the word 'passport', in eight languages"
634 region = Region.international
635 category = Category.government
636 keywords = _PASSPORT_KEYWORDS
637 formats = (_format(r"\b[A-Z0-9]{6,9}\b", needs_context=True),)
638 examples = (
639 "passport number 123456789",
640 "Reisepass: C01X00T47",
641 "my passport is 12AB34567",
642 )
643 near_misses = ("ticket 123456789", "passport photo taken")
645 def valid(self, value: str) -> bool:
646 return sum(ch.isdigit() for ch in value) >= 2
649@register
650class IpAddress(Recogniser):
651 kind = "ip_address"
652 label = "IP address"
653 plural = "IP addresses"
654 example = "203.0.113.42"
655 note = "IPv4 and IPv6; loopback excluded"
656 region = Region.international
657 category = Category.network
658 # Personal data when it identifies a person's connection, routine
659 # infrastructure detail when it does not — so a rule opts in.
660 default = False
661 formats = (
662 _format(r"(?<![\w.])(?:\d{1,3}\.){3}\d{1,3}(?![\w.]?\d)"),
663 _format(r"(?<![\w:])(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}(?![\w:])"),
664 )
665 examples = ("from 203.0.113.42 at noon", "client 2001:db8::8a2e:370:7334")
666 near_misses = ("localhost 127.0.0.1", "at 12:30:45", "mac 00:1A:2B:3C:4D:5E")
667 verified = True
669 def valid(self, value: str) -> bool:
670 try:
671 address = ipaddress.ip_address(value)
672 except ValueError:
673 return False
674 return not (address.is_loopback or address.is_unspecified)
676 def canonical(self, value: str) -> str:
677 return str(ipaddress.ip_address(value))
680# ── Financial ─────────────────────────────────────────────────────────────────
683def _group_spans(text: str, start: int, end: int) -> list[tuple[int, int]]:
684 """The digit-and-letter groups inside ``text[start:end]``."""
685 return [
686 (start + m.start(), start + m.end())
687 for m in re.finditer(r"[0-9A-Za-z]+", text[start:end])
688 ]
691class _Grouped(Recogniser):
692 """A value written in groups that a careless pattern runs on past.
694 "Card 4111 1111 1111 1111 2024" holds a card number followed by a year.
695 A regular expression cannot backtrack into a checksum, so the longest
696 valid run of whole groups inside each match is kept instead — starting at
697 the first group or the second, never deeper: every further start is
698 another roll of a checksum that passes one time in ten, and an order
699 number in four groups would sooner or later come up a card.
700 """
702 def find(self, text: str) -> Iterator[tuple[int, int]]:
703 for fmt in self._formats_for(text):
704 position = 0
705 while match := fmt.pattern.search(text, position):
706 groups = _group_spans(text, *match.span())
707 best: tuple[int, int] | None = None
708 for i in range(min(2, len(groups))):
709 for j in range(len(groups) - 1, i - 1, -1):
710 start, end = groups[i][0], groups[j][1]
711 if best and end - start <= best[1] - best[0]:
712 break
713 if self.valid(text[start:end]):
714 best = (start, end)
715 break
716 if best:
717 yield best
718 # Resume after the value, not after the match: the groups a
719 # match ran on past may open the next value ("… 3M02 606 ES91
720 # 2100 …"). With nothing found, every start this match offered
721 # has been tried, so resume at its third group.
722 if best:
723 position = best[1]
724 elif len(groups) > 2:
725 position = groups[2][0]
726 else:
727 position = match.end()
730def _card_scheme(digits: str) -> bool:
731 """Whether ``digits`` opens like a number a card scheme issues."""
732 length = len(digits)
733 two, four = int(digits[:2]), int(digits[:4])
734 return (
735 (digits[0] == "4" and length in (13, 16, 19)) # Visa
736 or (51 <= two <= 55 and length == 16) # Mastercard
737 or (2221 <= four <= 2720 and length == 16) # Mastercard 2-series
738 or (two in (34, 37) and length == 15) # American Express
739 or (
740 (digits.startswith("6011") or digits.startswith("65"))
741 and length in (16, 19)
742 )
743 or (644 <= int(digits[:3]) <= 649 and length in (16, 19)) # Discover
744 or (3528 <= four <= 3589 and 16 <= length <= 19) # JCB
745 or (
746 (300 <= int(digits[:3]) <= 305 or two in (36, 38, 39))
747 and 14 <= length <= 19
748 )
749 or (two == 62 and 16 <= length <= 19) # UnionPay
750 or (two in (50, 56, 57, 58, 63, 67) and 13 <= length <= 19) # Maestro
751 )
754@register
755class CardNumber(_Grouped):
756 kind = "card"
757 label = "payment card number"
758 plural = "payment card numbers"
759 example = "4111 1111 1111 1111"
760 note = "Luhn-checked; every major scheme, spaced or not"
761 region = Region.international
762 category = Category.financial
763 verified = True
764 formats = (_format(r"(?<![\d\-])\d{4}(?:[ \-]?\d{2,6}+){1,4}(?![\d])"),)
765 examples = (
766 "card 4111 1111 1111 1111 exp 12/27",
767 "5555-5555-5555-4444",
768 "amex 3782 822463 10005",
769 "4111111111111111",
770 "2223 0031 2200 3222",
771 "paid with 6011 1111 1111 1117 in 2024",
772 )
773 near_misses = ("4111 1111 1111 1112", "order 1234 5678 9012 3456")
775 def valid(self, value: str) -> bool:
776 digits = _digits(value)
777 return 13 <= len(digits) <= 19 and _card_scheme(digits) and luhn(digits)
779 def canonical(self, value: str) -> str:
780 return _digits(value)
783#: IBAN length by country — every country in the SWIFT IBAN registry.
784IBAN_LENGTHS: dict[str, int] = {
785 "AD": 24, "AE": 23, "AL": 28, "AT": 20, "AZ": 28, "BA": 20, "BE": 16,
786 "BG": 22, "BH": 22, "BR": 29, "BY": 28, "CH": 21, "CR": 22, "CY": 28,
787 "CZ": 24, "DE": 22, "DK": 18, "DO": 28, "EE": 20, "EG": 29, "ES": 24,
788 "FI": 18, "FO": 18, "FR": 27, "GB": 22, "GE": 22, "GI": 23, "GL": 18,
789 "GR": 27, "GT": 28, "HR": 21, "HU": 28, "IE": 22, "IL": 23, "IQ": 23,
790 "IS": 26, "IT": 27, "JO": 30, "KW": 30, "KZ": 20, "LB": 28, "LC": 32,
791 "LI": 21, "LT": 20, "LU": 20, "LV": 21, "LY": 25, "MC": 27, "MD": 24,
792 "ME": 22, "MK": 19, "MR": 27, "MT": 31, "MU": 30, "NL": 18, "NO": 15,
793 "PK": 24, "PL": 28, "PS": 29, "PT": 25, "QA": 29, "RO": 24, "RS": 22,
794 "SA": 24, "SC": 31, "SE": 24, "SI": 19, "SK": 24, "SM": 27, "ST": 25,
795 "SV": 28, "TL": 23, "TN": 24, "TR": 26, "UA": 29, "VA": 22, "VG": 24,
796 "XK": 20,
797} # fmt: skip
800@register
801class Iban(_Grouped):
802 kind = "iban"
803 label = "IBAN"
804 plural = "IBANs"
805 example = "GB82 WEST 1234 5698 7654 32"
806 note = "checksum-verified, every IBAN country"
807 region = Region.international
808 category = Category.financial
809 verified = True
810 formats = (_format(r"\b[A-Za-z]{2}\d{2}(?:[ ]?[A-Za-z0-9]{2,4}+){3,8}\b"),)
811 examples = (
812 "pay GB82 WEST 1234 5698 7654 32 by Friday",
813 "DE89370400440532013000",
814 "FR14 2004 1010 0505 0001 3M02 606",
815 "ES91 2100 0418 4502 0005 1332",
816 "NL91 ABNA 0417 1643 00",
817 "IT60 X054 2811 1010 0000 0123 456",
818 )
819 near_misses = ("GB82 WEST 1234 5698 7654 33", "AB12 CDEF 1234 5678")
821 def valid(self, value: str) -> bool:
822 iban = _alnum(value)
823 if IBAN_LENGTHS.get(iban[:2]) != len(iban):
824 return False
825 rearranged = iban[4:] + iban[:4]
826 numeric = "".join(str(int(ch, 36)) for ch in rearranged)
827 return _mod97(numeric) == 1
830# ── United Kingdom ────────────────────────────────────────────────────────────
833@register
834class UkNationalInsuranceNumber(Recogniser):
835 kind = "uk_nino"
836 label = "UK National Insurance number"
837 plural = "UK National Insurance numbers"
838 example = "AB 12 34 56 C"
839 region = Region.uk
840 category = Category.government
841 # HMRC's allocation rules: D, F, I, Q, U and V never open a number, O
842 # never follows, and BG, GB, KN, NK, NT, TN and ZZ are never issued.
843 formats = (
844 _format(
845 r"\b(?!BG|GB|KN|NK|NT|TN|ZZ)[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Z]"
846 r" ?\d{2} ?\d{2} ?\d{2} ?[A-D]\b",
847 flags=re.IGNORECASE,
848 ),
849 )
850 examples = ("NI number AB 12 34 56 C", "ab123456c", "JG103759A")
851 near_misses = ("QQ 12 34 56 C", "GB 12 34 56 A", "AB 12 34 56 E")
854@register
855class NhsNumber(Recogniser):
856 kind = "nhs_number"
857 label = "NHS number"
858 plural = "NHS numbers"
859 example = "943 476 5919"
860 note = "mod-11 checked"
861 region = Region.uk
862 category = Category.health
863 verified = True
864 keywords = ("nhs", "nhs no", "nhs number", "patient", "chi", "hospital number")
865 formats = (
866 _format(r"(?<![\d\-])\d{3}[ \-]\d{3}[ \-]\d{4}(?![\d\-])"),
867 _format(r"(?<!\d)\d{10}(?!\d)", needs_context=True),
868 )
869 examples = ("NHS no. 943 476 5919", "943-476-5919", "NHS number 9434765919")
870 near_misses = ("943 476 5918", "9434765919 rows")
872 def valid(self, value: str) -> bool:
873 digits = _digits(value)
874 if len(digits) != 10 or len(set(digits)) == 1:
875 return False
876 total = sum(int(d) * w for d, w in zip(digits[:9], range(10, 1, -1)))
877 check = 11 - total % 11
878 if check == 11:
879 check = 0
880 return check != 10 and check == int(digits[9])
883@register
884class UkDrivingLicence(Recogniser):
885 kind = "uk_driving_licence"
886 label = "UK driving licence number"
887 plural = "UK driving licence numbers"
888 example = "MORGA753116SM9IJ"
889 region = Region.uk
890 category = Category.government
891 # Surname (padded with 9s), decade, month (+5 for women), day, year,
892 # initials, a digit and two check letters.
893 formats = (
894 _format(
895 r"\b[A-Z9]{5} ?\d[0156]\d(?:0[1-9]|[12]\d|3[01])\d ?[A-Z9]{2}\d[A-Z]{2}\b"
896 ),
897 )
898 examples = ("licence MORGA753116SM9IJ", "SMITH 802153 JJ9AB")
899 near_misses = ("MORGA753116SM9I", "MORGA793116SM9IJ")
902@register
903class UkTaxReference(Recogniser):
904 kind = "uk_utr"
905 label = "UK Unique Taxpayer Reference"
906 plural = "UK Unique Taxpayer References"
907 example = "12345 67890"
908 note = "after a keyword such as 'UTR'"
909 region = Region.uk
910 category = Category.government
911 keywords = (
912 "utr",
913 "unique taxpayer reference",
914 "taxpayer reference",
915 "self assessment",
916 )
917 formats = (_format(r"(?<!\d)\d{5} ?\d{5}(?!\d)K?", needs_context=True),)
918 examples = ("UTR: 12345 67890", "my unique taxpayer reference is 1234567890")
919 near_misses = ("reference 1234567890",)
922@register
923class UkBankAccount(Recogniser):
924 kind = "uk_bank_account"
925 label = "UK sort code or account number"
926 plural = "UK sort codes and account numbers"
927 example = "20-00-00 55779911"
928 note = "after a keyword such as 'sort code' or 'account'"
929 region = Region.uk
930 category = Category.financial
931 keywords = (
932 "sort code",
933 "sort-code",
934 "sortcode",
935 "s/c",
936 "account",
937 "account number",
938 "account no",
939 "acct",
940 "a/c",
941 "bank",
942 "bank details",
943 )
944 formats = (
945 _format(r"(?<![\d\-])\d{2}[ \-]\d{2}[ \-]\d{2}(?![\d\-])", needs_context=True),
946 _format(r"(?<!\d)\d{8}(?!\d)", needs_context=True),
947 )
948 examples = ("sort code 20-00-00, account 55779911", "Bank: 20 00 00 55779911")
949 near_misses = ("dated 20-00-00", "ref 55779911")
952@register
953class UkPostcode(Recogniser):
954 kind = "uk_postcode"
955 label = "UK postcode"
956 plural = "UK postcodes"
957 example = "SW1A 2AA"
958 region = Region.uk
959 category = Category.location
960 # Identifying with a house number, an area without one — so a rule opts in.
961 default = False
962 formats = (
963 _format(
964 r"\b(?:[A-PR-UWYZ][A-HK-Y]?\d[A-HJKPSTUW\d]?|[A-PR-UWYZ]\d[A-HJKPSTUW]"
965 r"|[A-PR-UWYZ][A-HK-Y]\d[ABEHMNPRV-Y]) ?\d[ABD-HJLNP-UW-Z]{2}\b"
966 ),
967 )
968 examples = ("10 Downing Street, London SW1A 2AA", "M1 1AE", "B33 8TH")
969 near_misses = ("SW1A 2AC", "model X1 9VV")
972# ── United States ─────────────────────────────────────────────────────────────
975@register
976class UsSocialSecurityNumber(Recogniser):
977 # Stored as ``ssn`` since before kinds had regions: redaction events and
978 # the stats behind them use the key.
979 kind = "ssn"
980 label = "US social security number"
981 plural = "US social security numbers"
982 example = "123-45-6789"
983 region = Region.us
984 category = Category.government
985 keywords = ("ssn", "social security", "social security number", "ss#")
986 formats = (
987 _format(r"(?<![\d\-])\d{3}-\d{2}-\d{4}(?![\d\-])"),
988 _format(
989 r"(?<!\d)\d{3} \d{2} \d{4}(?!\d)|(?<!\d)\d{9}(?!\d)", needs_context=True
990 ),
991 )
992 examples = ("SSN 123-45-6789", "social security number 123 45 6789")
993 near_misses = ("000-12-3456", "666-12-3456", "123-00-4567")
995 def valid(self, value: str) -> bool:
996 digits = _digits(value)
997 area, group, serial = digits[:3], digits[3:5], digits[5:]
998 return (
999 area not in ("000", "666")
1000 and area[0] != "9"
1001 and group != "00"
1002 and serial != "0000"
1003 )
1006# ── European Union ────────────────────────────────────────────────────────────
1009@register
1010class FrenchSocialSecurityNumber(Recogniser):
1011 kind = "fr_nir"
1012 label = "French social security number (NIR)"
1013 plural = "French social security numbers (NIR)"
1014 example = "1 85 05 78 006 084 91"
1015 note = "key-checked"
1016 region = Region.eu
1017 category = Category.government
1018 verified = True
1019 formats = (
1020 _format(
1021 r"(?<![\w])[1-478] ?\d{2} ?\d{2} ?(?:\d{2}|2[ABab]) ?\d{3} ?\d{3} ?\d{2}(?![\w])"
1022 ),
1023 )
1024 examples = ("NIR 1 85 05 78 006 084 91", "185057800608491", "2 69 05 2A 004 011 29")
1025 near_misses = ("1 85 05 78 006 084 92",)
1027 def valid(self, value: str) -> bool:
1028 compact = _alnum(value)
1029 if len(compact) != 15:
1030 return False
1031 body = compact[:13].replace("2A", "19").replace("2B", "18")
1032 if not body.isdigit():
1033 return False
1034 return 97 - _mod97(body) == int(compact[13:])
1037def _steuer_id_valid(digits: str) -> bool:
1038 """ISO 7064 MOD 11,10, plus the rule that exactly one digit repeats."""
1039 if len(digits) != 11 or digits[0] == "0":
1040 return False
1041 counts = [digits[:10].count(d) for d in set(digits[:10])]
1042 if sorted(c for c in counts if c > 1) not in ([2], [3]):
1043 return False
1044 product = 10
1045 for char in digits[:10]:
1046 total = (int(char) + product) % 10 or 10
1047 product = (total * 2) % 11
1048 check = 11 - product
1049 return (0 if check == 10 else check) == int(digits[10])
1052@register
1053class GermanTaxId(Recogniser):
1054 kind = "de_tax_id"
1055 label = "German tax ID (Steuer-ID)"
1056 plural = "German tax IDs (Steuer-ID)"
1057 example = "86 095 742 719"
1058 note = "checksum-verified, after a keyword such as 'Steuer-ID'"
1059 region = Region.eu
1060 category = Category.government
1061 verified = True
1062 keywords = (
1063 "steuer-id",
1064 "steuerid",
1065 "steuer-identifikationsnummer",
1066 "steueridentifikationsnummer",
1067 "identifikationsnummer",
1068 "idnr",
1069 "tax id",
1070 "tin",
1071 )
1072 formats = (_format(r"(?<!\d)\d{2} ?\d{3} ?\d{3} ?\d{3}(?!\d)", needs_context=True),)
1073 examples = ("Steuer-ID: 86 095 742 719", "Identifikationsnummer 86095742719")
1074 near_misses = ("Steuer-ID: 86095742718",)
1076 def valid(self, value: str) -> bool:
1077 return _steuer_id_valid(_digits(value))
1080_DNI_LETTERS = "TRWAGMYFPDXBNJZSQVHLCKE"
1083@register
1084class SpanishDni(Recogniser):
1085 kind = "es_dni"
1086 label = "Spanish DNI or NIE number"
1087 plural = "Spanish DNI and NIE numbers"
1088 example = "12345678Z"
1089 note = "check letter verified"
1090 region = Region.eu
1091 category = Category.government
1092 verified = True
1093 formats = (
1094 _format(r"\b\d{8}[ \-]?[A-Za-z]\b"),
1095 _format(r"\b[XYZxyz][ \-]?\d{7}[ \-]?[A-Za-z]\b"),
1096 )
1097 examples = ("DNI 12345678Z", "NIE X1234567L", "12345678-z")
1098 near_misses = ("12345678A", "X1234567A")
1100 def valid(self, value: str) -> bool:
1101 compact = _alnum(value)
1102 number = compact[:-1].replace("X", "0").replace("Y", "1").replace("Z", "2")
1103 return number.isdigit() and _DNI_LETTERS[int(number) % 23] == compact[-1]
1106_CF_ODD = {
1107 **dict(zip("0123456789", (1, 0, 5, 7, 9, 13, 15, 17, 19, 21))),
1108 **dict(
1109 zip(
1110 "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
1111 (1, 0, 5, 7, 9, 13, 15, 17, 19, 21, 2, 4, 18, 20, 11, 3, 6, 8, 12, 14,
1112 16, 10, 22, 25, 24, 23),
1113 )
1114 ),
1115} # fmt: skip
1118@register
1119class ItalianFiscalCode(Recogniser):
1120 kind = "it_fiscal_code"
1121 label = "Italian fiscal code (codice fiscale)"
1122 plural = "Italian fiscal codes (codice fiscale)"
1123 example = "RSSMRA85T10A562S"
1124 note = "check character verified"
1125 region = Region.eu
1126 category = Category.government
1127 verified = True
1128 # Digits may be swapped for letters (omocodia) when two people would
1129 # otherwise share a code.
1130 formats = (
1131 _format(
1132 r"\b[A-Z]{6}[\dLMNPQRSTUV]{2}[ABCDEHLMPRST][\dLMNPQRSTUV]{2}[A-Z]"
1133 r"[\dLMNPQRSTUV]{3}[A-Z]\b"
1134 ),
1135 )
1136 examples = ("codice fiscale RSSMRA85T10A562S",)
1137 near_misses = ("RSSMRA85T10A562T",)
1139 def valid(self, value: str) -> bool:
1140 code = value.upper()
1141 total = sum(
1142 _CF_ODD[ch] if i % 2 == 0 else (int(ch) if ch.isdigit() else ord(ch) - 65)
1143 for i, ch in enumerate(code[:15])
1144 )
1145 return chr(65 + total % 26) == code[15]
1148def _bsn_valid(digits: str) -> bool:
1149 if len(digits) != 9 or digits == "000000000":
1150 return False
1151 total = sum(int(d) * w for d, w in zip(digits[:8], range(9, 1, -1)))
1152 return (total - int(digits[8])) % 11 == 0
1155@register
1156class DutchBsn(Recogniser):
1157 kind = "nl_bsn"
1158 label = "Dutch citizen service number (BSN)"
1159 plural = "Dutch citizen service numbers (BSN)"
1160 example = "111222333"
1161 note = "11-proof checked, after a keyword such as 'BSN'"
1162 region = Region.eu
1163 category = Category.government
1164 verified = True
1165 keywords = ("bsn", "burgerservicenummer", "sofinummer", "citizen service number")
1166 formats = (
1167 _format(r"(?<![\d.])\d{4}\.?\d{2}\.?\d{3}(?!\.?\d)", needs_context=True),
1168 )
1169 examples = ("BSN: 111222333.", "burgerservicenummer 1112.22.333")
1170 near_misses = ("BSN: 111222334",)
1172 def valid(self, value: str) -> bool:
1173 return _bsn_valid(_digits(value))
1176@register
1177class BelgianNationalNumber(Recogniser):
1178 kind = "be_national_number"
1179 label = "Belgian national register number"
1180 plural = "Belgian national register numbers"
1181 example = "85.07.30-033.28"
1182 note = "checksum-verified"
1183 region = Region.eu
1184 category = Category.government
1185 verified = True
1186 keywords = (
1187 "rijksregisternummer",
1188 "rijksregister",
1189 "numéro national",
1190 "registre national",
1191 "national number",
1192 "national register",
1193 "insz",
1194 "niss",
1195 )
1196 formats = (
1197 _format(r"(?<![\d.])\d{2}\.\d{2}\.\d{2}-\d{3}\.\d{2}(?!\.?\d)"),
1198 _format(r"(?<!\d)\d{11}(?!\d)", needs_context=True),
1199 )
1200 examples = ("NN 85.07.30-033.28.", "rijksregisternummer 85073003328")
1201 near_misses = ("85.07.30-033.29",)
1203 def valid(self, value: str) -> bool:
1204 digits = _digits(value)
1205 if len(digits) != 11:
1206 return False
1207 check = int(digits[9:])
1208 # Born in 2000 or later: the check is computed with a leading 2.
1209 return check in (97 - _mod97(digits[:9]), 97 - _mod97("2" + digits[:9]))
1212def _pesel_valid(digits: str) -> bool:
1213 if len(digits) != 11:
1214 return False
1215 weights = (1, 3, 7, 9, 1, 3, 7, 9, 1, 3)
1216 total = sum(int(d) * w for d, w in zip(digits, weights))
1217 if (10 - total % 10) % 10 != int(digits[10]):
1218 return False
1219 year, month, day = int(digits[:2]), int(digits[2:4]), int(digits[4:6])
1220 century = {0: 1900, 2: 2000, 4: 2100, 6: 2200, 8: 1800}.get(month // 20 * 2)
1221 return century is not None and _plausible_date(century + year, month % 20, day)
1224@register
1225class PolishPesel(Recogniser):
1226 kind = "pl_pesel"
1227 label = "Polish PESEL number"
1228 plural = "Polish PESEL numbers"
1229 example = "44051401359"
1230 note = "checksum and date verified, after the keyword 'PESEL'"
1231 region = Region.eu
1232 category = Category.government
1233 verified = True
1234 keywords = ("pesel",)
1235 formats = (_format(r"(?<!\d)\d{11}(?!\d)", needs_context=True),)
1236 examples = ("PESEL: 44051401359", "numer PESEL 02070803628")
1237 near_misses = ("PESEL: 44051401358",)
1239 def valid(self, value: str) -> bool:
1240 return _pesel_valid(_digits(value))
1243@register
1244class SwedishPersonnummer(Recogniser):
1245 kind = "se_personnummer"
1246 label = "Swedish personal identity number"
1247 plural = "Swedish personal identity numbers"
1248 example = "811218-9876"
1249 note = "Luhn and date verified"
1250 region = Region.eu
1251 category = Category.government
1252 verified = True
1253 keywords = ("personnummer", "personnr", "samordningsnummer")
1254 formats = (
1255 _format(r"(?<![\d\-])(?:\d{2})?\d{6}[\-+]\d{4}(?![\d\-])"),
1256 _format(r"(?<!\d)(?:\d{2})?\d{10}(?!\d)", needs_context=True),
1257 )
1258 examples = ("personnummer 811218-9876", "19811218-9876")
1259 near_misses = ("811218-9875", "811318-9876")
1261 def valid(self, value: str) -> bool:
1262 digits = _digits(value)[-10:]
1263 if len(digits) != 10 or not luhn(digits):
1264 return False
1265 # Coordination numbers add 60 to the day.
1266 day = int(digits[4:6])
1267 return _two_digit_year_date(
1268 int(digits[:2]), int(digits[2:4]), day - 60 if day > 60 else day
1269 )
1272@register
1273class DanishCpr(Recogniser):
1274 kind = "dk_cpr"
1275 label = "Danish CPR number"
1276 plural = "Danish CPR numbers"
1277 example = "070761-4285"
1278 note = "date verified, after a keyword such as 'CPR'"
1279 region = Region.eu
1280 category = Category.government
1281 verified = True
1282 keywords = ("cpr", "cpr-nr", "cpr-nummer", "cpr nr", "personnummer")
1283 formats = (_format(r"(?<![\d\-])\d{6}-?\d{4}(?![\d\-])", needs_context=True),)
1284 examples = ("CPR-nr. 070761-4285", "CPR 0707614285")
1285 near_misses = ("CPR 320761-4285",)
1287 def valid(self, value: str) -> bool:
1288 digits = _digits(value)
1289 return _two_digit_year_date(int(digits[4:6]), int(digits[2:4]), int(digits[:2]))
1292_HETU_CHECKS = "0123456789ABCDEFHJKLMNPRSTUVWXY"
1295@register
1296class FinnishHetu(Recogniser):
1297 kind = "fi_hetu"
1298 label = "Finnish personal identity code (HETU)"
1299 plural = "Finnish personal identity codes (HETU)"
1300 example = "131052-308T"
1301 note = "check character and date verified"
1302 region = Region.eu
1303 category = Category.government
1304 verified = True
1305 formats = (_format(r"\b\d{6}[\-+A-FU-Y]\d{3}[0-9A-Y]\b"),)
1306 examples = ("HETU 131052-308T", "010101A123N")
1307 near_misses = ("131052-308U",)
1309 def valid(self, value: str) -> bool:
1310 value = value.upper()
1311 day, month, year = int(value[:2]), int(value[2:4]), int(value[4:6])
1312 century = {"+": 1800, "-": 1900, "A": 2000}.get(value[6], 1900)
1313 if value[6] in "BCDEF":
1314 century = 2000
1315 if not _plausible_date(century + year, month, day):
1316 return False
1317 return _HETU_CHECKS[int(value[:6] + value[7:10]) % 31] == value[10]
1320@register
1321class IrishPpsn(Recogniser):
1322 kind = "ie_ppsn"
1323 label = "Irish PPS number"
1324 plural = "Irish PPS numbers"
1325 example = "1234567T"
1326 note = "check letter verified, after a keyword such as 'PPS'"
1327 region = Region.eu
1328 category = Category.government
1329 verified = True
1330 keywords = ("pps", "ppsn", "pps number", "pps no", "personal public service")
1331 formats = (_format(r"\b\d{7}[A-Wa-w][ABHWabhw]?\b", needs_context=True),)
1332 examples = ("PPS number 1234567T", "PPSN: 1234567TW")
1333 near_misses = ("PPS number 1234567A",)
1335 def valid(self, value: str) -> bool:
1336 value = value.upper()
1337 total = sum(int(d) * w for d, w in zip(value[:7], range(8, 1, -1)))
1338 if len(value) == 9 and value[8] != "W":
1339 total += (ord(value[8]) - 64) * 9
1340 return "WABCDEFGHIJKLMNOPQRSTUV"[total % 23] == value[7]
1343@register
1344class PortugueseNif(Recogniser):
1345 kind = "pt_nif"
1346 label = "Portuguese tax number (NIF)"
1347 plural = "Portuguese tax numbers (NIF)"
1348 example = "123456789"
1349 note = "check digit verified, after a keyword such as 'NIF'"
1350 region = Region.eu
1351 category = Category.government
1352 verified = True
1353 keywords = ("nif", "contribuinte", "número de contribuinte", "identificação fiscal")
1354 formats = (_format(r"(?<!\d)[1-35689]\d{8}(?!\d)", needs_context=True),)
1355 examples = ("NIF 123456789", "contribuinte n.º 123456789")
1356 near_misses = ("NIF 123456788",)
1358 def valid(self, value: str) -> bool:
1359 digits = _digits(value)
1360 total = sum(int(d) * w for d, w in zip(digits[:8], range(9, 1, -1)))
1361 check = 11 - total % 11
1362 return (0 if check >= 10 else check) == int(digits[8])
1365# ─── The registry, as a vocabulary ────────────────────────────────────────────
1367#: Every kind, in registration order — the order the builder lists them in.
1368KINDS: tuple[str, ...] = tuple(_REGISTRY)
1369#: What a rule redacts when it names no kinds.
1370DEFAULT_KINDS: frozenset[str] = frozenset(k for k, r in _REGISTRY.items() if r.default)
1373def get(kind: str) -> Recogniser | None:
1374 """The recogniser registered for ``kind``, if any."""
1375 return _REGISTRY.get(kind)
1378def recognisers() -> list[Recogniser]:
1379 """Every recogniser, in registration order."""
1380 return list(_REGISTRY.values())
1383def catalogue() -> list[dict[str, Any]]:
1384 """Every kind as the rule builder lists it."""
1385 return [recogniser.spec() for recogniser in _REGISTRY.values()]
1388def parse_kinds(raw: Any) -> tuple[frozenset[str] | None, list[str]]:
1389 """A rule's ``kinds`` parameter: the kinds it names, and any it names that
1390 do not exist.
1392 Accepts a list or the comma-separated string the rule builder stores.
1393 None (or nothing named) means the default set — a rule written before
1394 kinds existed redacts what a rule that names none does today.
1395 """
1396 if raw is None:
1397 return None, []
1398 items = (
1399 raw if isinstance(raw, (list, tuple, set, frozenset)) else str(raw).split(",")
1400 )
1401 named = [str(item).strip().lower() for item in items if str(item).strip()]
1402 if not named:
1403 return None, []
1404 unknown = [kind for kind in named if kind not in _REGISTRY]
1405 known = frozenset(kind for kind in named if kind in _REGISTRY)
1406 # A rule naming only kinds that do not exist (one written against a newer
1407 # release, say) redacts the default set rather than nothing: an empty set
1408 # would be a redaction rule that silently stopped redacting.
1409 return (known or None), unknown
1412def summary(kinds: Iterable[str] | None = None) -> str:
1413 """The kinds as one phrase — "email addresses, phone numbers and IBANs" —
1414 in registration order, for descriptions."""
1415 chosen = DEFAULT_KINDS if kinds is None else set(kinds)
1416 return vocab.one_of(
1417 [r.plural for r in _REGISTRY.values() if r.kind in chosen],
1418 quote="",
1419 conjunction="and",
1420 )
1423# ─── Placeholders ─────────────────────────────────────────────────────────────
1425#: Used when a service has no secret to derive the key from — tests and a bare
1426#: development stack. Never in production: both services refuse to start
1427#: there without ``INTERNAL_JWT_SECRET``.
1428_DEVELOPMENT_SECRET = "chainr-development-only-placeholder-key" # nosec B105 — no secret: the stand-in when a stack has none
1430_CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
1433def placeholder_key(secret: str | None) -> bytes:
1434 """The placeholder key derived from a service secret.
1436 Derived rather than the secret itself, under a label of its own, so a
1437 placeholder can never stand in for anything the secret signs.
1438 """
1439 return hmac.new(
1440 (secret or _DEVELOPMENT_SECRET).encode(),
1441 b"chainr/pii-placeholder/v1",
1442 hashlib.sha256,
1443 ).digest()
1446def _suffix(key: bytes, owner: str, kind: str, canonical: str) -> str:
1447 digest = hmac.new(
1448 key, f"{owner}\x1f{kind}\x1f{canonical}".encode(), hashlib.sha256
1449 ).digest()
1450 bits = int.from_bytes(digest[:3], "big") >> 4 # 20 bits
1451 return "".join(_CROCKFORD[(bits >> shift) & 31] for shift in (15, 10, 5, 0))
1454#: Every placeholder this module writes, so a later pass never re-reads one
1455#: as a value and a stream can tell one apart from text.
1456PLACEHOLDER = re.compile(r"\[[A-Z][A-Z_]*(?:_[0-9A-HJKMNP-TV-Z]{4})?\]")
1459# ─── Redaction ────────────────────────────────────────────────────────────────
1462class Redactor:
1463 """Detects and redacts the kinds one rule (or several, merged) names.
1465 ``key`` and ``owner`` make placeholders: the same value for the same owner
1466 always becomes the same ``[KIND_XXXX]``. Without a key, a placeholder is
1467 the kind alone.
1468 """
1470 def __init__(
1471 self,
1472 kinds: Iterable[str] | None = None,
1473 *,
1474 key: bytes | None = None,
1475 owner: str | None = None,
1476 ) -> None:
1477 chosen = DEFAULT_KINDS if kinds is None else frozenset(kinds)
1478 self.kinds: frozenset[str] = frozenset(k for k in chosen if k in _REGISTRY)
1479 self._recognisers = [r for r in _REGISTRY.values() if r.kind in self.kinds]
1480 self._key = key
1481 self._owner = owner or ""
1483 def merged(self, other: Redactor | None) -> Redactor:
1484 """A redactor covering this one's kinds and ``other``'s."""
1485 if other is None:
1486 return self
1487 return Redactor(
1488 self.kinds | other.kinds, key=self._key or other._key, owner=self._owner
1489 )
1491 def detect(self, text: str) -> list[Detection]:
1492 """Every value in ``text``, overlaps resolved, in order."""
1493 if not text:
1494 return []
1495 protected = [m.span() for m in PLACEHOLDER.finditer(text)]
1496 # Ranked longest first, then with its keyword nearby, then verified,
1497 # then registration order — and taken greedily, so an IBAN beats the
1498 # card-shaped run inside it and "call 943 476 5919" is a phone number.
1499 ranked: list[tuple[tuple[int, bool, bool, int], Detection]] = []
1500 for order, recogniser in enumerate(self._recognisers):
1501 for start, end in recogniser.find(text):
1502 if any(start < p_end and p_start < end for p_start, p_end in protected):
1503 continue
1504 rank = (
1505 end - start,
1506 recogniser.has_context(text, start),
1507 recogniser.verified,
1508 -order,
1509 )
1510 ranked.append((rank, Detection(start, end, recogniser.kind)))
1511 ranked.sort(key=lambda item: item[0], reverse=True)
1512 # Kept sorted and disjoint, so each candidate is checked against its
1513 # two neighbours rather than everything taken so far — a text with
1514 # thousands of values stays linear-logarithmic.
1515 starts: list[int] = []
1516 taken: list[Detection] = []
1517 for _, found in ranked:
1518 at = bisect.bisect_left(starts, found.start)
1519 if at > 0 and taken[at - 1].end > found.start:
1520 continue
1521 if at < len(taken) and taken[at].start < found.end:
1522 continue
1523 starts.insert(at, found.start)
1524 taken.insert(at, found)
1525 return taken
1527 def kinds_in(self, text: str) -> list[str]:
1528 """The kinds present in ``text``, in registration order."""
1529 found = {d.kind for d in self.detect(text)}
1530 return [kind for kind in KINDS if kind in found]
1532 def placeholder(self, kind: str, value: str) -> str:
1533 label = kind.upper()
1534 recogniser = _REGISTRY.get(kind)
1535 if self._key is None or recogniser is None:
1536 return f"[{label}]"
1537 return f"[{label}_{_suffix(self._key, self._owner, kind, recogniser.canonical(value))}]"
1539 def redact(self, text: str) -> tuple[str, dict[str, int]]:
1540 """``text`` with every value replaced, and how many of each kind.
1542 The counts are what the governance activity log records — "2 email
1543 addresses and 1 card number were removed" — never the values: a log
1544 quoting them would be a copy of exactly what the rule exists to
1545 remove, kept longer than the conversation it came from.
1546 """
1547 if not text:
1548 return text, {}
1549 detections = self.detect(text)
1550 if not detections:
1551 return text, {}
1552 return self.render(text, detections, 0, len(text))
1554 def render(
1555 self, text: str, detections: list[Detection], start: int, end: int
1556 ) -> tuple[str, dict[str, int]]:
1557 """``text[start:end]`` with the ``detections`` in it replaced.
1559 A detection reaching outside the range is still replaced by its
1560 placeholder rather than half-shown — the stream never cuts through a
1561 value, but if it ever did, the half it had not yet released stays
1562 hidden.
1563 """
1564 counts: dict[str, int] = {}
1565 pieces: list[str] = []
1566 cursor = start
1567 for found in detections:
1568 if found.end <= start or found.start >= end:
1569 continue
1570 pieces.append(text[cursor : max(cursor, found.start)])
1571 pieces.append(self.placeholder(found.kind, text[found.start : found.end]))
1572 counts[found.kind] = counts.get(found.kind, 0) + 1
1573 cursor = min(found.end, end)
1574 pieces.append(text[cursor:end])
1575 return "".join(pieces), counts
1577 def redact_values(self, value: Any) -> Any:
1578 """``value`` with every string in it redacted, keys and shape kept."""
1579 if isinstance(value, str):
1580 return self.redact(value)[0]
1581 if isinstance(value, dict):
1582 return {k: self.redact_values(v) for k, v in value.items()}
1583 if isinstance(value, (list, tuple)):
1584 return [self.redact_values(v) for v in value]
1585 return value
1588# ─── Streams ──────────────────────────────────────────────────────────────────
1590#: Text a stream holds back before releasing it. Longer than any value that
1591#: contains a space (an IBAN in groups, a name with its title), so a value
1592#: cannot straddle what has been released and what has not; a value without
1593#: one is never cut, because the stream cuts only at whitespace.
1594STREAM_HOLD = 96
1596#: Held text past which a stream with no whitespace (an encoded blob, a
1597#: minified file) is cut anyway, at the last non-word character outside every
1598#: value — rather than held, and re-read on every token, without end.
1599STREAM_FORCE = 1024
1602class StreamRedactor:
1603 """Redacts text that arrives a token at a time.
1605 A token is released only once nothing after it could still make it part
1606 of a value: the stream holds :data:`STREAM_HOLD` characters back and cuts
1607 only at whitespace outside every value found. The text already released
1608 stays visible to the recognisers, so "passport number" in one token still
1609 marks the digits in the next.
1610 """
1612 def __init__(self, redactor: Redactor) -> None:
1613 self._redactor = redactor
1614 self._pending = ""
1615 self._context = ""
1617 def feed(self, token: str) -> str:
1618 """Add ``token``; return whatever can now be released, redacted."""
1619 self._pending += token
1620 if len(self._pending) <= STREAM_HOLD:
1621 return ""
1622 text = self._context + self._pending
1623 detections = self._redactor.detect(text)
1624 limit = len(text) - STREAM_HOLD
1625 cut = self._last_cut(text, detections, limit, r"\s+")
1626 if cut is None and len(self._pending) > STREAM_FORCE:
1627 cut = self._last_cut(text, detections, limit, r"[^\w@.%+\-]")
1628 if cut is None:
1629 cut = limit
1630 for found in detections:
1631 if found.start < cut < found.end:
1632 cut = found.end
1633 if cut is None:
1634 return ""
1635 return self._release(text, detections, cut)
1637 def _last_cut(
1638 self, text: str, detections: list[Detection], limit: int, boundary: str
1639 ) -> int | None:
1640 """The last position after ``boundary`` in the unreleased text, before
1641 ``limit``, that is outside every value found."""
1642 cut = None
1643 for gap in re.finditer(boundary, text[len(self._context) : limit]):
1644 position = len(self._context) + gap.end()
1645 if all(position <= d.start or position >= d.end for d in detections):
1646 cut = position
1647 return cut
1649 def flush(self) -> str:
1650 """Release everything held, redacted — the stream has ended."""
1651 if not self._pending:
1652 return ""
1653 text = self._context + self._pending
1654 return self._release(text, self._redactor.detect(text), len(text))
1656 def _release(self, text: str, detections: list[Detection], cut: int) -> str:
1657 released, _ = self._redactor.render(text, detections, len(self._context), cut)
1658 self._pending = text[cut:]
1659 self._context = text[:cut][-CONTEXT_WINDOW:]
1660 return released
1663# ─── Compatibility ────────────────────────────────────────────────────────────
1665_DEFAULT = Redactor()
1666_EVERY = Redactor(KINDS)
1669def redact(text: str) -> tuple[str, dict[str, int]]:
1670 """Redact the default kinds, with bare placeholders. See :class:`Redactor`."""
1671 return _DEFAULT.redact(text)
1674def filter_pii(text: str) -> str:
1675 """Redact the default kinds."""
1676 return _DEFAULT.redact(text)[0]
1679def detect_pii(text: str) -> bool:
1680 """True when ``text`` holds a value of a default kind — ``pii_detected``."""
1681 return bool(text) and bool(_DEFAULT.detect(text))
1684def detected_kinds(text: str) -> list[str]:
1685 """Every kind present in ``text``, default or not — ``pii_types``."""
1686 return _EVERY.kinds_in(text) if text else []