lumoz-utils 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.
@@ -0,0 +1 @@
1
+ prune tests
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: lumoz-utils
3
+ Version: 0.1.0
4
+ Summary: Shared Python utilities for Lumoz
5
+ Requires-Python: >=3.11
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: presidio-analyzer==2.2.364
8
+ Requires-Dist: presidio-anonymizer==2.2.364
9
+ Provides-Extra: test
10
+ Requires-Dist: pytest>=8.0; extra == "test"
11
+
12
+ # lumoz-utils
13
+
14
+ Shared Python utilities for Lumoz. Redaction is available in `lumoz_utils.redaction` for ingestion, classifiers, Python SDKs, and integrations. See the [redaction spec](docs/redaction-lib.md) for the API and metadata schema.
15
+
16
+ ## Installation
17
+
18
+ Python 3.11 or newer is required. From a checkout of this private repository:
19
+
20
+ ```sh
21
+ python -m pip install .
22
+ ```
23
+
24
+ To depend on the package from another Python project, use an authenticated Git URL pinned to a release tag or commit.
25
+
26
+ ```sh
27
+ python -m pip install 'lumoz-utils @ git+https://github.com/lumozai/lumoz-utils.git@v0.1.0'
28
+ ```
29
+
30
+ To run the redaction tests locally:
31
+
32
+ ```sh
33
+ python -m pip install -e '.[test]'
34
+ python -m pytest -q
35
+ ```
36
+
37
+ See [Publishing to PyPI](docs/release.md) for the tagged release workflow.
38
+
39
+ ## Core API
40
+
41
+ The core layer scans a value and returns it with each match replaced by a
42
+ typed placeholder, such as `[REDACTED:EMAIL_ADDRESS]`. It has no field
43
+ categories, keep or drop rules, or retention setting; those belong to the span
44
+ layer above it.
45
+
46
+ ```python
47
+ from lumoz_utils.redaction import Budget, Redactor
48
+
49
+ redactor = Redactor.from_config() # optional: {"entities": [...], "min_score": 0.5}
50
+ budget = Budget() # one per request, shared by every call
51
+ result = redactor.redact_value({"message": "Contact alex@example.com"}, budget=budget)
52
+
53
+ result.disposition # "redacted", or "omitted" if the value could not be scanned completely
54
+ result.value # {"message": "Contact [REDACTED:EMAIL_ADDRESS]"}
55
+ result.metadata # coverage, reason codes, omissions and one pass per key or leaf with matches
56
+ ```
57
+
58
+ `redact_value` accepts text or a value made of JSON types. `scan_text` returns
59
+ the matches in text without replacing them. `REASON_CODES` lists every reason
60
+ code the core records.
61
+
62
+ `redact_otlp` does the same for an OTLP JSON document (as returned by
63
+ `json.loads`) and keeps its shape. Each `{"key": name, "value": ...}` attribute
64
+ pair is treated as an entry named by its key: a credential-named attribute
65
+ keeps its key with the `[REDACTED:SECRET]` placeholder as its value, an
66
+ attribute whose name contains a match is removed, and the name is the context
67
+ for detecting its value.
68
+
69
+ ```python
70
+ span = json.loads(line)
71
+ result = redactor.redact_otlp(span, budget=Budget(field_bytes=4_000_000, request_bytes=8_000_000))
72
+ if result.disposition == "redacted":
73
+ write(json.dumps(result.value))
74
+ ```
75
+
76
+ Hash mode replaces each match with a stable keyed code instead, such as
77
+ `[REDACTED:EMAIL_ADDRESS:3f9a1c0b2e4d]`, so the same value can be grouped
78
+ without being shown. It requires a salt of at least 16 bytes; keep the salt
79
+ secret, because anyone who has it can test guesses against a code. `SECRET`
80
+ matches and credential-named attributes are still masked.
81
+
82
+ ```python
83
+ redactor = Redactor.from_config({"action": "hash"}, hash_salt=os.environ["REDACT_SALT"])
84
+ ```
85
+
86
+ Callers can add their own recognizers: Presidio `PatternRecognizer` objects,
87
+ or dicts in Presidio's recognizer format (`name`, `supported_entity`, `patterns`
88
+ of `{name, regex, score}`, and `deny_list`), which `recognizer_from_dict` turns
89
+ into them. Presidio runs them as-is, with its default flags (patterns ignore
90
+ case). Context words and languages other than `en` are rejected, because they
91
+ need an NLP engine. The library never reads files: callers load the definitions
92
+ from a file or a store and pass them in.
93
+
94
+ Known limitation: Presidio's duplicate filter takes time proportional to the
95
+ square of the number of matches in one value (about 3–4 s for 4,000 matches).
96
+ See the spec.
97
+
98
+ ```python
99
+ redactor = Redactor.from_config({"recognizers": [{
100
+ "name": "Employee ID recognizer",
101
+ "supported_entity": "EMPLOYEE_ID",
102
+ "patterns": [{"name": "employee id", "regex": r"EMP-\d{6}", "score": 0.8}],
103
+ }]})
104
+ redactor.placeholder("VALUE", "acct-1") # the replacement for a value the caller removes whole
105
+ ```
106
+
107
+ ## Bundled data
108
+
109
+ `src/lumoz_utils/redaction/data/public_suffix_list.dat` is a snapshot of the
110
+ [Public Suffix List](https://publicsuffix.org/list/public_suffix_list.dat)
111
+ (MPL-2.0), version `2026-11-28_07-14-22_UTC`. Email validation reads it so the
112
+ default profile never fetches the list over the network. Refresh it by
113
+ downloading the same URL in a reviewed commit.
114
+
115
+ ## Credential fixtures
116
+
117
+ `tests/fixtures/credentials/` holds synthetic credential samples for the
118
+ credential-rule tests, one value per file:
119
+
120
+ - `private_key_block.txt`: PEM delimiters wrapped around deliberately invalid body text
121
+ - `aws_access_key_id.txt`: AWS's documented example access key ID
122
+ - `anthropic_api_key.txt`, `openai_api_key.txt`: fake `sk-` keys
123
+ - `github_token.txt`, `slack_token.txt`, `google_api_key.txt`: fake tokens in
124
+ each provider's format
125
+ - `jwt.txt`: a JWT with a zero-filled dummy signature
126
+ - `bearer_token.txt`: a fake `Bearer` token
127
+
128
+ These examples exercise redaction formats without using credentials issued by a service.
@@ -0,0 +1,117 @@
1
+ # lumoz-utils
2
+
3
+ Shared Python utilities for Lumoz. Redaction is available in `lumoz_utils.redaction` for ingestion, classifiers, Python SDKs, and integrations. See the [redaction spec](docs/redaction-lib.md) for the API and metadata schema.
4
+
5
+ ## Installation
6
+
7
+ Python 3.11 or newer is required. From a checkout of this private repository:
8
+
9
+ ```sh
10
+ python -m pip install .
11
+ ```
12
+
13
+ To depend on the package from another Python project, use an authenticated Git URL pinned to a release tag or commit.
14
+
15
+ ```sh
16
+ python -m pip install 'lumoz-utils @ git+https://github.com/lumozai/lumoz-utils.git@v0.1.0'
17
+ ```
18
+
19
+ To run the redaction tests locally:
20
+
21
+ ```sh
22
+ python -m pip install -e '.[test]'
23
+ python -m pytest -q
24
+ ```
25
+
26
+ See [Publishing to PyPI](docs/release.md) for the tagged release workflow.
27
+
28
+ ## Core API
29
+
30
+ The core layer scans a value and returns it with each match replaced by a
31
+ typed placeholder, such as `[REDACTED:EMAIL_ADDRESS]`. It has no field
32
+ categories, keep or drop rules, or retention setting; those belong to the span
33
+ layer above it.
34
+
35
+ ```python
36
+ from lumoz_utils.redaction import Budget, Redactor
37
+
38
+ redactor = Redactor.from_config() # optional: {"entities": [...], "min_score": 0.5}
39
+ budget = Budget() # one per request, shared by every call
40
+ result = redactor.redact_value({"message": "Contact alex@example.com"}, budget=budget)
41
+
42
+ result.disposition # "redacted", or "omitted" if the value could not be scanned completely
43
+ result.value # {"message": "Contact [REDACTED:EMAIL_ADDRESS]"}
44
+ result.metadata # coverage, reason codes, omissions and one pass per key or leaf with matches
45
+ ```
46
+
47
+ `redact_value` accepts text or a value made of JSON types. `scan_text` returns
48
+ the matches in text without replacing them. `REASON_CODES` lists every reason
49
+ code the core records.
50
+
51
+ `redact_otlp` does the same for an OTLP JSON document (as returned by
52
+ `json.loads`) and keeps its shape. Each `{"key": name, "value": ...}` attribute
53
+ pair is treated as an entry named by its key: a credential-named attribute
54
+ keeps its key with the `[REDACTED:SECRET]` placeholder as its value, an
55
+ attribute whose name contains a match is removed, and the name is the context
56
+ for detecting its value.
57
+
58
+ ```python
59
+ span = json.loads(line)
60
+ result = redactor.redact_otlp(span, budget=Budget(field_bytes=4_000_000, request_bytes=8_000_000))
61
+ if result.disposition == "redacted":
62
+ write(json.dumps(result.value))
63
+ ```
64
+
65
+ Hash mode replaces each match with a stable keyed code instead, such as
66
+ `[REDACTED:EMAIL_ADDRESS:3f9a1c0b2e4d]`, so the same value can be grouped
67
+ without being shown. It requires a salt of at least 16 bytes; keep the salt
68
+ secret, because anyone who has it can test guesses against a code. `SECRET`
69
+ matches and credential-named attributes are still masked.
70
+
71
+ ```python
72
+ redactor = Redactor.from_config({"action": "hash"}, hash_salt=os.environ["REDACT_SALT"])
73
+ ```
74
+
75
+ Callers can add their own recognizers: Presidio `PatternRecognizer` objects,
76
+ or dicts in Presidio's recognizer format (`name`, `supported_entity`, `patterns`
77
+ of `{name, regex, score}`, and `deny_list`), which `recognizer_from_dict` turns
78
+ into them. Presidio runs them as-is, with its default flags (patterns ignore
79
+ case). Context words and languages other than `en` are rejected, because they
80
+ need an NLP engine. The library never reads files: callers load the definitions
81
+ from a file or a store and pass them in.
82
+
83
+ Known limitation: Presidio's duplicate filter takes time proportional to the
84
+ square of the number of matches in one value (about 3–4 s for 4,000 matches).
85
+ See the spec.
86
+
87
+ ```python
88
+ redactor = Redactor.from_config({"recognizers": [{
89
+ "name": "Employee ID recognizer",
90
+ "supported_entity": "EMPLOYEE_ID",
91
+ "patterns": [{"name": "employee id", "regex": r"EMP-\d{6}", "score": 0.8}],
92
+ }]})
93
+ redactor.placeholder("VALUE", "acct-1") # the replacement for a value the caller removes whole
94
+ ```
95
+
96
+ ## Bundled data
97
+
98
+ `src/lumoz_utils/redaction/data/public_suffix_list.dat` is a snapshot of the
99
+ [Public Suffix List](https://publicsuffix.org/list/public_suffix_list.dat)
100
+ (MPL-2.0), version `2026-11-28_07-14-22_UTC`. Email validation reads it so the
101
+ default profile never fetches the list over the network. Refresh it by
102
+ downloading the same URL in a reviewed commit.
103
+
104
+ ## Credential fixtures
105
+
106
+ `tests/fixtures/credentials/` holds synthetic credential samples for the
107
+ credential-rule tests, one value per file:
108
+
109
+ - `private_key_block.txt`: PEM delimiters wrapped around deliberately invalid body text
110
+ - `aws_access_key_id.txt`: AWS's documented example access key ID
111
+ - `anthropic_api_key.txt`, `openai_api_key.txt`: fake `sk-` keys
112
+ - `github_token.txt`, `slack_token.txt`, `google_api_key.txt`: fake tokens in
113
+ each provider's format
114
+ - `jwt.txt`: a JWT with a zero-filled dummy signature
115
+ - `bearer_token.txt`: a fake `Bearer` token
116
+
117
+ These examples exercise redaction formats without using credentials issued by a service.
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "lumoz-utils"
7
+ version = "0.1.0"
8
+ description = "Shared Python utilities for Lumoz"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ # Exact pins: the serialized metadata contract is tested against these versions.
12
+ dependencies = [
13
+ "presidio-analyzer==2.2.364",
14
+ "presidio-anonymizer==2.2.364",
15
+ ]
16
+
17
+ [project.optional-dependencies]
18
+ test = ["pytest>=8.0"]
19
+
20
+ [tool.setuptools.packages.find]
21
+ where = ["src"]
22
+
23
+ [tool.setuptools.package-data]
24
+ "lumoz_utils.redaction" = ["data/*.dat"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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