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(guardrails): mask all regex pattern matches, not just first (#17727)
Peter Chanthamynavong539ce89d4e22
diff --git a/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py b/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.pyindex c9feb2c47e6..847048768f5 100644--- a/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py+++ b/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py@@ -337,10 +337,11 @@ class ContentFilterGuardrail(CustomGuardrail):processed_texts = []for text in texts:- # Check regex patterns- pattern_match = self._check_patterns(text)- if pattern_match:- matched_text, pattern_name, action = pattern_match+ # Check regex patterns - process ALL patterns, not just first match+ for compiled_pattern, pattern_name, action in self.compiled_patterns:+ match = compiled_pattern.search(text)+ if not match:+ continueif action == ContentFilterAction.BLOCK:error_msg = f"Content blocked: {pattern_name} pattern detected"@@ -350,10 +351,12 @@ class ContentFilterGuardrail(CustomGuardrail):detail={"error": error_msg, "pattern": pattern_name},)elif action == ContentFilterAction.MASK:- # Replace the matched text with redaction tag- redaction_tag = self._mask_content(matched_text, pattern_name)- text = text.replace(matched_text, redaction_tag)- verbose_proxy_logger.info(f"Masked {pattern_name} in content")+ # Replace ALL matches of this pattern with redaction tag+ redaction_tag = self.pattern_redaction_format.format(+ pattern_name=pattern_name.upper()+ )+ text = compiled_pattern.sub(redaction_tag, text)+ verbose_proxy_logger.info(f"Masked all {pattern_name} matches in content")# Check blocked words - iterate through ALL blocked words# to ensure all matching keywords are processed, not just the first onediff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/content_filter/test_content_filter.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/content_filter/test_content_filter.pyindex ec7a0c0700a..0f8b73ee640 100644--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/content_filter/test_content_filter.py+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/content_filter/test_content_filter.py@@ -671,3 +671,93 @@ class TestContentFilterGuardrail:assert exc_info.value.status_code == 400assert "danger_word" in str(exc_info.value.detail)++ @pytest.mark.asyncio+ async def test_apply_guardrail_masks_all_regex_pattern_matches(self):+ """+ Test that ALL matches of a regex pattern are masked, not just the first one.++ Regression test for GitHub issue #17687:+ https://github.com/BerriAI/litellm/issues/17687++ Before fix:+ Regex: Key\\d++ Input: "Key1 Key1 Key2"+ Output: "[CUSTOM_REGEX_REDACTED] [CUSTOM_REGEX_REDACTED] Key2"+ (only first unique match was replaced)++ After fix:+ Input: "Key1 Key1 Key2"+ Output: "[CUSTOM_REGEX_REDACTED] [CUSTOM_REGEX_REDACTED] [CUSTOM_REGEX_REDACTED]"+ (all matches are replaced)+ """+ patterns = [+ ContentFilterPattern(+ pattern_type="regex",+ pattern=r"Key\d+",+ name="custom_key",+ action=ContentFilterAction.MASK,+ ),+ ]++ guardrail = ContentFilterGuardrail(+ guardrail_name="test-regex-all-matches",+ patterns=patterns,+ )++ # Test case from issue #17687+ guardrailed_inputs = await guardrail.apply_guardrail(+ inputs={"texts": ["Key1 Key1 Key2"]},+ request_data={},+ input_type="request",+ )+ result = guardrailed_inputs.get("texts", [])++ assert result is not None+ assert len(result) == 1+ # All matches should be redacted+ assert result[0] == "[CUSTOM_KEY_REDACTED] [CUSTOM_KEY_REDACTED] [CUSTOM_KEY_REDACTED]"+ assert "Key1" not in result[0]+ assert "Key2" not in result[0]++ @pytest.mark.asyncio+ async def test_apply_guardrail_masks_multiple_patterns_all_matches(self):+ """+ Test that multiple different patterns each mask ALL their matches.+ """+ patterns = [+ ContentFilterPattern(+ pattern_type="prebuilt",+ pattern_name="email",+ action=ContentFilterAction.MASK,+ ),+ ContentFilterPattern(+ pattern_type="regex",+ pattern=r"Key\d+",+ name="custom_key",+ action=ContentFilterAction.MASK,+ ),+ ]++ guardrail = ContentFilterGuardrail(+ guardrail_name="test-multiple-patterns-all",+ patterns=patterns,+ )++ guardrailed_inputs = await guardrail.apply_guardrail(+ inputs={"texts": ["Key1 [email protected] Key2 [email protected] Key1"]},+ request_data={},+ input_type="request",+ )+ result = guardrailed_inputs.get("texts", [])++ assert result is not None+ assert len(result) == 1+ # All emails should be redacted+ assert "[email protected]" not in result[0]+ assert "[email protected]" not in result[0]+ assert result[0].count("[EMAIL_REDACTED]") == 2+ # All Key patterns should be redacted+ assert "Key1" not in result[0]+ assert "Key2" not in result[0]+ assert result[0].count("[CUSTOM_KEY_REDACTED]") == 3