lumoz-utils 0.1.0__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.
- lumoz_utils/__init__.py +1 -0
- lumoz_utils/redaction/__init__.py +20 -0
- lumoz_utils/redaction/budget.py +67 -0
- lumoz_utils/redaction/config.py +172 -0
- lumoz_utils/redaction/credentials.py +86 -0
- lumoz_utils/redaction/custom.py +112 -0
- lumoz_utils/redaction/data/public_suffix_list.dat +16884 -0
- lumoz_utils/redaction/otlp.py +262 -0
- lumoz_utils/redaction/recognizers.py +660 -0
- lumoz_utils/redaction/redactor.py +640 -0
- lumoz_utils/redaction/serializer.py +478 -0
- lumoz_utils-0.1.0.dist-info/METADATA +128 -0
- lumoz_utils-0.1.0.dist-info/RECORD +15 -0
- lumoz_utils-0.1.0.dist-info/WHEEL +5 -0
- lumoz_utils-0.1.0.dist-info/top_level.txt +1 -0
lumoz_utils/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Shared Python utilities for Lumoz."""
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Shared span redaction library."""
|
|
2
|
+
from lumoz_utils.redaction.budget import Budget
|
|
3
|
+
from lumoz_utils.redaction.config import REASON_CODES, ConfigError, Policy, build_policy
|
|
4
|
+
from lumoz_utils.redaction.custom import recognizer_from_dict
|
|
5
|
+
from lumoz_utils.redaction.redactor import Redactor, TextAnalysis, ValueRedaction
|
|
6
|
+
from lumoz_utils.redaction.serializer import SCHEMA_VERSION, metadata_to_json
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"REASON_CODES",
|
|
10
|
+
"SCHEMA_VERSION",
|
|
11
|
+
"Budget",
|
|
12
|
+
"ConfigError",
|
|
13
|
+
"Policy",
|
|
14
|
+
"Redactor",
|
|
15
|
+
"TextAnalysis",
|
|
16
|
+
"ValueRedaction",
|
|
17
|
+
"build_policy",
|
|
18
|
+
"recognizer_from_dict",
|
|
19
|
+
"metadata_to_json",
|
|
20
|
+
]
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Request budget for redaction scans."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class Budget:
|
|
6
|
+
"""Tracks scan work for one request."""
|
|
7
|
+
|
|
8
|
+
def __init__(
|
|
9
|
+
self,
|
|
10
|
+
*,
|
|
11
|
+
field_bytes: int = 64 * 1024,
|
|
12
|
+
request_bytes: int = 2 * 1024 * 1024,
|
|
13
|
+
max_depth: int = 16,
|
|
14
|
+
) -> None:
|
|
15
|
+
if not isinstance(field_bytes, int) or isinstance(field_bytes, bool):
|
|
16
|
+
raise TypeError("field_bytes must be a positive integer")
|
|
17
|
+
if not isinstance(request_bytes, int) or isinstance(request_bytes, bool):
|
|
18
|
+
raise TypeError("request_bytes must be a positive integer")
|
|
19
|
+
if not isinstance(max_depth, int) or isinstance(max_depth, bool):
|
|
20
|
+
raise TypeError("max_depth must be a positive integer")
|
|
21
|
+
if field_bytes <= 0:
|
|
22
|
+
raise ValueError("field_bytes must be positive")
|
|
23
|
+
if request_bytes <= 0:
|
|
24
|
+
raise ValueError("request_bytes must be positive")
|
|
25
|
+
if max_depth <= 0:
|
|
26
|
+
raise ValueError("max_depth must be positive")
|
|
27
|
+
self._field_bytes = field_bytes
|
|
28
|
+
self._request_bytes = request_bytes
|
|
29
|
+
self._max_depth = max_depth
|
|
30
|
+
self._remaining = request_bytes
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def field_bytes(self) -> int:
|
|
34
|
+
return self._field_bytes
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def request_bytes(self) -> int:
|
|
38
|
+
return self._request_bytes
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def max_depth(self) -> int:
|
|
42
|
+
return self._max_depth
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def remaining_bytes(self) -> int:
|
|
46
|
+
return self._remaining
|
|
47
|
+
|
|
48
|
+
def try_consume(self, nbytes: int) -> bool:
|
|
49
|
+
"""Reserve nbytes for the scan of one value.
|
|
50
|
+
|
|
51
|
+
Returns True and deducts only when nbytes <= field_bytes and nbytes <= remaining_bytes.
|
|
52
|
+
Zero is a no-op returning True. Negative raises ValueError. Non-int/bool raises TypeError.
|
|
53
|
+
"""
|
|
54
|
+
if isinstance(nbytes, bool):
|
|
55
|
+
raise TypeError("nbytes must be a non-negative integer, not bool")
|
|
56
|
+
if not isinstance(nbytes, int):
|
|
57
|
+
raise TypeError("nbytes must be a non-negative integer")
|
|
58
|
+
if nbytes < 0:
|
|
59
|
+
raise ValueError("nbytes must be non-negative")
|
|
60
|
+
if nbytes == 0:
|
|
61
|
+
return True
|
|
62
|
+
if nbytes > self._field_bytes:
|
|
63
|
+
return False
|
|
64
|
+
if nbytes > self._remaining:
|
|
65
|
+
return False
|
|
66
|
+
self._remaining -= nbytes
|
|
67
|
+
return True
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""Policy configuration for the redaction library."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
# Payment and identity identifier entity types.
|
|
8
|
+
_IDENTIFIER_ENTITIES = (
|
|
9
|
+
"CREDIT_CARD",
|
|
10
|
+
"CRYPTO",
|
|
11
|
+
"IBAN_CODE",
|
|
12
|
+
"US_BANK_NUMBER",
|
|
13
|
+
"US_DRIVER_LICENSE",
|
|
14
|
+
"US_ITIN",
|
|
15
|
+
"US_PASSPORT",
|
|
16
|
+
"US_SSN",
|
|
17
|
+
"IN_GSTIN",
|
|
18
|
+
"IN_PAN",
|
|
19
|
+
"IN_PASSPORT",
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
SUPPORTED_ENTITIES: frozenset[str] = frozenset(
|
|
23
|
+
("EMAIL_ADDRESS", "PHONE_NUMBER", "IP_ADDRESS") + _IDENTIFIER_ENTITIES + ("SECRET",)
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
DEFAULT_ENTITIES: tuple[str, ...] = (
|
|
27
|
+
"EMAIL_ADDRESS",
|
|
28
|
+
"PHONE_NUMBER",
|
|
29
|
+
"IP_ADDRESS",
|
|
30
|
+
) + _IDENTIFIER_ENTITIES + ("SECRET",)
|
|
31
|
+
|
|
32
|
+
_KNOWN_KEYS = frozenset({"entities", "min_score", "action", "recognizers"})
|
|
33
|
+
|
|
34
|
+
# How a detected value is replaced. "mask" writes [REDACTED:<ENTITY>]; "hash"
|
|
35
|
+
# writes [REDACTED:<ENTITY>:<code>], a keyed hash that is the same for the same
|
|
36
|
+
# value and key. SECRET matches are always masked.
|
|
37
|
+
ACTIONS: tuple[str, ...] = ("mask", "hash")
|
|
38
|
+
|
|
39
|
+
# Reason codes the core layer records. Each is defined once here; the
|
|
40
|
+
# redactor emits these names and REASON_CODES lists them. The span layer adds
|
|
41
|
+
# its own codes.
|
|
42
|
+
CREDENTIAL_KEY = "credential_key"
|
|
43
|
+
SENSITIVE_KEY = "sensitive_key"
|
|
44
|
+
FIELD_BUDGET_EXCEEDED = "field_budget_exceeded"
|
|
45
|
+
REQUEST_BUDGET_EXCEEDED = "request_budget_exceeded"
|
|
46
|
+
INVALID_TEXT = "invalid_text"
|
|
47
|
+
INVALID_NUMBER = "invalid_number"
|
|
48
|
+
DEPTH_EXCEEDED = "depth_exceeded"
|
|
49
|
+
STRUCTURE_TOO_LARGE = "structure_too_large"
|
|
50
|
+
DETECTION_FAILED = "detection_failed"
|
|
51
|
+
ANONYMIZATION_FAILED = "anonymization_failed"
|
|
52
|
+
|
|
53
|
+
REASON_CODES: tuple[str, ...] = (
|
|
54
|
+
CREDENTIAL_KEY,
|
|
55
|
+
SENSITIVE_KEY,
|
|
56
|
+
FIELD_BUDGET_EXCEEDED,
|
|
57
|
+
REQUEST_BUDGET_EXCEEDED,
|
|
58
|
+
INVALID_TEXT,
|
|
59
|
+
INVALID_NUMBER,
|
|
60
|
+
DEPTH_EXCEEDED,
|
|
61
|
+
STRUCTURE_TOO_LARGE,
|
|
62
|
+
DETECTION_FAILED,
|
|
63
|
+
ANONYMIZATION_FAILED,
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class ConfigError(ValueError):
|
|
68
|
+
"""Raised when configuration is invalid."""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _validate_policy_fields(
|
|
72
|
+
version: int,
|
|
73
|
+
entities: tuple[str, ...],
|
|
74
|
+
min_score: float,
|
|
75
|
+
action: str = "mask",
|
|
76
|
+
) -> None:
|
|
77
|
+
"""Validate all policy fields; raise ConfigError on any violation."""
|
|
78
|
+
if isinstance(version, bool) or not isinstance(version, int) or version != 1:
|
|
79
|
+
raise ConfigError(f"unsupported policy version: {version!r}")
|
|
80
|
+
if not isinstance(entities, tuple) or len(entities) == 0:
|
|
81
|
+
raise ConfigError("entities must be a non-empty list")
|
|
82
|
+
for e in entities:
|
|
83
|
+
if not isinstance(e, str) or e not in SUPPORTED_ENTITIES:
|
|
84
|
+
raise ConfigError(f"entities contains unsupported type: {e!r}")
|
|
85
|
+
if len(entities) != len(set(entities)):
|
|
86
|
+
raise ConfigError("entities contains duplicate entries")
|
|
87
|
+
if "SECRET" not in entities:
|
|
88
|
+
raise ConfigError("entities must include 'SECRET'")
|
|
89
|
+
if isinstance(min_score, bool) or not isinstance(min_score, float):
|
|
90
|
+
raise ConfigError("min_score must be a number between 0 and 1")
|
|
91
|
+
if not (0.0 <= min_score <= 1.0):
|
|
92
|
+
raise ConfigError("min_score must be between 0 and 1")
|
|
93
|
+
if not isinstance(action, str) or action not in ACTIONS:
|
|
94
|
+
raise ConfigError("action must be 'mask' or 'hash'")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass(frozen=True)
|
|
98
|
+
class Policy:
|
|
99
|
+
"""Immutable detection policy for the core layer."""
|
|
100
|
+
|
|
101
|
+
version: int
|
|
102
|
+
entities: tuple[str, ...]
|
|
103
|
+
min_score: float
|
|
104
|
+
action: str = "mask"
|
|
105
|
+
# Caller-defined recognizers: Presidio PatternRecognizer objects.
|
|
106
|
+
recognizers: tuple = ()
|
|
107
|
+
|
|
108
|
+
def __post_init__(self) -> None:
|
|
109
|
+
_validate_policy_fields(self.version, self.entities, self.min_score, self.action)
|
|
110
|
+
from lumoz_utils.redaction.custom import validate_recognizers
|
|
111
|
+
|
|
112
|
+
# Keep private copies, so the caller's objects can be changed without effect.
|
|
113
|
+
object.__setattr__(self, "recognizers", validate_recognizers(self.recognizers))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def build_policy(config: dict[str, Any] | None) -> Policy:
|
|
117
|
+
"""Validate config and return a Policy. Raises ConfigError on invalid input."""
|
|
118
|
+
if config is None:
|
|
119
|
+
config = {}
|
|
120
|
+
|
|
121
|
+
if not isinstance(config, dict):
|
|
122
|
+
raise ConfigError("config must be a dict")
|
|
123
|
+
|
|
124
|
+
# Reject unknown keys — report all offenders in sorted order (by str to handle mixed types).
|
|
125
|
+
unknown = set(config) - _KNOWN_KEYS
|
|
126
|
+
if unknown:
|
|
127
|
+
keys = ", ".join(sorted(repr(k) for k in unknown))
|
|
128
|
+
raise ConfigError(f"unknown config key: {keys}")
|
|
129
|
+
|
|
130
|
+
# entities
|
|
131
|
+
if "entities" in config:
|
|
132
|
+
entities_val = config["entities"]
|
|
133
|
+
if not isinstance(entities_val, (list, tuple)) or not entities_val:
|
|
134
|
+
raise ConfigError("entities must be a non-empty list")
|
|
135
|
+
entities: tuple[str, ...] = tuple(entities_val)
|
|
136
|
+
for e in entities:
|
|
137
|
+
if not isinstance(e, str):
|
|
138
|
+
raise ConfigError(f"entities contains unsupported type: {e!r}")
|
|
139
|
+
if e not in SUPPORTED_ENTITIES:
|
|
140
|
+
raise ConfigError(f"entities contains unsupported type: {e!r}")
|
|
141
|
+
if len(entities) != len(set(entities)):
|
|
142
|
+
raise ConfigError("entities contains duplicate entries")
|
|
143
|
+
if "SECRET" not in entities:
|
|
144
|
+
raise ConfigError("entities must include 'SECRET'")
|
|
145
|
+
else:
|
|
146
|
+
entities = tuple(DEFAULT_ENTITIES)
|
|
147
|
+
|
|
148
|
+
# min_score — check range before float() to avoid OverflowError on huge ints
|
|
149
|
+
if "min_score" in config:
|
|
150
|
+
min_score = config["min_score"]
|
|
151
|
+
if isinstance(min_score, bool) or not isinstance(min_score, (int, float)):
|
|
152
|
+
raise ConfigError("min_score must be a number between 0 and 1")
|
|
153
|
+
if not (0 <= min_score <= 1):
|
|
154
|
+
raise ConfigError("min_score must be between 0 and 1")
|
|
155
|
+
min_score = float(min_score)
|
|
156
|
+
else:
|
|
157
|
+
min_score = 0.5
|
|
158
|
+
|
|
159
|
+
action = config.get("action", "mask")
|
|
160
|
+
if not isinstance(action, str) or action not in ACTIONS:
|
|
161
|
+
raise ConfigError("action must be 'mask' or 'hash'")
|
|
162
|
+
|
|
163
|
+
recognizers = config.get("recognizers", ())
|
|
164
|
+
if not isinstance(recognizers, (list, tuple)):
|
|
165
|
+
raise ConfigError("recognizers must be a list")
|
|
166
|
+
from lumoz_utils.redaction.custom import recognizer_from_dict
|
|
167
|
+
|
|
168
|
+
recognizers = tuple(r if not isinstance(r, dict) else recognizer_from_dict(r) for r in recognizers)
|
|
169
|
+
|
|
170
|
+
return Policy(
|
|
171
|
+
version=1, entities=entities, min_score=min_score, action=action, recognizers=recognizers
|
|
172
|
+
)
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Credential pattern recognizer for the redaction library."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
# Single-line credential patterns.
|
|
8
|
+
# Bearer branch: scheme is case-insensitive (RFC 9110 §11.1); trailing
|
|
9
|
+
# sentence punctuation excluded by requiring the last character to be drawn
|
|
10
|
+
# from the token charset without '.'.
|
|
11
|
+
# JWT middle (claims) segment requires only 3 chars to handle minimal payloads
|
|
12
|
+
# such as base64url({}).
|
|
13
|
+
_SINGLE_LINE_RE = re.compile(
|
|
14
|
+
r"\bsk-[A-Za-z0-9_-]{20,}"
|
|
15
|
+
r"|\bAKIA[0-9A-Z]{16}\b"
|
|
16
|
+
r"|\bgh[pousr]_[A-Za-z0-9]{36,}"
|
|
17
|
+
r"|\bxox[abprs]-[A-Za-z0-9-]{10,}"
|
|
18
|
+
r"|\bAIza[0-9A-Za-z_-]{35}"
|
|
19
|
+
r"|\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{3,}\.[A-Za-z0-9_-]{8,}"
|
|
20
|
+
r"|\b(?i:Bearer)\s+[A-Za-z0-9._~+/=-]{19,}[A-Za-z0-9_~+/=-]"
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
# PEM private-key block. Label may be empty or qualified (e.g. "RSA ").
|
|
24
|
+
# First alternative finds a matching footer that is on its own line: only
|
|
25
|
+
# spaces/tabs may surround it (YAML indentation), followed by a line ending
|
|
26
|
+
# (LF or CRLF) or end of text. This prevents a quoted footer, or a footer
|
|
27
|
+
# followed by prose on the same line, from terminating the match early.
|
|
28
|
+
# Second alternative runs to end of text when no such footer is found.
|
|
29
|
+
# The pattern is split so no single source line reproduces a full PEM delimiter.
|
|
30
|
+
_PEM_PRIVATE_KEY_RE = re.compile(
|
|
31
|
+
r"-----BEGIN ([A-Z ]*?)"
|
|
32
|
+
r"PRIVATE KEY-----"
|
|
33
|
+
r"(?:[\s\S]*?[\r\n][ \t]*-----END \1"
|
|
34
|
+
r"PRIVATE KEY-----(?=[ \t]*(?:\r?\n|\Z))|[\s\S]*)"
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class _CredentialRecognizer:
|
|
39
|
+
"""Presidio-compatible recognizer for the SECRET entity type."""
|
|
40
|
+
|
|
41
|
+
name = "CredentialRecognizer"
|
|
42
|
+
_PATTERN_NAMES = ("SECRET (Single-line)", "SECRET (PEM private key)")
|
|
43
|
+
supported_entities = ("SECRET",)
|
|
44
|
+
is_loaded = True
|
|
45
|
+
|
|
46
|
+
def load(self) -> None:
|
|
47
|
+
self.is_loaded = True
|
|
48
|
+
|
|
49
|
+
def analyze(
|
|
50
|
+
self, *, text: str, entities: list[str], nlp_artifacts: Any = None
|
|
51
|
+
) -> list[Any]:
|
|
52
|
+
if "SECRET" not in entities:
|
|
53
|
+
return []
|
|
54
|
+
|
|
55
|
+
from presidio_analyzer import AnalysisExplanation, RecognizerResult
|
|
56
|
+
|
|
57
|
+
results: list[Any] = []
|
|
58
|
+
seen: set[tuple[int, int]] = set()
|
|
59
|
+
|
|
60
|
+
for m in _SINGLE_LINE_RE.finditer(text):
|
|
61
|
+
key = (m.start(), m.end())
|
|
62
|
+
if key not in seen:
|
|
63
|
+
seen.add(key)
|
|
64
|
+
results.append(RecognizerResult(
|
|
65
|
+
"SECRET", m.start(), m.end(), 1.0,
|
|
66
|
+
analysis_explanation=AnalysisExplanation(
|
|
67
|
+
self.name, 1.0,
|
|
68
|
+
pattern_name=self._PATTERN_NAMES[0],
|
|
69
|
+
),
|
|
70
|
+
recognition_metadata={"recognizer_name": self.name},
|
|
71
|
+
))
|
|
72
|
+
|
|
73
|
+
for m in _PEM_PRIVATE_KEY_RE.finditer(text):
|
|
74
|
+
key = (m.start(), m.end())
|
|
75
|
+
if key not in seen:
|
|
76
|
+
seen.add(key)
|
|
77
|
+
results.append(RecognizerResult(
|
|
78
|
+
"SECRET", m.start(), m.end(), 1.0,
|
|
79
|
+
analysis_explanation=AnalysisExplanation(
|
|
80
|
+
self.name, 1.0,
|
|
81
|
+
pattern_name=self._PATTERN_NAMES[1],
|
|
82
|
+
),
|
|
83
|
+
recognition_metadata={"recognizer_name": self.name},
|
|
84
|
+
))
|
|
85
|
+
|
|
86
|
+
return results
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Caller-defined recognizers, using Presidio's PatternRecognizer as-is.
|
|
2
|
+
|
|
3
|
+
A caller passes Presidio PatternRecognizer objects, or dicts in Presidio's
|
|
4
|
+
recognizer format that recognizer_from_dict turns into them. The library only
|
|
5
|
+
checks what it cannot support without an NLP engine, and that names and entity
|
|
6
|
+
types do not clash with the built-in ones.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from lumoz_utils.redaction.config import SUPPORTED_ENTITIES, ConfigError
|
|
15
|
+
|
|
16
|
+
ENTITY_NAME = re.compile(r"[A-Z][A-Z0-9_]{0,63}")
|
|
17
|
+
_RESERVED_ENTITIES = frozenset(SUPPORTED_ENTITIES) | {"VALUE"}
|
|
18
|
+
_DICT_KEYS = frozenset({"name", "supported_entity", "supported_entities", "patterns", "deny_list",
|
|
19
|
+
"deny_list_score", "supported_language"})
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def recognizer_from_dict(spec: Any) -> Any:
|
|
23
|
+
"""Build a Presidio PatternRecognizer from a Presidio-style recognizer dict.
|
|
24
|
+
|
|
25
|
+
Accepts the keys that work without an NLP engine. Context words need NLP,
|
|
26
|
+
so they are rejected rather than silently ignored.
|
|
27
|
+
"""
|
|
28
|
+
from presidio_analyzer import PatternRecognizer
|
|
29
|
+
|
|
30
|
+
if not isinstance(spec, dict):
|
|
31
|
+
raise ConfigError("each recognizer must be a mapping")
|
|
32
|
+
unknown = set(spec) - _DICT_KEYS
|
|
33
|
+
if unknown:
|
|
34
|
+
keys = ", ".join(sorted(repr(k) for k in unknown))
|
|
35
|
+
raise ConfigError(f"recognizer {spec.get('name')!r}: unsupported key(s) {keys}")
|
|
36
|
+
try:
|
|
37
|
+
recognizer = PatternRecognizer.from_dict(spec)
|
|
38
|
+
except (ValueError, TypeError, KeyError) as e:
|
|
39
|
+
raise ConfigError(f"recognizer {spec.get('name')!r}: {e}") from None
|
|
40
|
+
check_recognizer(recognizer)
|
|
41
|
+
return recognizer
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def check_recognizer(recognizer: Any) -> None:
|
|
45
|
+
from presidio_analyzer import PatternRecognizer
|
|
46
|
+
|
|
47
|
+
if not isinstance(recognizer, PatternRecognizer):
|
|
48
|
+
raise ConfigError("recognizers must be Presidio PatternRecognizer objects")
|
|
49
|
+
name = recognizer.name
|
|
50
|
+
if recognizer.context:
|
|
51
|
+
raise ConfigError(f"recognizer {name!r}: context words need an NLP engine and are not supported")
|
|
52
|
+
if recognizer.supported_language != "en":
|
|
53
|
+
raise ConfigError(f"recognizer {name!r}: supported_language must be 'en'")
|
|
54
|
+
entity = recognizer.supported_entities[0]
|
|
55
|
+
if not ENTITY_NAME.fullmatch(entity):
|
|
56
|
+
raise ConfigError(
|
|
57
|
+
f"recognizer {name!r}: entity must be upper case letters, digits and underscores"
|
|
58
|
+
)
|
|
59
|
+
if entity in _RESERVED_ENTITIES:
|
|
60
|
+
raise ConfigError(f"recognizer {name!r}: entity {entity!r} is built in")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _snapshot(recognizer: Any) -> Any:
|
|
64
|
+
"""A private copy, so later changes to the caller's object cannot change detection.
|
|
65
|
+
|
|
66
|
+
Deny-list terms are ordered longest first: Presidio joins them into one
|
|
67
|
+
alternation, where the first term that matches wins, so a shorter term
|
|
68
|
+
would otherwise cut a longer one short ("ACME" inside "ACME-US").
|
|
69
|
+
"""
|
|
70
|
+
from presidio_analyzer import PatternRecognizer
|
|
71
|
+
|
|
72
|
+
spec = recognizer.to_dict()
|
|
73
|
+
deny_list = list(recognizer.deny_list or [])
|
|
74
|
+
patterns = spec.get("patterns") or []
|
|
75
|
+
if deny_list:
|
|
76
|
+
patterns = patterns[:-1] # Presidio appends the deny-list pattern last; it is rebuilt below
|
|
77
|
+
spec["patterns"] = patterns
|
|
78
|
+
spec["deny_list"] = sorted(deny_list, key=len, reverse=True)
|
|
79
|
+
spec["deny_list_score"] = recognizer.deny_list_score
|
|
80
|
+
spec["global_regex_flags"] = recognizer.global_regex_flags
|
|
81
|
+
return PatternRecognizer.from_dict(spec)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def validate_recognizers(recognizers: Any) -> tuple:
|
|
85
|
+
"""Check the recognizers and return private copies of them."""
|
|
86
|
+
if not isinstance(recognizers, tuple):
|
|
87
|
+
raise ConfigError("recognizers must be a tuple of PatternRecognizer")
|
|
88
|
+
for r in recognizers:
|
|
89
|
+
check_recognizer(r)
|
|
90
|
+
names = [r.name for r in recognizers]
|
|
91
|
+
if len(names) != len(set(names)):
|
|
92
|
+
raise ConfigError("recognizer names must be unique")
|
|
93
|
+
return tuple(_snapshot(r) for r in recognizers)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@dataclass(frozen=True)
|
|
97
|
+
class _CustomRegistry:
|
|
98
|
+
"""The custom recognizers of one Redactor, attached to its metadata.
|
|
99
|
+
|
|
100
|
+
metadata_to_json accepts custom entity types and names only from this
|
|
101
|
+
immutable object, which the Redactor builds from its policy, so metadata
|
|
102
|
+
assembled elsewhere cannot declare its own.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
entries: tuple
|
|
106
|
+
|
|
107
|
+
@classmethod
|
|
108
|
+
def of(cls, recognizers: tuple) -> "_CustomRegistry":
|
|
109
|
+
return cls(tuple(
|
|
110
|
+
(r.name, r.supported_entities[0], frozenset(p.name for p in r.patterns))
|
|
111
|
+
for r in recognizers
|
|
112
|
+
))
|