Skip to content

Commit fb262c8

Browse files
committed
fix(hash): preserve existing pseudonyms while honoring algorithms and HMAC
1 parent ad36d6a commit fb262c8

7 files changed

Lines changed: 96 additions & 196 deletions

File tree

‎CHANGELOG.MD‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,10 @@
1616

1717
#### Changed
1818

19-
- Hash APIs honor the selected algorithm and emit full digests. Optional
20-
`hash_key` enables HMAC with a key of at least 32 bytes. Plain hashes provide
21-
deterministic pseudonyms and do not resist guessing of low-entropy PII.
19+
- Hash APIs honor the selected algorithm while preserving existing plain-hash
20+
marker widths and defaults. Optional `hash_key` enables full-length HMAC with
21+
a key of at least 32 bytes. Plain hashes provide deterministic pseudonyms and
22+
do not resist guessing of low-entropy PII.
2223
- Reuse tokens for repeated values, avoid existing token collisions, reject
2324
invalid explicit ranges and unsupported entity selections, and report backend
2425
entity capabilities. Async decorators await results before filtering.

‎datafog/__init__.py‎

Lines changed: 22 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ def process(
290290
anonymize: bool = False,
291291
method: str = "redact",
292292
*,
293-
hash_type: str = "sha256",
293+
hash_type: str | None = None,
294294
hash_key: bytes | None = None,
295295
) -> dict:
296296
"""
@@ -300,6 +300,9 @@ def process(
300300
text: Input text to process
301301
anonymize: Whether to anonymize detected PII
302302
method: Anonymization method ('redact', 'replace', 'hash')
303+
hash_type: Optional algorithm. The legacy plain-hash default is MD5;
304+
keyed hashes default to SHA256.
305+
hash_key: At least 32 bytes for a full keyed HMAC digest.
303306
304307
Returns:
305308
Dictionary with original text, anonymized text (if requested), and findings
@@ -321,32 +324,32 @@ def process(
321324

322325
if method not in {"redact", "replace", "hash"}:
323326
raise ValueError("method must be 'redact', 'replace', or 'hash'")
327+
if anonymize and method == "hash":
328+
from .engine import _hash_value, _validate_hash_parameters
329+
330+
algorithm = (
331+
hash_type
332+
if hash_type is not None
333+
else ("sha256" if hash_key is not None else "md5")
334+
)
335+
_validate_hash_parameters("hash", algorithm, hash_key)
324336
findings = _detect_impl(text)
325337

326338
result = {"original": text, "findings": findings}
327339

328-
if anonymize and method == "hash":
329-
entities = [
330-
Entity(
331-
item["type"], item["value"], item["start"], item["end"], 1.0, "regex"
332-
)
333-
for item in findings
334-
]
335-
result["anonymized"] = redact(
336-
text,
337-
entities=entities,
338-
strategy="hash",
339-
hash_type=hash_type,
340-
hash_key=hash_key,
341-
).redacted_text
342-
elif anonymize:
340+
if anonymize:
343341
parts = []
344342
cursor = 0
345343
suffix = "REDACTED" if method == "redact" else "XXXXX"
346344
for finding in sorted(findings, key=lambda item: item["start"]):
347-
parts.extend(
348-
(text[cursor : finding["start"]], f"[{finding['type']}_{suffix}]")
349-
)
345+
if method == "hash":
346+
digest = _hash_value(
347+
finding["value"], algorithm, hash_key, plain_length=8
348+
)
349+
replacement = f"[{finding['type']}_{digest}]"
350+
else:
351+
replacement = f"[{finding['type']}_{suffix}]"
352+
parts.extend((text[cursor : finding["start"]], replacement))
350353
cursor = finding["end"]
351354
parts.append(text[cursor:])
352355
result["anonymized"] = "".join(parts)

‎datafog/engine.py‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -809,6 +809,26 @@ def _validate_hash_parameters(
809809
raise ValueError(f"Unsupported hash_type: {hash_type!r}") from None
810810

811811

812+
def _hash_value(
813+
text: str,
814+
hash_type: str,
815+
hash_key: bytes | None,
816+
*,
817+
plain_length: int = 12,
818+
) -> str:
819+
"""Retain legacy plain-hash widths; keyed HMAC always uses its full digest.
820+
821+
Unkeyed hashes are deterministic pseudonyms and remain vulnerable to
822+
dictionary attacks regardless of digest width. Supply a private key to
823+
prevent direct enumeration of low-entropy identifiers.
824+
"""
825+
_validate_hash_parameters("hash", hash_type, hash_key)
826+
encoded = text.encode("utf-8", "surrogatepass")
827+
if hash_key is not None:
828+
return hmac.new(hash_key, encoded, hash_type).hexdigest()
829+
return hashlib.new(hash_type, encoded).hexdigest()[:plain_length]
830+
831+
812832
def _validated_redaction_entities(text: str, entities: list[Entity]) -> list[Entity]:
813833
valid_entities = []
814834
for entity in entities:
@@ -842,6 +862,10 @@ def redact(
842862
type priority and then confidence. Suppressed spans are omitted from
843863
``RedactResult.entities`` and ``mapping``.
844864
865+
Plain hashes retain the historical 12-character digest prefix and provide
866+
deterministic pseudonymization. With ``hash_key`` (at least 32 bytes), HMAC
867+
uses the complete digest. Unkeyed hashes do not resist dictionary attacks.
868+
845869
Invalid ranges, mismatched source text, and malformed labels raise ValueError.
846870
847871
``mapping`` for the ``mask`` strategy is keyed by per-type indexed keys
@@ -881,12 +905,7 @@ def redact(
881905
break
882906
occupied_tokens.add(mapping_key)
883907
elif strategy == "hash":
884-
encoded = original.encode("utf-8", "surrogatepass")
885-
digest = (
886-
hmac.new(hash_key, encoded, hash_type).hexdigest()
887-
if hash_key is not None
888-
else hashlib.new(hash_type, encoded).hexdigest()
889-
)
908+
digest = _hash_value(original, hash_type, hash_key)
890909
key = (entity.type, original)
891910
if key not in pseudonym_by_value:
892911
candidate = f"[{entity.type}_{digest}]"

‎docs/review-remediation.md‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,14 @@ nonblocking events receive an explicit incomplete-scan notice. Unexpected hook
3030
failures retain the documented fail-open contract and log exception types only.
3131

3232
`hash_type` selects md5, sha256 or sha3_256 on the CLI and legacy model APIs.
33-
The engine also accepts algorithms provided by hashlib. Digests use full hex
34-
lengths. Plain deterministic hashes are pseudonymization: SSNs, phones and
33+
The engine also accepts fixed-length algorithms provided by hashlib. Existing
34+
plain-hash marker formats remain compatible: engine, class facade and CLI
35+
markers use 12 hex characters with SHA256 as their default; deprecated top-level
36+
`process` uses eight hex characters and retains its MD5 default. Its explicit
37+
`hash_type` option uses that same legacy width. The legacy Anonymizer model keeps
38+
its existing full plain digests. Explicit keyed hashes use the full HMAC digest;
39+
an omitted algorithm selects SHA256 for this new keyed mode.
40+
Plain deterministic hashes are pseudonymization: SSNs, phones and
3541
other guessable inputs can be enumerated. Use `hash_key` (at least 32 random
3642
bytes) for keyed HMAC and keep the key outside logs and source control:
3743

@@ -91,7 +97,7 @@ release still requires the Core publication and Python dependency update above.
9197
| PY-M4 | Native backend selection also supplies the structured stage of smart/spaCy/GLiNER. CLI commands work with DATAFOG_BACKEND=rust. |
9298
| PY-M5 | Request-scoped tokens, nested tool/function arguments, prompt/input fields and buffered streaming protect all tested request/response shapes. Live proxy deployment is not claimed. |
9399
| PY-M6 | Bare strings, invalid labels and labels unavailable to the selected backend/engine raise explicit errors. Supported aliases remain accepted. |
94-
| PY-M7 | APIs and CLI honor hash_type, use full digests and support keyed HMAC. Plain-hash guessing limitations are documented; algorithm/key tests pass. |
100+
| PY-M7 | APIs and CLI honor hash_type, preserve existing plain-hash formats and support full-length keyed HMAC. Plain-hash guessing limitations are documented; algorithm/key and compatibility tests pass. |
95101
| PY-M8 | Hook per-string/total budget exhaustion emits review/deny or an incomplete-scan notice. Tests put PII past the cap. |
96102
| PY-M9 | Allowlist expressions run with match timeouts; timed-out expressions retain findings. Adversarial patterns and safe quantified groups are tested. |
97103
| PY-M10 | Dependency resolution stays within the explicitly reviewed Core minor, replacing the broad less-than-2 range. Exact output locks should still pin patch versions. |

‎tests/contracts/wrapper-4.12.0.json‎

Lines changed: 5 additions & 158 deletions
Original file line numberDiff line numberDiff line change
@@ -131,151 +131,6 @@
131131
"warnings": []
132132
}
133133
},
134-
"redact-hash": {
135-
"classification": "behavioral-fix",
136-
"reason": "PY-M7 emits the complete chosen digest and supports keyed HMAC.",
137-
"expected": {
138-
"value": {
139-
"result_type": "RedactResult",
140-
"fields": {
141-
"redacted_text": "[EMAIL_08168cd80dfd534ab0f10af10f1303fe00af2d43ab5c1432360d137f8197e17a] [EMAIL_e8f39b3e1382367d6d41ab34dc270d4e7533f978c9e9a775dfe2185b2f96b96c] [EMAIL_08168cd80dfd534ab0f10af10f1303fe00af2d43ab5c1432360d137f8197e17a] [SSN_01a54629efb952287e554eb23ef69c52097a75aecc0e3a93ca0855ab6d7a31a0]",
142-
"mapping": {
143-
"[EMAIL_08168cd80dfd534ab0f10af10f1303fe00af2d43ab5c1432360d137f8197e17a]": "a@example.com",
144-
"[EMAIL_e8f39b3e1382367d6d41ab34dc270d4e7533f978c9e9a775dfe2185b2f96b96c]": "b@example.com",
145-
"[SSN_01a54629efb952287e554eb23ef69c52097a75aecc0e3a93ca0855ab6d7a31a0]": "123-45-6789"
146-
},
147-
"entities": [
148-
{
149-
"result_type": "Entity",
150-
"fields": {
151-
"type": "EMAIL",
152-
"text": "a@example.com",
153-
"start": 0,
154-
"end": 13,
155-
"confidence": 1.0,
156-
"engine": "regex"
157-
}
158-
},
159-
{
160-
"result_type": "Entity",
161-
"fields": {
162-
"type": "EMAIL",
163-
"text": "b@example.com",
164-
"start": 14,
165-
"end": 27,
166-
"confidence": 1.0,
167-
"engine": "regex"
168-
}
169-
},
170-
{
171-
"result_type": "Entity",
172-
"fields": {
173-
"type": "EMAIL",
174-
"text": "a@example.com",
175-
"start": 28,
176-
"end": 41,
177-
"confidence": 1.0,
178-
"engine": "regex"
179-
}
180-
},
181-
{
182-
"result_type": "Entity",
183-
"fields": {
184-
"type": "SSN",
185-
"text": "123-45-6789",
186-
"start": 42,
187-
"end": 53,
188-
"confidence": 1.0,
189-
"engine": "regex"
190-
}
191-
}
192-
]
193-
}
194-
},
195-
"warnings": []
196-
}
197-
},
198-
"engine-redact-hash": {
199-
"classification": "behavioral-fix",
200-
"reason": "PY-M7 emits the complete chosen digest and supports keyed HMAC.",
201-
"expected": {
202-
"value": {
203-
"result_type": "RedactResult",
204-
"fields": {
205-
"redacted_text": "[EMAIL_08168cd80dfd534ab0f10af10f1303fe00af2d43ab5c1432360d137f8197e17a] [EMAIL_e8f39b3e1382367d6d41ab34dc270d4e7533f978c9e9a775dfe2185b2f96b96c] [EMAIL_08168cd80dfd534ab0f10af10f1303fe00af2d43ab5c1432360d137f8197e17a]",
206-
"mapping": {
207-
"[EMAIL_08168cd80dfd534ab0f10af10f1303fe00af2d43ab5c1432360d137f8197e17a]": "a@example.com",
208-
"[EMAIL_e8f39b3e1382367d6d41ab34dc270d4e7533f978c9e9a775dfe2185b2f96b96c]": "b@example.com"
209-
},
210-
"entities": [
211-
{
212-
"result_type": "Entity",
213-
"fields": {
214-
"type": "EMAIL",
215-
"text": "a@example.com",
216-
"start": 0,
217-
"end": 13,
218-
"confidence": 1.0,
219-
"engine": "regex"
220-
}
221-
},
222-
{
223-
"result_type": "Entity",
224-
"fields": {
225-
"type": "EMAIL",
226-
"text": "b@example.com",
227-
"start": 14,
228-
"end": 27,
229-
"confidence": 1.0,
230-
"engine": "regex"
231-
}
232-
},
233-
{
234-
"result_type": "Entity",
235-
"fields": {
236-
"type": "EMAIL",
237-
"text": "a@example.com",
238-
"start": 28,
239-
"end": 41,
240-
"confidence": 1.0,
241-
"engine": "regex"
242-
}
243-
}
244-
]
245-
}
246-
},
247-
"warnings": []
248-
}
249-
},
250-
"preset-hash": {
251-
"classification": "behavioral-fix",
252-
"reason": "PY-M7 emits the complete chosen digest and supports keyed HMAC.",
253-
"expected": {
254-
"value": {
255-
"result_type": "RedactResult",
256-
"fields": {
257-
"redacted_text": "[EMAIL_ff8d9819fc0e12bf0d24892e45987e249a28dce836a85cad60e28eaaa8c6d976]",
258-
"mapping": {
259-
"[EMAIL_ff8d9819fc0e12bf0d24892e45987e249a28dce836a85cad60e28eaaa8c6d976]": "alice@example.com"
260-
},
261-
"entities": [
262-
{
263-
"result_type": "Entity",
264-
"fields": {
265-
"type": "EMAIL",
266-
"text": "alice@example.com",
267-
"start": 0,
268-
"end": 17,
269-
"confidence": 1.0,
270-
"engine": "regex"
271-
}
272-
}
273-
]
274-
}
275-
},
276-
"warnings": []
277-
}
278-
},
279134
"explicit-invalid-bounds": {
280135
"classification": "validation-difference",
281136
"reason": "PY-L7 rejects malformed explicit spans rather than silently skipping them.",
@@ -495,8 +350,8 @@
495350
}
496351
},
497352
"process-hash": {
498-
"classification": "behavioral-fix",
499-
"reason": "PY-M7 replaces legacy truncated MD5 with the complete selected digest; PY-L3 updates the retirement notice.",
353+
"classification": "diagnostic-difference",
354+
"reason": "PY-L3 retirement notices identify the current release. Legacy default MD5 and its eight-character prefix remain compatible; explicit algorithms and keyed HMAC are additional options.",
500355
"expected": {
501356
"value": {
502357
"original": "alice@example.com",
@@ -508,7 +363,7 @@
508363
"end": 17
509364
}
510365
],
511-
"anonymized": "[EMAIL_ff8d9819fc0e12bf0d24892e45987e249a28dce836a85cad60e28eaaa8c6d976]"
366+
"anonymized": "[EMAIL_c160f8cc]"
512367
},
513368
"warnings": [
514369
{
@@ -569,7 +424,7 @@
569424
},
570425
"public-signatures": {
571426
"classification": "signature-addition",
572-
"reason": "PY-M7 adds keyword-only hash_type/hash_key; TextService custom models use the engine gliner_model keyword; backend remains keyword-only.",
427+
"reason": "PY-M7 adds keyword-only hash_type/hash_key while preserving existing unkeyed output widths and omitted legacy hash defaults; TextService custom models use the engine gliner_model keyword; backend remains keyword-only.",
573428
"expected": {
574429
"value": {
575430
"datafog:scan": {
@@ -762,7 +617,7 @@
762617
"name": "hash_type",
763618
"kind": "KEYWORD_ONLY",
764619
"required": false,
765-
"default": "sha256"
620+
"default": null
766621
},
767622
{
768623
"name": "hash_key",
@@ -1112,14 +967,6 @@
1112967
},
1113968
"warnings": []
1114969
}
1115-
},
1116-
"anonymize-text-hash": {
1117-
"classification": "behavioral-fix",
1118-
"reason": "PY-M7 emits the complete chosen digest rather than a truncated unsalted token.",
1119-
"expected": {
1120-
"value": "[EMAIL_ff8d9819fc0e12bf0d24892e45987e249a28dce836a85cad60e28eaaa8c6d976]",
1121-
"warnings": []
1122-
}
1123970
}
1124971
}
1125972
}

0 commit comments

Comments
 (0)