redact-intl 0.1.0__tar.gz
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.
- redact_intl-0.1.0/LICENSE +21 -0
- redact_intl-0.1.0/PKG-INFO +130 -0
- redact_intl-0.1.0/README.md +89 -0
- redact_intl-0.1.0/pyproject.toml +38 -0
- redact_intl-0.1.0/src/redact_intl/__init__.py +12 -0
- redact_intl-0.1.0/src/redact_intl/cli.py +51 -0
- redact_intl-0.1.0/src/redact_intl/core.py +151 -0
- redact_intl-0.1.0/src/redact_intl/countries/__init__.py +53 -0
- redact_intl-0.1.0/src/redact_intl/countries/br.py +34 -0
- redact_intl-0.1.0/src/redact_intl/countries/id.py +51 -0
- redact_intl-0.1.0/src/redact_intl/countries/in_.py +57 -0
- redact_intl-0.1.0/src/redact_intl/countries/pl.py +62 -0
- redact_intl-0.1.0/tests/test_core.py +171 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 alfathir27
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: redact-intl
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Detect and redact national identifiers (id, br, pl, in) plus emails and phone numbers
|
|
5
|
+
Project-URL: Homepage, https://github.com/alfathir27/redact-intl
|
|
6
|
+
Project-URL: Repository, https://github.com/alfathir27/redact-intl
|
|
7
|
+
Project-URL: Issues, https://github.com/alfathir27/redact-intl/issues
|
|
8
|
+
Author-email: alfathir27 <admin@alfathir.id>
|
|
9
|
+
License: MIT License
|
|
10
|
+
|
|
11
|
+
Copyright (c) 2026 alfathir27
|
|
12
|
+
|
|
13
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
14
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
15
|
+
in the Software without restriction, including without limitation the rights
|
|
16
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
17
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
18
|
+
furnished to do so, subject to the following conditions:
|
|
19
|
+
|
|
20
|
+
The above copyright notice and this permission notice shall be included in all
|
|
21
|
+
copies or substantial portions of the Software.
|
|
22
|
+
|
|
23
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
24
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
25
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
26
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
27
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
28
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
29
|
+
SOFTWARE.
|
|
30
|
+
License-File: LICENSE
|
|
31
|
+
Keywords: aadhaar,cpf,gdpr,logging,nik,pesel,pii,redact
|
|
32
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
33
|
+
Classifier: Operating System :: OS Independent
|
|
34
|
+
Classifier: Programming Language :: Python :: 3
|
|
35
|
+
Classifier: Topic :: Security
|
|
36
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
37
|
+
Requires-Python: >=3.9
|
|
38
|
+
Provides-Extra: dev
|
|
39
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
40
|
+
Description-Content-Type: text/markdown
|
|
41
|
+
|
|
42
|
+
# redact-intl
|
|
43
|
+
|
|
44
|
+
Detect and redact national identifiers, emails and phone numbers before records leave a
|
|
45
|
+
trust boundary — logs, CSV exports, analytics payloads. Zero runtime dependencies.
|
|
46
|
+
|
|
47
|
+
Python port of [`@alfathir27/redact-intl`](https://www.npmjs.com/package/@alfathir27/redact-intl);
|
|
48
|
+
the JS and Python packages share the same rule contract and the same test corpus.
|
|
49
|
+
|
|
50
|
+
## Install
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
pip install redact-intl
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Use
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
import redact_intl as r
|
|
60
|
+
|
|
61
|
+
r.mask("NIK 3171054401230001, CPF 529.982.247-25")
|
|
62
|
+
# 'NIK 3171********0001, CPF 529.***.***-25'
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Styles:
|
|
66
|
+
|
|
67
|
+
| style | output for a NIK |
|
|
68
|
+
|---|---|
|
|
69
|
+
| `partial` (default) | `3171********0001` |
|
|
70
|
+
| `full` | `[id]` |
|
|
71
|
+
| `hash` | `<id:a4234810>` |
|
|
72
|
+
|
|
73
|
+
Walk a payload:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
r.mask_object({"user": {"nik": "3171054401230001"}, "tags": ["529.982.247-25"]})
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Inspect instead of replace — every hit carries a validity verdict:
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
r.find("CPF 529.982.247-26")
|
|
83
|
+
# [{'kind': 'br', 'value': '529.982.247-26', 'start': 4, 'end': 21,
|
|
84
|
+
# 'valid': False, 'reason': 'checksum mismatch'}]
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Restrict the rules:
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
r.find(text, countries=["id"]) # only Indonesia
|
|
91
|
+
r.find(text, kinds=["email"]) # only emails
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## CLI
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
redact-intl access.log
|
|
98
|
+
redact-intl --style hash --countries id,br dump.csv
|
|
99
|
+
redact-intl --json access.log | jq '.[].kind'
|
|
100
|
+
redact-intl --list
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Countries
|
|
104
|
+
|
|
105
|
+
| code | identifier | check |
|
|
106
|
+
|---|---|---|
|
|
107
|
+
| `id` | NIK, 16 digits | province, birth date, serial |
|
|
108
|
+
| `br` | CPF, 11 digits | modulo-11 double check digit |
|
|
109
|
+
| `in` | Aadhaar, 12 digits | Verhoeff |
|
|
110
|
+
| `pl` | PESEL, 11 digits | weighted checksum, century offset |
|
|
111
|
+
|
|
112
|
+
Emails and phone numbers are always active and cannot be switched off per country.
|
|
113
|
+
|
|
114
|
+
## Adding a country
|
|
115
|
+
|
|
116
|
+
Copy `countries/id.py`, rename to your two-letter code, implement `PATTERNS`, `validate`
|
|
117
|
+
and `mask`, register it in `countries/__init__.py`. Run `pytest`. Rules are one file and
|
|
118
|
+
carry no dependency — see `CONTRIBUTING.md` in the repository.
|
|
119
|
+
|
|
120
|
+
## Guarantees and limits
|
|
121
|
+
|
|
122
|
+
- Detection is regex plus a per-country structural or checksum check. A string that
|
|
123
|
+
passes the check is treated as an identifier; a string that looks like one but fails
|
|
124
|
+
is still reported, with `valid: False`.
|
|
125
|
+
- Masking is stable per input: the same value always yields the same hash.
|
|
126
|
+
- Nothing is sent anywhere. No network, no telemetry.
|
|
127
|
+
|
|
128
|
+
## License
|
|
129
|
+
|
|
130
|
+
MIT
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# redact-intl
|
|
2
|
+
|
|
3
|
+
Detect and redact national identifiers, emails and phone numbers before records leave a
|
|
4
|
+
trust boundary — logs, CSV exports, analytics payloads. Zero runtime dependencies.
|
|
5
|
+
|
|
6
|
+
Python port of [`@alfathir27/redact-intl`](https://www.npmjs.com/package/@alfathir27/redact-intl);
|
|
7
|
+
the JS and Python packages share the same rule contract and the same test corpus.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install redact-intl
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Use
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
import redact_intl as r
|
|
19
|
+
|
|
20
|
+
r.mask("NIK 3171054401230001, CPF 529.982.247-25")
|
|
21
|
+
# 'NIK 3171********0001, CPF 529.***.***-25'
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Styles:
|
|
25
|
+
|
|
26
|
+
| style | output for a NIK |
|
|
27
|
+
|---|---|
|
|
28
|
+
| `partial` (default) | `3171********0001` |
|
|
29
|
+
| `full` | `[id]` |
|
|
30
|
+
| `hash` | `<id:a4234810>` |
|
|
31
|
+
|
|
32
|
+
Walk a payload:
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
r.mask_object({"user": {"nik": "3171054401230001"}, "tags": ["529.982.247-25"]})
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Inspect instead of replace — every hit carries a validity verdict:
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
r.find("CPF 529.982.247-26")
|
|
42
|
+
# [{'kind': 'br', 'value': '529.982.247-26', 'start': 4, 'end': 21,
|
|
43
|
+
# 'valid': False, 'reason': 'checksum mismatch'}]
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Restrict the rules:
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
r.find(text, countries=["id"]) # only Indonesia
|
|
50
|
+
r.find(text, kinds=["email"]) # only emails
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## CLI
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
redact-intl access.log
|
|
57
|
+
redact-intl --style hash --countries id,br dump.csv
|
|
58
|
+
redact-intl --json access.log | jq '.[].kind'
|
|
59
|
+
redact-intl --list
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Countries
|
|
63
|
+
|
|
64
|
+
| code | identifier | check |
|
|
65
|
+
|---|---|---|
|
|
66
|
+
| `id` | NIK, 16 digits | province, birth date, serial |
|
|
67
|
+
| `br` | CPF, 11 digits | modulo-11 double check digit |
|
|
68
|
+
| `in` | Aadhaar, 12 digits | Verhoeff |
|
|
69
|
+
| `pl` | PESEL, 11 digits | weighted checksum, century offset |
|
|
70
|
+
|
|
71
|
+
Emails and phone numbers are always active and cannot be switched off per country.
|
|
72
|
+
|
|
73
|
+
## Adding a country
|
|
74
|
+
|
|
75
|
+
Copy `countries/id.py`, rename to your two-letter code, implement `PATTERNS`, `validate`
|
|
76
|
+
and `mask`, register it in `countries/__init__.py`. Run `pytest`. Rules are one file and
|
|
77
|
+
carry no dependency — see `CONTRIBUTING.md` in the repository.
|
|
78
|
+
|
|
79
|
+
## Guarantees and limits
|
|
80
|
+
|
|
81
|
+
- Detection is regex plus a per-country structural or checksum check. A string that
|
|
82
|
+
passes the check is treated as an identifier; a string that looks like one but fails
|
|
83
|
+
is still reported, with `valid: False`.
|
|
84
|
+
- Masking is stable per input: the same value always yields the same hash.
|
|
85
|
+
- Nothing is sent anywhere. No network, no telemetry.
|
|
86
|
+
|
|
87
|
+
## License
|
|
88
|
+
|
|
89
|
+
MIT
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.24"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "redact-intl"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Detect and redact national identifiers (id, br, pl, in) plus emails and phone numbers"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { file = "LICENSE" }
|
|
12
|
+
authors = [{ name = "alfathir27", email = "admin@alfathir.id" }]
|
|
13
|
+
keywords = ["redact", "pii", "nik", "cpf", "pesel", "aadhaar", "gdpr", "logging"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"License :: OSI Approved :: MIT License",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
"Topic :: Security",
|
|
19
|
+
"Topic :: Software Development :: Libraries",
|
|
20
|
+
]
|
|
21
|
+
dependencies = []
|
|
22
|
+
|
|
23
|
+
[project.urls]
|
|
24
|
+
Homepage = "https://github.com/alfathir27/redact-intl"
|
|
25
|
+
Repository = "https://github.com/alfathir27/redact-intl"
|
|
26
|
+
Issues = "https://github.com/alfathir27/redact-intl/issues"
|
|
27
|
+
|
|
28
|
+
[project.scripts]
|
|
29
|
+
redact-intl = "redact_intl.cli:main"
|
|
30
|
+
|
|
31
|
+
[project.optional-dependencies]
|
|
32
|
+
dev = ["pytest>=8"]
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.wheel]
|
|
35
|
+
packages = ["src/redact_intl"]
|
|
36
|
+
|
|
37
|
+
[tool.pytest.ini_options]
|
|
38
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""redact-intl — strip national identifiers, emails and phone numbers before data leaves."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .core import STYLES, countries, digits, find, mask, mask_object
|
|
6
|
+
|
|
7
|
+
__all__ = ["find", "mask", "mask_object", "countries", "digits", "STYLES", "Country", "__version__"]
|
|
8
|
+
|
|
9
|
+
from .countries import Country # noqa: E402
|
|
10
|
+
from .countries import CODES, REGISTRY # noqa: E402,F401
|
|
11
|
+
|
|
12
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Command line interface: redact-intl [--style partial|full|hash] [-c code] [-k kind] [file]"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from .core import countries as list_countries
|
|
10
|
+
from .core import find, mask
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
14
|
+
parser = argparse.ArgumentParser(
|
|
15
|
+
prog="redact-intl",
|
|
16
|
+
description="Redact national identifiers, emails and phone numbers from text or stdin.",
|
|
17
|
+
)
|
|
18
|
+
parser.add_argument("file", nargs="?", help="file to read (default: stdin)")
|
|
19
|
+
parser.add_argument("-s", "--style", default="partial", choices=("partial", "full", "hash"), help="redaction style")
|
|
20
|
+
parser.add_argument("-c", "--countries", help="comma separated country codes, e.g. id,br")
|
|
21
|
+
parser.add_argument("-k", "--kinds", help="comma separated kinds, e.g. email,phone")
|
|
22
|
+
parser.add_argument("-l", "--list", action="store_true", help="list supported countries and exit")
|
|
23
|
+
parser.add_argument("-j", "--json", action="store_true", help="emit findings as JSON instead of text")
|
|
24
|
+
return parser
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def main(argv=None) -> int:
|
|
28
|
+
args = build_parser().parse_args(argv)
|
|
29
|
+
if args.list:
|
|
30
|
+
for country in list_countries():
|
|
31
|
+
print("%s\t%s" % (country["code"], country["name"]))
|
|
32
|
+
return 0
|
|
33
|
+
|
|
34
|
+
if args.file:
|
|
35
|
+
with open(args.file, "r", encoding="utf-8") as handle:
|
|
36
|
+
text = handle.read()
|
|
37
|
+
else:
|
|
38
|
+
text = sys.stdin.read()
|
|
39
|
+
|
|
40
|
+
codes = args.countries.split(",") if args.countries else None
|
|
41
|
+
kinds = args.kinds.split(",") if args.kinds else None
|
|
42
|
+
|
|
43
|
+
if args.json:
|
|
44
|
+
print(json.dumps(find(text, countries=codes, kinds=kinds), ensure_ascii=False, indent=2))
|
|
45
|
+
else:
|
|
46
|
+
sys.stdout.write(mask(text, style=args.style, countries=codes, kinds=kinds))
|
|
47
|
+
return 0
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
if __name__ == "__main__":
|
|
51
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""Detection core: country rules are pluggable, universal rules are built in."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import Any, Dict, Iterable, List, Optional
|
|
7
|
+
|
|
8
|
+
from .countries import CODES, REGISTRY
|
|
9
|
+
|
|
10
|
+
UNIVERSAL = [
|
|
11
|
+
("email", re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")),
|
|
12
|
+
(
|
|
13
|
+
"phone",
|
|
14
|
+
re.compile(
|
|
15
|
+
r"(?<![\d+])\+?\d{1,3}[ -]?\(?\d{1,4}\)?(?:[ -]?\d{2,4}){2,4}(?!\d)"
|
|
16
|
+
),
|
|
17
|
+
),
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
STYLES = ("partial", "full", "hash")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def digits(value: str) -> str:
|
|
24
|
+
return re.sub(r"\D", "", str(value))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _fnv1a(text: str) -> int:
|
|
28
|
+
h = 2166136261
|
|
29
|
+
for ch in text:
|
|
30
|
+
h ^= ord(ch)
|
|
31
|
+
h = (h * 16777619) & 0xFFFFFFFF
|
|
32
|
+
return h
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _hash(value: str, kind: str) -> str:
|
|
36
|
+
return "<%s:%x>" % (kind, _fnv1a(value))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def find(
|
|
40
|
+
text: str,
|
|
41
|
+
countries: Optional[Iterable[str]] = None,
|
|
42
|
+
kinds: Optional[Iterable[str]] = None,
|
|
43
|
+
) -> List[Dict[str, Any]]:
|
|
44
|
+
"""Return every identifier found in ``text``.
|
|
45
|
+
|
|
46
|
+
Earlier match wins, a country rule beats a generic one at the same offset,
|
|
47
|
+
the longer match wins inside the same priority, and nested matches are dropped.
|
|
48
|
+
"""
|
|
49
|
+
if not isinstance(text, str):
|
|
50
|
+
raise TypeError("text must be a string")
|
|
51
|
+
active = [c.lower() for c in countries] if countries else list(CODES)
|
|
52
|
+
wanted = set(kinds) if kinds else None
|
|
53
|
+
candidates: List[Dict[str, Any]] = []
|
|
54
|
+
|
|
55
|
+
def push(kind: str, pattern: "re.Pattern[str]", validator, priority: int = 1, order: int = 0) -> None:
|
|
56
|
+
if wanted is not None and kind not in wanted:
|
|
57
|
+
return
|
|
58
|
+
for m in pattern.finditer(text):
|
|
59
|
+
if not m.group(0):
|
|
60
|
+
continue
|
|
61
|
+
hit = {
|
|
62
|
+
"kind": kind,
|
|
63
|
+
"value": m.group(0),
|
|
64
|
+
"start": m.start(),
|
|
65
|
+
"end": m.end(),
|
|
66
|
+
"priority": priority,
|
|
67
|
+
"order": order,
|
|
68
|
+
}
|
|
69
|
+
if validator is not None:
|
|
70
|
+
hit.update(validator(m.group(0)))
|
|
71
|
+
candidates.append(hit)
|
|
72
|
+
|
|
73
|
+
for kind, pattern in UNIVERSAL:
|
|
74
|
+
push(kind, pattern, None, 1)
|
|
75
|
+
|
|
76
|
+
for index, code in enumerate(active):
|
|
77
|
+
country = REGISTRY.get(code)
|
|
78
|
+
if country is None:
|
|
79
|
+
raise ValueError("unknown country code: %s" % code)
|
|
80
|
+
for pattern in country.PATTERNS:
|
|
81
|
+
push(country.CODE, pattern, country.validate, 0, index)
|
|
82
|
+
|
|
83
|
+
candidates.sort(key=lambda c: (c["start"], c["priority"], -c["end"], c["order"]))
|
|
84
|
+
|
|
85
|
+
found: List[Dict[str, Any]] = []
|
|
86
|
+
boundary = -1
|
|
87
|
+
for candidate in candidates:
|
|
88
|
+
if candidate["start"] < boundary:
|
|
89
|
+
continue
|
|
90
|
+
boundary = candidate["end"]
|
|
91
|
+
found.append(candidate)
|
|
92
|
+
return found
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _replace(hit: Dict[str, Any], style: str) -> str:
|
|
96
|
+
if style == "full":
|
|
97
|
+
return "[%s]" % hit["kind"]
|
|
98
|
+
if style == "hash":
|
|
99
|
+
return _hash(hit["value"], hit["kind"])
|
|
100
|
+
country = REGISTRY.get(hit["kind"])
|
|
101
|
+
if country is not None:
|
|
102
|
+
return country.mask(hit["value"])
|
|
103
|
+
if hit["kind"] == "email":
|
|
104
|
+
user, domain = hit["value"].split("@", 1)
|
|
105
|
+
return "%s%s@%s" % (user[:2], "*" * max(1, len(user) - 2), domain)
|
|
106
|
+
d = digits(hit["value"])
|
|
107
|
+
return "%s%s%s" % (d[:3], "*" * max(0, len(d) - 5), d[-2:])
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def mask(
|
|
111
|
+
text: str,
|
|
112
|
+
style: str = "partial",
|
|
113
|
+
countries: Optional[Iterable[str]] = None,
|
|
114
|
+
kinds: Optional[Iterable[str]] = None,
|
|
115
|
+
) -> str:
|
|
116
|
+
"""Redact every identifier in ``text`` using one of: partial, full, hash."""
|
|
117
|
+
if style not in STYLES:
|
|
118
|
+
raise ValueError("unknown style: %s" % style)
|
|
119
|
+
out: List[str] = []
|
|
120
|
+
position = 0
|
|
121
|
+
for hit in find(text, countries=countries, kinds=kinds):
|
|
122
|
+
out.append(text[position:hit["start"]])
|
|
123
|
+
out.append(_replace(hit, style))
|
|
124
|
+
position = hit["end"]
|
|
125
|
+
out.append(text[position:])
|
|
126
|
+
return "".join(out)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def mask_object(value: Any, style: str = "partial", countries=None, kinds=None) -> Any:
|
|
130
|
+
"""Redact string values inside dicts/lists recursively; cycles become ``[cycle]``."""
|
|
131
|
+
seen: set = set()
|
|
132
|
+
|
|
133
|
+
def walk(node: Any) -> Any:
|
|
134
|
+
if isinstance(node, str):
|
|
135
|
+
return mask(node, style=style, countries=countries, kinds=kinds)
|
|
136
|
+
if isinstance(node, (list, tuple)):
|
|
137
|
+
return [walk(item) for item in node]
|
|
138
|
+
if isinstance(node, dict):
|
|
139
|
+
marker = id(node)
|
|
140
|
+
if marker in seen:
|
|
141
|
+
return "[cycle]"
|
|
142
|
+
seen.add(marker)
|
|
143
|
+
return {key: walk(item) for key, item in node.items()}
|
|
144
|
+
return node
|
|
145
|
+
|
|
146
|
+
return walk(value)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def countries() -> List[Dict[str, str]]:
|
|
150
|
+
"""Supported countries, e.g. ``[{"code": "br", "name": "Brazil"}]``."""
|
|
151
|
+
return [{"code": country.CODE, "name": country.NAME} for country in REGISTRY.values()]
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Country rule contract.
|
|
2
|
+
|
|
3
|
+
Drop a new module in this package, register it in ``REGISTRY`` and the rule is live.
|
|
4
|
+
A rule module exposes four attributes:
|
|
5
|
+
|
|
6
|
+
``CODE`` two-letter lowercase code, also used as the ``kind`` of a hit
|
|
7
|
+
``NAME`` human readable country name
|
|
8
|
+
``PATTERNS`` list of compiled patterns matching candidate identifiers
|
|
9
|
+
``validate`` ``str -> dict``; returns ``{"valid": bool, "reason": str?, "meta": dict?}``
|
|
10
|
+
``mask`` ``str -> str``; returns the partially redacted form
|
|
11
|
+
|
|
12
|
+
Keep ``validate`` honest: a checksum or structural check is what separates a real
|
|
13
|
+
identifier from any string of digits. See ``id.py`` for a full example.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from typing import Dict, List, Pattern
|
|
19
|
+
|
|
20
|
+
from . import br, id as id_rule, in_ as in_rule, pl
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Country:
|
|
24
|
+
CODE: str = "xx"
|
|
25
|
+
NAME: str = "Nowhere"
|
|
26
|
+
PATTERNS: List[Pattern[str]] = []
|
|
27
|
+
|
|
28
|
+
@staticmethod
|
|
29
|
+
def validate(value: str) -> Dict[str, object]:
|
|
30
|
+
return {"valid": False, "reason": "not implemented"}
|
|
31
|
+
|
|
32
|
+
@staticmethod
|
|
33
|
+
def mask(value: str) -> str:
|
|
34
|
+
return value
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _wrap(module, code, name, patterns, validate, mask):
|
|
38
|
+
return type(
|
|
39
|
+
"Country_%s" % code,
|
|
40
|
+
(Country,),
|
|
41
|
+
{"CODE": code, "NAME": name, "PATTERNS": patterns, "validate": staticmethod(validate), "mask": staticmethod(mask)},
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
REGISTRY = {
|
|
46
|
+
"br": _wrap(br, "br", "Brazil", br.PATTERNS, br.validate, br.mask),
|
|
47
|
+
"id": _wrap(id_rule, "id", "Indonesia", id_rule.PATTERNS, id_rule.validate, id_rule.mask),
|
|
48
|
+
"in": _wrap(in_rule, "in", "India", in_rule.PATTERNS, in_rule.validate, in_rule.mask),
|
|
49
|
+
"pl": _wrap(pl, "pl", "Poland", pl.PATTERNS, pl.validate, pl.mask),
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
# order matters when two country rules genuinely overlap (11-digit CPF and PESEL)
|
|
53
|
+
CODES = ["br", "id", "in", "pl"]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Brazil — CPF, 11 digits, modulo-11 double check digit. Usually written 000.000.000-00."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
PATTERNS = [re.compile(r"(?<!\d)\d{3}\.?\d{3}\.?\d{3}-?\d{2}(?!\d)")]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _check_digit(head, weights):
|
|
11
|
+
total = sum(int(char) * weights[i] for i, char in enumerate(head))
|
|
12
|
+
rest = total % 11
|
|
13
|
+
return 0 if rest < 2 else 11 - rest
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def validate(value):
|
|
17
|
+
n = re.sub(r"\D", "", str(value))
|
|
18
|
+
if len(n) != 11:
|
|
19
|
+
return {"valid": False, "reason": "must be 11 digits"}
|
|
20
|
+
if re.fullmatch(r"(\d)\1{10}", n):
|
|
21
|
+
return {"valid": False, "reason": "all digits identical"}
|
|
22
|
+
cpf = [int(char) for char in n]
|
|
23
|
+
first = _check_digit(cpf[:9], [10, 9, 8, 7, 6, 5, 4, 3, 2])
|
|
24
|
+
second = _check_digit(cpf[:10], [11, 10, 9, 8, 7, 6, 5, 4, 3, 2])
|
|
25
|
+
if cpf[9] != first or cpf[10] != second:
|
|
26
|
+
return {"valid": False, "reason": "checksum mismatch"}
|
|
27
|
+
return {"valid": True, "meta": {"region": "fiscal-%d" % cpf[8]}}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def mask(value):
|
|
31
|
+
n = re.sub(r"\D", "", str(value))
|
|
32
|
+
if len(n) < 11:
|
|
33
|
+
return n
|
|
34
|
+
return "%s.***.***-%s" % (n[:3], n[-2:])
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Indonesia — NIK (Nomor Induk Kependudukan), 16 digits.
|
|
2
|
+
|
|
3
|
+
Structure: 2 province + 2 regency + 2 district + 2 birth day (+40 for female) + 2 month
|
|
4
|
+
+ 2 year + 4 serial. There is no checksum; validity is structural.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
|
|
11
|
+
PATTERNS = [re.compile(r"(?<![\d.])(\d{16})(?![\d.])")]
|
|
12
|
+
|
|
13
|
+
PROVINCES = frozenset(
|
|
14
|
+
{
|
|
15
|
+
"11", "12", "13", "14", "15", "16", "17", "18", "19", "21",
|
|
16
|
+
"31", "32", "33", "34", "35", "36",
|
|
17
|
+
"51", "52", "53",
|
|
18
|
+
"61", "62", "63", "64", "65",
|
|
19
|
+
"71", "72", "73", "74", "75", "76",
|
|
20
|
+
"81", "82",
|
|
21
|
+
"91", "92", "93", "94",
|
|
22
|
+
}
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def validate(value):
|
|
27
|
+
n = re.sub(r"\D", "", str(value))
|
|
28
|
+
if len(n) != 16:
|
|
29
|
+
return {"valid": False, "reason": "must be 16 digits"}
|
|
30
|
+
province = n[:2]
|
|
31
|
+
if province not in PROVINCES:
|
|
32
|
+
return {"valid": False, "reason": "unknown province code %s" % province}
|
|
33
|
+
day = int(n[6:8])
|
|
34
|
+
female = day > 40
|
|
35
|
+
if female:
|
|
36
|
+
day -= 40
|
|
37
|
+
if not 1 <= day <= 31:
|
|
38
|
+
return {"valid": False, "reason": "birth day outside 01-31"}
|
|
39
|
+
month = int(n[8:10])
|
|
40
|
+
if not 1 <= month <= 12:
|
|
41
|
+
return {"valid": False, "reason": "month outside 01-12"}
|
|
42
|
+
if int(n[12:16]) == 0:
|
|
43
|
+
return {"valid": False, "reason": "serial 0000"}
|
|
44
|
+
return {"valid": True, "meta": {"sex": "F" if female else "M", "province": province}}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def mask(value):
|
|
48
|
+
n = str(value)
|
|
49
|
+
if len(n) < 16:
|
|
50
|
+
return n
|
|
51
|
+
return "%s%s%s" % (n[:4], "*" * 8, n[12:])
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""India — Aadhaar, 12 digits, Verhoeff check digit. Usually grouped 4-4-4."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
PATTERNS = [re.compile(r"(?<!\d)\d{4}\s?\d{4}\s?\d{4}(?!\d)")]
|
|
8
|
+
|
|
9
|
+
_D = (
|
|
10
|
+
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
|
|
11
|
+
(1, 2, 3, 4, 0, 6, 7, 8, 9, 5),
|
|
12
|
+
(2, 3, 4, 0, 1, 7, 8, 9, 5, 6),
|
|
13
|
+
(3, 4, 0, 1, 2, 8, 9, 5, 6, 7),
|
|
14
|
+
(4, 0, 1, 2, 3, 9, 5, 6, 7, 8),
|
|
15
|
+
(5, 9, 8, 7, 6, 0, 4, 3, 2, 1),
|
|
16
|
+
(6, 5, 9, 8, 7, 1, 0, 4, 3, 2),
|
|
17
|
+
(7, 6, 5, 9, 8, 2, 1, 0, 4, 3),
|
|
18
|
+
(8, 7, 6, 5, 9, 3, 2, 1, 0, 4),
|
|
19
|
+
(9, 8, 7, 6, 5, 4, 3, 2, 1, 0),
|
|
20
|
+
)
|
|
21
|
+
_P = (
|
|
22
|
+
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
|
|
23
|
+
(1, 5, 7, 6, 2, 8, 3, 0, 9, 4),
|
|
24
|
+
(5, 8, 0, 3, 7, 9, 6, 1, 4, 2),
|
|
25
|
+
(8, 9, 1, 6, 0, 4, 3, 5, 2, 7),
|
|
26
|
+
(9, 4, 5, 3, 1, 2, 6, 8, 7, 0),
|
|
27
|
+
(4, 2, 8, 6, 5, 7, 3, 9, 0, 1),
|
|
28
|
+
(2, 7, 9, 3, 8, 0, 6, 4, 1, 5),
|
|
29
|
+
(7, 0, 4, 6, 9, 1, 3, 2, 5, 8),
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _verhoeff(number: str) -> bool:
|
|
34
|
+
check = 0
|
|
35
|
+
for position, char in enumerate(reversed(number)):
|
|
36
|
+
check = _D[check][_P[position % 8][int(char)]]
|
|
37
|
+
return check == 0
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def validate(value):
|
|
41
|
+
n = re.sub(r"\D", "", str(value))
|
|
42
|
+
if len(n) != 12:
|
|
43
|
+
return {"valid": False, "reason": "must be 12 digits"}
|
|
44
|
+
if n[0] in "01":
|
|
45
|
+
return {"valid": False, "reason": "first digit must be 2-9"}
|
|
46
|
+
if re.fullmatch(r"(\d)\1{11}", n):
|
|
47
|
+
return {"valid": False, "reason": "all digits identical"}
|
|
48
|
+
if not _verhoeff(n):
|
|
49
|
+
return {"valid": False, "reason": "Verhoeff checksum mismatch"}
|
|
50
|
+
return {"valid": True, "meta": {}}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def mask(value):
|
|
54
|
+
n = re.sub(r"\D", "", str(value))
|
|
55
|
+
if len(n) < 12:
|
|
56
|
+
return n
|
|
57
|
+
return "XXXX XXXX %s" % n[-4:]
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Poland — PESEL, 11 digits.
|
|
2
|
+
|
|
3
|
+
Weights 1,3,7,9,1,3,7,9,1,3 on the first ten digits, check = (10 - sum % 10) % 10.
|
|
4
|
+
Digits 3-4 carry a century offset: +0 1900s, +20 2000s, +40 2100s, +60 2200s, +80 1800s.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
|
|
11
|
+
PATTERNS = [re.compile(r"(?<!\d)\d{11}(?!\d)")]
|
|
12
|
+
WEIGHTS = (1, 3, 7, 9, 1, 3, 7, 9, 1, 3)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _century(raw_month):
|
|
16
|
+
if 81 <= raw_month <= 92:
|
|
17
|
+
return 1800, 80
|
|
18
|
+
if 1 <= raw_month <= 12:
|
|
19
|
+
return 1900, 0
|
|
20
|
+
if 21 <= raw_month <= 32:
|
|
21
|
+
return 2000, 20
|
|
22
|
+
if 41 <= raw_month <= 52:
|
|
23
|
+
return 2100, 40
|
|
24
|
+
if 61 <= raw_month <= 72:
|
|
25
|
+
return 2200, 60
|
|
26
|
+
return None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def validate(value):
|
|
30
|
+
n = re.sub(r"\D", "", str(value))
|
|
31
|
+
if len(n) != 11:
|
|
32
|
+
return {"valid": False, "reason": "must be 11 digits"}
|
|
33
|
+
digits = [int(char) for char in n]
|
|
34
|
+
total = sum(weight * digit for weight, digit in zip(WEIGHTS, digits))
|
|
35
|
+
if (10 - total % 10) % 10 != digits[10]:
|
|
36
|
+
return {"valid": False, "reason": "checksum mismatch"}
|
|
37
|
+
raw_month = digits[2] * 10 + digits[3]
|
|
38
|
+
shift = _century(raw_month)
|
|
39
|
+
if shift is None:
|
|
40
|
+
return {"valid": False, "reason": "month offset not recognised"}
|
|
41
|
+
base, offset = shift
|
|
42
|
+
year = base + digits[0] * 10 + digits[1]
|
|
43
|
+
month = raw_month - offset
|
|
44
|
+
day = digits[4] * 10 + digits[5]
|
|
45
|
+
if not 1 <= day <= 31:
|
|
46
|
+
return {"valid": False, "reason": "day outside 01-31"}
|
|
47
|
+
if not 1 <= month <= 12:
|
|
48
|
+
return {"valid": False, "reason": "month outside 01-12"}
|
|
49
|
+
return {
|
|
50
|
+
"valid": True,
|
|
51
|
+
"meta": {
|
|
52
|
+
"sex": "F" if digits[9] % 2 == 0 else "M",
|
|
53
|
+
"born": "%04d-%02d-%02d" % (year, month, day),
|
|
54
|
+
},
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def mask(value):
|
|
59
|
+
n = str(value)
|
|
60
|
+
if len(n) < 11:
|
|
61
|
+
return n
|
|
62
|
+
return "%s%s%s" % (n[:2], "*" * 6, n[-3:])
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import subprocess
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
import redact_intl as r
|
|
8
|
+
|
|
9
|
+
NIK = "3171054401230001"
|
|
10
|
+
CPF = "529.982.247-25"
|
|
11
|
+
PESEL = "44051401359"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_countries_lists_four_rules():
|
|
15
|
+
codes = [c["code"] for c in r.countries()]
|
|
16
|
+
assert codes == ["br", "id", "in", "pl"]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_find_nik_reports_valid_structure():
|
|
20
|
+
hits = r.find("NIK %s terlampir" % NIK, countries=["id"])
|
|
21
|
+
assert len(hits) == 1
|
|
22
|
+
assert hits[0]["kind"] == "id"
|
|
23
|
+
assert hits[0]["valid"] is True
|
|
24
|
+
assert hits[0]["meta"]["sex"] == "F" # birth day 44 = day 4, female
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_invalid_nik_province_is_flagged():
|
|
28
|
+
hits = r.find("NIK 9971054401230001")
|
|
29
|
+
assert hits and hits[0]["valid"] is False
|
|
30
|
+
assert "province" in hits[0]["reason"]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_nik_with_zero_serial_is_invalid():
|
|
34
|
+
hits = r.find("NIK 3171054401230000")
|
|
35
|
+
assert hits and hits[0]["valid"] is False
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_cpf_checksum_accepted():
|
|
39
|
+
hits = r.find("CPF %s" % CPF, countries=["br"])
|
|
40
|
+
assert hits and hits[0]["kind"] == "br"
|
|
41
|
+
assert hits[0]["valid"] is True
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_cpf_wrong_check_digit_rejected():
|
|
45
|
+
hits = r.find("CPF 529.982.247-26", countries=["br"])
|
|
46
|
+
assert hits and hits[0]["valid"] is False
|
|
47
|
+
assert hits[0]["reason"] == "checksum mismatch"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def test_repeated_digits_cpf_rejected():
|
|
51
|
+
hits = r.find("CPF 111.111.111-11")
|
|
52
|
+
assert hits and hits[0]["valid"] is False
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_pesel_valid_and_decodes_birth_date():
|
|
56
|
+
hits = r.find("PESEL %s" % PESEL, countries=["pl"])
|
|
57
|
+
assert len(hits) == 1
|
|
58
|
+
assert hits[0]["meta"]["born"] == "1944-05-14"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_aadhaar_verhoeff_accepted():
|
|
62
|
+
valid = _aadhaar_with_check_digit("23456789012")
|
|
63
|
+
hits = r.find("Aadhaar %s" % valid)
|
|
64
|
+
assert hits and hits[0]["kind"] == "in"
|
|
65
|
+
assert hits[0]["valid"] is True
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_aadhaar_bad_check_digit_rejected():
|
|
69
|
+
valid = _aadhaar_with_check_digit("23456789012")
|
|
70
|
+
broken = valid[:-1] + str((int(valid[-1]) + 1) % 10)
|
|
71
|
+
hits = r.find("Aadhaar %s" % broken)
|
|
72
|
+
assert hits and hits[0]["valid"] is False
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_email_partial_mask_keeps_two_chars_and_domain():
|
|
76
|
+
assert r.mask("kirim ke budi.santoso@example.co.id") == "kirim ke bu**********@example.co.id"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_phone_detected():
|
|
80
|
+
kinds = [h["kind"] for h in r.find("hubungi +62 812 3456 7890")]
|
|
81
|
+
assert "phone" in kinds
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_full_style_replaces_with_kind():
|
|
85
|
+
assert r.mask("NIK %s" % NIK, style="full") == "NIK [id]"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def test_hash_style_is_deterministic_and_bracketed():
|
|
89
|
+
first = r.mask("NIK %s" % NIK, style="hash")
|
|
90
|
+
second = r.mask("NIK %s" % NIK, style="hash")
|
|
91
|
+
assert first == second
|
|
92
|
+
assert first.startswith("NIK <id:") and first.endswith(">")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def test_unknown_style_raises():
|
|
96
|
+
with pytest.raises(ValueError):
|
|
97
|
+
r.mask("x", style="blur")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_unknown_country_raises():
|
|
101
|
+
with pytest.raises(ValueError):
|
|
102
|
+
r.find("x", countries=["zz"])
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def test_country_filter_limits_detection():
|
|
106
|
+
assert r.find("CPF %s" % CPF, countries=["pl"]) == []
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def test_kind_filter_limits_detection():
|
|
110
|
+
assert r.find("NIK %s mail@example.com" % NIK, kinds=["email"])[0]["kind"] == "email"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def test_mask_object_walks_nested_structures():
|
|
114
|
+
payload = {"user": {"nik": NIK}, "tags": ["CPF %s" % CPF]}
|
|
115
|
+
out = r.mask_object(payload)
|
|
116
|
+
assert out["user"]["nik"] == "3171********0001"
|
|
117
|
+
assert out["tags"] == ["CPF 529.***.***-25"]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def test_mask_object_survives_cycles():
|
|
121
|
+
node = {"nik": NIK}
|
|
122
|
+
node["self"] = node
|
|
123
|
+
assert r.mask_object(node)["self"] == "[cycle]"
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def test_digits_helper_strips_separators():
|
|
127
|
+
assert r.digits("529.982.247-25") == "52998224725"
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def test_cli_text_mode_redacts_file(tmp_path):
|
|
131
|
+
target = tmp_path / "in.txt"
|
|
132
|
+
target.write_text("NIK %s" % NIK, encoding="utf-8")
|
|
133
|
+
out = subprocess.run(
|
|
134
|
+
[sys.executable, "-m", "redact_intl.cli", str(target)],
|
|
135
|
+
capture_output=True,
|
|
136
|
+
text=True,
|
|
137
|
+
check=True,
|
|
138
|
+
)
|
|
139
|
+
assert out.stdout == "NIK 3171********0001"
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def test_cli_json_mode_emits_findings(tmp_path):
|
|
143
|
+
target = tmp_path / "in.txt"
|
|
144
|
+
target.write_text("NIK %s" % NIK, encoding="utf-8")
|
|
145
|
+
out = subprocess.run(
|
|
146
|
+
[sys.executable, "-m", "redact_intl.cli", "--json", str(target)],
|
|
147
|
+
capture_output=True,
|
|
148
|
+
text=True,
|
|
149
|
+
check=True,
|
|
150
|
+
)
|
|
151
|
+
assert json.loads(out.stdout)[0]["kind"] == "id"
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def test_cli_lists_countries():
|
|
155
|
+
out = subprocess.run(
|
|
156
|
+
[sys.executable, "-m", "redact_intl.cli", "--list"],
|
|
157
|
+
capture_output=True,
|
|
158
|
+
text=True,
|
|
159
|
+
check=True,
|
|
160
|
+
)
|
|
161
|
+
assert "Indonesia" in out.stdout
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _aadhaar_with_check_digit(head: str) -> str:
|
|
165
|
+
"""Append the Verhoeff digit that makes the 12-digit Aadhaar valid."""
|
|
166
|
+
from redact_intl.countries import in_ as in_rule
|
|
167
|
+
|
|
168
|
+
for candidate in range(10):
|
|
169
|
+
if in_rule._verhoeff(head + str(candidate)):
|
|
170
|
+
return head + str(candidate)
|
|
171
|
+
raise AssertionError("no check digit found")
|