The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(presidio): use correct text positions in anonymize_text (#24998)
Dmitryfc75380b8848
diff --git a/litellm/proxy/guardrails/guardrail_hooks/presidio.py b/litellm/proxy/guardrails/guardrail_hooks/presidio.pyindex 0f4ebbd4880..e048ca21cba 100644--- a/litellm/proxy/guardrails/guardrail_hooks/presidio.py+++ b/litellm/proxy/guardrails/guardrail_hooks/presidio.py@@ -485,61 +485,71 @@ class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):redacted_text = await response.json()- new_text = textif redacted_text is not None:verbose_proxy_logger.debug("redacted_text: %s", redacted_text)- # Process items in reverse order by start position so that- # replacing later spans first does not shift earlier coordinates.- for item in sorted(- redacted_text["items"], key=lambda x: x["start"], reverse=True- ):- start = item["start"]- end = item["end"]- replacement = item["text"] # replacement token- if item["operator"] == "replace" and output_parse_pii is True:- if request_data is None:- verbose_proxy_logger.warning(- "Presidio anonymize_text called without request_data — "- "PII tokens cannot be stored per-request. "- "This may indicate a missing caller update."- )- request_data = {}- # Store pii_tokens in metadata to avoid leaking to LLM providers.- # Providers like Anthropic reject unknown top-level fields.- if not request_data.get("metadata"):- request_data["metadata"] = {}- if "pii_tokens" not in request_data["metadata"]:- request_data["metadata"]["pii_tokens"] = {}- pii_tokens = request_data["metadata"]["pii_tokens"]-- # Append a sequential number to make each token unique- # per request, so unmasking maps back to the correct- # original value. Format: <PHONE_NUMBER_1>, <PHONE_NUMBER_2>- # This is LLM-friendly and degrades gracefully if the- # LLM doesn't echo the token verbatim.- seq = len(pii_tokens) + 1- if replacement.endswith(">"):- replacement = f"{replacement[:-1]}_{seq}>"- else:- replacement = f"{replacement}_{seq}"-- # Use ORIGINAL text (not new_text) since start/end- # reference the original text's coordinates.- pii_tokens[replacement] = text[start:end]+ if not output_parse_pii:+ # No need to build numbered tokens — just use Presidio's+ # already-anonymized text directly. The old code incorrectly+ # applied anonymizer item positions (which reference the+ # *output* text) to the *original* text, causing offset errors.+ for item in redacted_text.get("items", []):+ entity_type = item.get("entity_type", None)+ if entity_type is not None:+ masked_entity_count[entity_type] = (+ masked_entity_count.get(entity_type, 0) + 1+ )+ return redacted_text["text"]++ # output_parse_pii is True — we need sequentially numbered+ # tokens and a pii_tokens mapping for later unmasking.+ # Use analyze_results positions (which reference the ORIGINAL+ # text) instead of anonymizer items (which reference the output).+ new_text = text+ if request_data is None:+ verbose_proxy_logger.warning(+ "Presidio anonymize_text called without request_data — "+ "PII tokens cannot be stored per-request. "+ "This may indicate a missing caller update."+ )+ request_data = {}+ if not request_data.get("metadata"):+ request_data["metadata"] = {}+ if "pii_tokens" not in request_data["metadata"]:+ request_data["metadata"]["pii_tokens"] = {}+ pii_tokens = request_data["metadata"]["pii_tokens"]++ # Assign sequence numbers in forward (left-to-right) order so+ # that <PERSON_1> is the first entity in the text, etc.+ sorted_forward = sorted(+ analyze_results, key=lambda x: x["start"]+ )+ seq_map = {}+ for idx, ar in enumerate(sorted_forward, start=1):+ seq_map[(ar["start"], ar["end"])] = idx++ # Apply replacements in reverse order by start position so+ # that replacing later spans first does not shift earlier+ # coordinates in the original text.+ for ar in reversed(sorted_forward):+ start = ar["start"]+ end = ar["end"]+ entity_type = ar["entity_type"]+ replacement = f"<{entity_type}>"++ seq = seq_map[(start, end)]+ if replacement.endswith(">"):+ replacement = f"{replacement[:-1]}_{seq}>"+ else:+ replacement = f"{replacement}_{seq}"++ pii_tokens[replacement] = text[start:end]new_text = new_text[:start] + replacement + new_text[end:]- entity_type = item.get("entity_type", None)- if entity_type is not None:- masked_entity_count[entity_type] = (- masked_entity_count.get(entity_type, 0) + 1- )- # When output_parse_pii is True, new_text contains sequentially- # numbered tokens (e.g. <PHONE_NUMBER_1>) that match the keys- # in pii_tokens. Returning redacted_text["text"] (Presidio's- # original output) would send un-numbered tokens to the LLM,- # making unmasking impossible.- # When output_parse_pii is False, new_text == redacted_text["text"]- # because no suffix is appended.++ masked_entity_count[entity_type] = (+ masked_entity_count.get(entity_type, 0) + 1+ )+return new_textelse:raise Exception("Invalid anonymizer response: received None")diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_presidio.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_presidio.pyindex 32a8c1b1070..38ea42285c1 100644--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_presidio.py+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_presidio.py@@ -2230,3 +2230,171 @@ async def test_apply_to_output_streaming_bytes_only_logs_warning():mock_logger.warning.assert_called_once()warning_msg = mock_logger.warning.call_args[0][0]assert "Output PII masking was skipped" in warning_msg+++async def test_anonymize_text_uses_correct_positions_no_parse_pii():+ """+ Regression test for anonymizer offset bug (fixes #24160).++ The Presidio anonymizer returns items with start/end positions that+ reference the *anonymized output* text, not the original input text.+ When output_parse_pii is False, anonymize_text must return+ redacted_text["text"] directly instead of manually splicing the+ original text using those positions, which produces garbled output+ with remnants of original PII data.+ """+ original_text = (+ "My name is John Smith, my email is [email protected], phone 555-867-5309"+ )+ # Positions as returned by the analyzer (reference original text)+ analyze_results = [+ {"end": 51, "entity_type": "EMAIL_ADDRESS", "score": 1.0, "start": 35},+ {"end": 21, "entity_type": "PERSON", "score": 0.85, "start": 11},+ {"end": 71, "entity_type": "PHONE_NUMBER", "score": 0.75, "start": 59},+ ]+ # Anonymizer response — positions reference the *anonymized* text+ anonymizer_response = {+ "text": "My name is <PERSON>, my email is <EMAIL_ADDRESS>, phone <PHONE_NUMBER>",+ "items": [+ {+ "start": 56,+ "end": 70,+ "entity_type": "PHONE_NUMBER",+ "text": "<PHONE_NUMBER>",+ "operator": "replace",+ },+ {+ "start": 33,+ "end": 48,+ "entity_type": "EMAIL_ADDRESS",+ "text": "<EMAIL_ADDRESS>",+ "operator": "replace",+ },+ {+ "start": 11,+ "end": 19,+ "entity_type": "PERSON",+ "text": "<PERSON>",+ "operator": "replace",+ },+ ],+ }++ guardrail = _OPTIONAL_PresidioPIIMasking(+ presidio_analyzer_api_base="http://test-analyzer/",+ presidio_anonymizer_api_base="http://test-anonymizer/",+ mock_testing=False,+ )++ mock_iterator = _make_mock_session_iterator(+ json_response=anonymizer_response,+ )++ masked_entity_count = {}+ with patch.object(guardrail, "_get_session_iterator", mock_iterator):+ result = await guardrail.anonymize_text(+ text=original_text,+ analyze_results=analyze_results,+ output_parse_pii=False,+ masked_entity_count=masked_entity_count,+ )++ expected = "My name is <PERSON>, my email is <EMAIL_ADDRESS>, phone <PHONE_NUMBER>"+ assert result == expected, (+ f"anonymize_text produced garbled output with PII remnants.\n"+ f"Expected: {expected!r}\n"+ f"Got: {result!r}"+ )+ assert masked_entity_count == {+ "PERSON": 1,+ "EMAIL_ADDRESS": 1,+ "PHONE_NUMBER": 1,+ }+++async def test_anonymize_text_uses_correct_positions_with_parse_pii():+ """+ Regression test for anonymizer offset bug with output_parse_pii=True+ (fixes #24160).++ When output_parse_pii is True, anonymize_text must use positions from+ analyze_results (which reference the original text) to build numbered+ tokens and the pii_tokens mapping, not positions from anonymizer items+ (which reference the anonymized output text).+ """+ original_text = (+ "My name is John Smith, my email is [email protected], phone 555-867-5309"+ )+ analyze_results = [+ {"end": 51, "entity_type": "EMAIL_ADDRESS", "score": 1.0, "start": 35},+ {"end": 21, "entity_type": "PERSON", "score": 0.85, "start": 11},+ {"end": 71, "entity_type": "PHONE_NUMBER", "score": 0.75, "start": 59},+ ]+ anonymizer_response = {+ "text": "My name is <PERSON>, my email is <EMAIL_ADDRESS>, phone <PHONE_NUMBER>",+ "items": [+ {+ "start": 56,+ "end": 70,+ "entity_type": "PHONE_NUMBER",+ "text": "<PHONE_NUMBER>",+ "operator": "replace",+ },+ {+ "start": 33,+ "end": 48,+ "entity_type": "EMAIL_ADDRESS",+ "text": "<EMAIL_ADDRESS>",+ "operator": "replace",+ },+ {+ "start": 11,+ "end": 19,+ "entity_type": "PERSON",+ "text": "<PERSON>",+ "operator": "replace",+ },+ ],+ }++ guardrail = _OPTIONAL_PresidioPIIMasking(+ presidio_analyzer_api_base="http://test-analyzer/",+ presidio_anonymizer_api_base="http://test-anonymizer/",+ mock_testing=False,+ output_parse_pii=True,+ )++ mock_iterator = _make_mock_session_iterator(+ json_response=anonymizer_response,+ )++ masked_entity_count = {}+ request_data = {"metadata": {}}+ with patch.object(guardrail, "_get_session_iterator", mock_iterator):+ result = await guardrail.anonymize_text(+ text=original_text,+ analyze_results=analyze_results,+ output_parse_pii=True,+ masked_entity_count=masked_entity_count,+ request_data=request_data,+ )++ # Result must not contain any remnants of original PII+ assert "John" not in result+ assert "[email protected]" not in result+ assert "555-867-5309" not in result++ # pii_tokens must map numbered tokens back to correct original values+ pii_tokens = request_data["metadata"]["pii_tokens"]+ token_values = set(pii_tokens.values())+ assert "John Smith" in token_values+ assert "[email protected]" in token_values+ assert "555-867-5309" in token_values++ # Tokens must be numbered in left-to-right order of appearance:+ # PERSON (pos 11) → _1, EMAIL_ADDRESS (pos 35) → _2, PHONE_NUMBER (pos 59) → _3+ assert pii_tokens.get("<PERSON_1>") == "John Smith"+ assert pii_tokens.get("<EMAIL_ADDRESS_2>") == "[email protected]"+ assert pii_tokens.get("<PHONE_NUMBER_3>") == "555-867-5309"