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
[Bug Fix] Bedrock Guardrails - Ensure PII Masking is applied on response streaming or non streaming content when using post call (#12086)
Ishaan Jaffc994c22c132d
diff --git a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.pyindex a16f7f1a0b2..22776dfded4 100644--- a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py+++ b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py@@ -39,7 +39,13 @@ from litellm.types.proxy.guardrails.guardrail_hooks.bedrock_guardrails import (BedrockRequest,BedrockTextContent,)-from litellm.types.utils import ModelResponse, ModelResponseStream+from litellm.types.utils import (+ Choices,+ ModelResponse,+ ModelResponseStream,+ StreamingChoices,+ TextChoices,+)GUARDRAIL_NAME = "bedrock"@@ -472,6 +478,13 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):))++ ########## 3. Apply masking to response if enabled ##########+ self._apply_masking_to_response(+ response=response,+ bedrock_guardrail_response=bedrock_guardrail_response,+ )+################################################################### 3. Add the guardrail to the applied guardrails header ###################################################################@@ -553,12 +566,20 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):# Bedrock will raise an exception if this violates the guardrail policy###################################################################- await self.make_bedrock_api_request(+ bedrock_guardrail_response = await self.make_bedrock_api_request(kwargs=request_data, response=assembled_model_response)#########################################################################- ########## If guardrail passed, then return the collected chunks ##########+ ########## 2. Apply masking to response if enabled ##########+ #########################################################################+ self._apply_masking_to_response(+ response=assembled_model_response,+ bedrock_guardrail_response=bedrock_guardrail_response,+ )++ #########################################################################+ ########## 3. Return the (potentially masked) chunks ###################################################################################mock_response = MockResponseIterator(model_response=assembled_model_response@@ -692,3 +713,77 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):elif isinstance(item, str):message_text_content.append(item)return message_text_content++ def _apply_masking_to_response(+ self,+ response: Union[ModelResponse, Any],+ bedrock_guardrail_response: BedrockGuardrailResponse,+ ) -> None:+ """+ Apply masked content from bedrock guardrail to the response object.++ Args:+ response: The response object to modify+ bedrock_guardrail_response: Response from Bedrock guardrail containing masked content+ """+ # Get masked texts from guardrail response+ masked_texts = self._extract_masked_texts_from_response(+ bedrock_guardrail_response+ )++ if not masked_texts:+ verbose_proxy_logger.debug("No masked outputs found, skipping response masking")+ return++ verbose_proxy_logger.debug(+ "Applying masking to response with %d masked texts", len(masked_texts)+ )++ # Apply masking to ModelResponse+ if isinstance(response, litellm.ModelResponse):+ self._apply_masking_to_model_response(response, masked_texts)+ else:+ verbose_proxy_logger.warning(+ "Unsupported response type for masking: %s", type(response)+ )++ def _apply_masking_to_model_response(+ self, response: litellm.ModelResponse, masked_texts: List[str]+ ) -> None:+ """+ Apply masked texts to a ModelResponse object.++ Args:+ response: The ModelResponse object to modify in-place+ masked_texts: List of masked text strings from guardrail+ """+ masking_index = 0++ for choice in response.choices:+ if isinstance(choice, Choices):+ # For chat completions+ if choice.message.content and isinstance(choice.message.content, str):+ if masking_index < len(masked_texts):+ choice.message.content = masked_texts[masking_index]+ masking_index += 1+ verbose_proxy_logger.debug(+ "Applied masking to choice message content"+ )+ elif isinstance(choice, StreamingChoices):+ # For streaming responses, modify delta content+ if choice.delta.content and isinstance(choice.delta.content, str):+ if masking_index < len(masked_texts):+ choice.delta.content = masked_texts[masking_index]+ masking_index += 1+ verbose_proxy_logger.debug(+ "Applied masking to choice delta content"+ )+ elif isinstance(choice, TextChoices):+ # For text completions+ if choice.text and isinstance(choice.text, str):+ if masking_index < len(masked_texts):+ choice.text = masked_texts[masking_index]+ masking_index += 1+ verbose_proxy_logger.debug(+ "Applied masking to choice text content"+ )diff --git a/tests/guardrails_tests/test_bedrock_guardrails.py b/tests/guardrails_tests/test_bedrock_guardrails.pyindex 246338fd1d3..a3df486bfa1 100644--- a/tests/guardrails_tests/test_bedrock_guardrails.py+++ b/tests/guardrails_tests/test_bedrock_guardrails.py@@ -568,5 +568,212 @@ async def test_bedrock_guardrail_uses_masked_output_without_masking_flags():print("✅ Masked output was applied even without masking flags enabled")+async def test_bedrock_guardrail_response_pii_masking_non_streaming():+ """Test that PII masking is applied to response content in non-streaming scenarios"""+ from unittest.mock import AsyncMock, MagicMock, patch+ from litellm.proxy._types import UserAPIKeyAuth++ # Create proper mock objects+ mock_user_api_key_dict = UserAPIKeyAuth()++ # Create guardrail with response masking enabled+ guardrail = BedrockGuardrail(+ guardrailIdentifier="test-guardrail",+ guardrailVersion="DRAFT",+ )++ # Mock the Bedrock API response with ANONYMIZED PII+ mock_bedrock_response = MagicMock()+ mock_bedrock_response.status_code = 200+ mock_bedrock_response.json.return_value = {+ "action": "GUARDRAIL_INTERVENED",+ "outputs": [{+ "text": "My credit card number is {CREDIT_DEBIT_CARD_NUMBER} and my phone is {PHONE}"+ }],+ "assessments": [{+ "sensitiveInformationPolicy": {+ "piiEntities": [+ {+ "type": "CREDIT_DEBIT_CARD_NUMBER",+ "match": "1234-5678-9012-3456",+ "action": "ANONYMIZED"+ },+ {+ "type": "PHONE",+ "match": "+1 412 555 1212",+ "action": "ANONYMIZED"+ }+ ]+ }+ }]+ }++ # Create a mock response that contains PII+ mock_response = litellm.ModelResponse(+ id="test-id",+ choices=[+ litellm.Choices(+ index=0,+ message=litellm.Message(+ role="assistant",+ content="My credit card number is 1234-5678-9012-3456 and my phone is +1 412 555 1212"+ ),+ finish_reason="stop"+ )+ ],+ created=1234567890,+ model="gpt-4o",+ object="chat.completion"+ )++ request_data = {+ "model": "gpt-4o",+ "messages": [+ {"role": "user", "content": "What's your credit card and phone number?"},+ ],+ }++ # Patch the async_handler.post method+ with patch.object(guardrail.async_handler, 'post', new_callable=AsyncMock) as mock_post:+ mock_post.return_value = mock_bedrock_response++ # Call the post-call success hook+ await guardrail.async_post_call_success_hook(+ data=request_data,+ user_api_key_dict=mock_user_api_key_dict,+ response=mock_response+ )++ # Verify that the response content was masked+ assert mock_response.choices[0].message.content == "My credit card number is {CREDIT_DEBIT_CARD_NUMBER} and my phone is {PHONE}"+ print("✓ Non-streaming response PII masking test passed")+++async def test_bedrock_guardrail_response_pii_masking_streaming():+ """Test that PII masking is applied to response content in streaming scenarios"""+ from unittest.mock import AsyncMock, MagicMock, patch+ from litellm.proxy._types import UserAPIKeyAuth+ from litellm.types.utils import ModelResponseStream++ # Create proper mock objects+ mock_user_api_key_dict = UserAPIKeyAuth()++ # Create guardrail with response masking enabled+ guardrail = BedrockGuardrail(+ guardrailIdentifier="test-guardrail",+ guardrailVersion="DRAFT",+ )++ # Mock the Bedrock API response with ANONYMIZED PII+ mock_bedrock_response = MagicMock()+ mock_bedrock_response.status_code = 200+ mock_bedrock_response.json.return_value = {+ "action": "GUARDRAIL_INTERVENED",+ "outputs": [{+ "text": "Sure! My email is {EMAIL} and SSN is {US_SSN}"+ }],+ "assessments": [{+ "sensitiveInformationPolicy": {+ "piiEntities": [+ {+ "type": "EMAIL",+ "match": "[email protected]",+ "action": "ANONYMIZED"+ },+ {+ "type": "US_SSN",+ "match": "123-45-6789",+ "action": "ANONYMIZED"+ }+ ]+ }+ }]+ }++ # Create mock streaming chunks+ async def mock_streaming_response():+ chunks = [+ ModelResponseStream(+ id="test-id",+ choices=[+ litellm.utils.StreamingChoices(+ index=0,+ delta=litellm.utils.Delta(content="Sure! My email is "),+ finish_reason=None+ )+ ],+ created=1234567890,+ model="gpt-4o",+ object="chat.completion.chunk"+ ),+ ModelResponseStream(+ id="test-id",+ choices=[+ litellm.utils.StreamingChoices(+ index=0,+ delta=litellm.utils.Delta(content="[email protected] and SSN is "),+ finish_reason=None+ )+ ],+ created=1234567890,+ model="gpt-4o",+ object="chat.completion.chunk"+ ),+ ModelResponseStream(+ id="test-id",+ choices=[+ litellm.utils.StreamingChoices(+ index=0,+ delta=litellm.utils.Delta(content="123-45-6789"),+ finish_reason="stop"+ )+ ],+ created=1234567890,+ model="gpt-4o",+ object="chat.completion.chunk"+ )+ ]+ for chunk in chunks:+ yield chunk++ request_data = {+ "model": "gpt-4o",+ "messages": [+ {"role": "user", "content": "What's your email and SSN?"},+ ],+ "stream": True,+ }++ # Patch the async_handler.post method+ with patch.object(guardrail.async_handler, 'post', new_callable=AsyncMock) as mock_post:+ mock_post.return_value = mock_bedrock_response++ # Call the streaming hook+ masked_stream = guardrail.async_post_call_streaming_iterator_hook(+ user_api_key_dict=mock_user_api_key_dict,+ response=mock_streaming_response(),+ request_data=request_data+ )++ # Collect all chunks from the masked stream+ masked_chunks = []+ async for chunk in masked_stream:+ masked_chunks.append(chunk)++ # Verify that we got chunks back+ assert len(masked_chunks) > 0++ # Reconstruct the full response from chunks to verify masking+ full_content = ""+ for chunk in masked_chunks:+ if hasattr(chunk, 'choices') and chunk.choices:+ if hasattr(chunk.choices[0], 'delta') and chunk.choices[0].delta:+ if hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content:+ full_content += chunk.choices[0].delta.content++ # Verify that the reconstructed content contains the masked PII+ assert "Sure! My email is {EMAIL} and SSN is {US_SSN}" == full_content+ print("✓ Streaming response PII masking test passed")-\ No newline at end of file