datadouble 0.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
datadouble/pii.py ADDED
@@ -0,0 +1,109 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Detectors for personal data that may have survived anonymization.
5
+
6
+ The PII scan reads text values from a restored golden image and flags any that
7
+ look like personal data. Values in reserved example domains and documentation
8
+ ranges, which the anonymizer generates, are not flagged. A spec can allow
9
+ values on purpose with ``LIKE`` patterns per column.
10
+ """
11
+
12
+ import re
13
+ from collections.abc import Iterable
14
+ from enum import StrEnum
15
+
16
+
17
+ class Detector(StrEnum):
18
+ """Kinds of personal data the scan looks for."""
19
+
20
+ EMAIL = "email"
21
+ PAYMENT_CARD = "payment-card"
22
+ US_SSN = "us-ssn"
23
+ PHONE = "phone"
24
+
25
+
26
+ _EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+)")
27
+ _RESERVED_DOMAINS = ("example.com", "example.net", "example.org")
28
+ _RESERVED_SUFFIXES = (".example", ".test", ".invalid", ".localhost")
29
+ _CARD = re.compile(
30
+ r"(?<![\d-])(?:\d{13,19}|\d{4}([ -])\d{4}\1\d{4}\1\d{4}(?:\1\d{3})?|\d{4}([ -])\d{6}\2\d{5})"
31
+ r"(?![\d-])"
32
+ )
33
+ _SSN = re.compile(r"(?<!\d)(\d{3})-(\d{2})-(\d{4})(?!\d)")
34
+ _PHONE = re.compile(
35
+ r"(?<![\w+])(?:\+\d{1,3}[ .-]?)?(?:\(\d{3}\)\s?|\d{3}[ .-])\d{3}[ .-]\d{4}(?!\d)"
36
+ )
37
+ _FICTIONAL_PHONE = re.compile(r"555[ .-]01\d\d$")
38
+ _LUHN_CARRY = 9
39
+ _SSN_INVALID_AREA = ("000", "666")
40
+
41
+
42
+ def _reserved_domain(domain: str) -> bool:
43
+ domain = domain.lower()
44
+ return (
45
+ domain in _RESERVED_DOMAINS
46
+ or any(domain.endswith("." + reserved) for reserved in _RESERVED_DOMAINS)
47
+ or domain.endswith(_RESERVED_SUFFIXES)
48
+ )
49
+
50
+
51
+ def _luhn(digits: str) -> bool:
52
+ total = 0
53
+ for index, char in enumerate(reversed(digits)):
54
+ digit = int(char)
55
+ if index % 2 == 1:
56
+ digit *= 2
57
+ if digit > _LUHN_CARRY:
58
+ digit -= _LUHN_CARRY
59
+ total += digit
60
+ return total % 10 == 0
61
+
62
+
63
+ def _card(match: str) -> bool:
64
+ digits = re.sub(r"[ -]", "", match)
65
+ return len(set(digits)) > 1 and _luhn(digits)
66
+
67
+
68
+ def _ssn(area: str, group: str, serial: str) -> bool:
69
+ return (
70
+ area not in _SSN_INVALID_AREA
71
+ and not area.startswith("9")
72
+ and group != "00"
73
+ and serial != "0000"
74
+ )
75
+
76
+
77
+ def detect(value: str) -> tuple[Detector, ...]:
78
+ """Every kind of personal data ``value`` appears to contain."""
79
+ found: list[Detector] = []
80
+ if any(not _reserved_domain(m[1]) for m in _EMAIL.finditer(value)):
81
+ found.append(Detector.EMAIL)
82
+ if any(_card(m[0]) for m in _CARD.finditer(value)):
83
+ found.append(Detector.PAYMENT_CARD)
84
+ if any(_ssn(*m.groups()) for m in _SSN.finditer(value)):
85
+ found.append(Detector.US_SSN)
86
+ if any(not _FICTIONAL_PHONE.search(m[0]) for m in _PHONE.finditer(value)):
87
+ found.append(Detector.PHONE)
88
+ return tuple(found)
89
+
90
+
91
+ def like_pattern(pattern: str) -> re.Pattern[str]:
92
+ r"""Compile a SQL ``LIKE`` pattern (``%``, ``_``, ``\`` escapes) to a regex."""
93
+ out: list[str] = []
94
+ chars = iter(pattern)
95
+ for char in chars:
96
+ if char == "\\":
97
+ out.append(re.escape(next(chars, "\\")))
98
+ elif char == "%":
99
+ out.append(".*")
100
+ elif char == "_":
101
+ out.append(".")
102
+ else:
103
+ out.append(re.escape(char))
104
+ return re.compile("".join(out), re.DOTALL)
105
+
106
+
107
+ def allowed(value: str, patterns: Iterable[re.Pattern[str]]) -> bool:
108
+ """Whether ``value`` matches one of a column's allow patterns."""
109
+ return any(pattern.fullmatch(value) for pattern in patterns)