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(bedrock_guardrails): select latest user message by original role in apply_guardrail (#30482)
michelligabriele5a47948a3ac3
diff --git a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.pyindex 4a550cb73a4..19055f1083a 100644--- a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py+++ b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py@@ -105,6 +105,19 @@ class GuardrailMessageFilterResult(NamedTuple):target_indices: Optional[List[int]]+class ApplyGuardrailMessageSelection(NamedTuple):+ """Messages selected for an apply_guardrail scan + write-back metadata."""++ filtered_messages: Optional[list[AllMessageValues]]+ # Slice of the flat `texts` list actually scanned (offset, length),+ # used to write masked content back to the right positions. None = whole list.+ scanned_slice: Optional[tuple[int, int]]+ # True when messages were selected by their original role.+ scanned_role_subset: bool+ # True when there is nothing to scan (e.g. no user-role message).+ skip_scan: bool = False++def _redact_pii_matches(response_json: dict) -> dict:"""Redact match-like fields from a Bedrock ApplyGuardrail JSON payload.@@ -370,6 +383,164 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):return indexreturn None+ @staticmethod+ def _count_message_texts(message: AllMessageValues) -> int:+ """Count the text segments the guardrail translation layer extracts from a message."""+ content = message.get("content")+ if isinstance(content, str):+ return 1+ if isinstance(content, list):+ return sum(+ 1+ for item in content+ if isinstance(item, dict) and item.get("text") is not None+ )+ return 0++ def _locate_message_texts_slice(+ self,+ structured_messages: list[AllMessageValues],+ target_index: int,+ texts: list[str],+ ) -> Optional[tuple[int, int]]:+ """+ Map one message's text segments to their (offset, length) slice in the+ flat `texts` list built by the guardrail translation handler.++ Returns None when the reconstruction does not line up with `texts`+ (the caller must then avoid positional write-back).+ """+ offset = 0+ total = 0+ target_count = 0+ for index, message in enumerate(structured_messages):+ count = self._count_message_texts(message)+ if index < target_index:+ offset += count+ elif index == target_index:+ target_count = count+ total += count+ if total != len(texts) or target_count == 0:+ return None+ return offset, target_count++ def _select_messages_for_apply_guardrail(+ self,+ texts: list[str],+ inputs: "GenericGuardrailAPIInputs",+ request_data: dict,+ input_type: Literal["request", "response"],+ ) -> ApplyGuardrailMessageSelection:+ """+ Decide which messages an apply_guardrail scan should cover.++ With ``experimental_use_latest_role_message_only`` enabled, request+ scans must select by the ORIGINAL message roles. The flat `texts` list+ has no role information, and wrapping it in role="user" mock messages+ makes the latest-user filter degenerate to "latest text of any role",+ leaking tool/assistant content to the INPUT scan+ (https://github.com/BerriAI/litellm/issues/23476).+ """+ mock_messages: list[AllMessageValues] = [+ ChatCompletionUserMessage(role="user", content=text) for text in texts+ ]++ if self.experimental_use_latest_role_message_only is not True:+ return ApplyGuardrailMessageSelection(+ filtered_messages=mock_messages,+ scanned_slice=None,+ scanned_role_subset=False,+ )++ # Prefer inputs["structured_messages"]: it is built alongside `texts` by+ # the translation handler and stays aligned with it even when+ # skip_system_message_in_guardrail / skip_tool_message_in_guardrail drop+ # messages. The fallback to request_data["messages"] is the *unfiltered*+ # list, so it only lines up with `texts` when no skip flags are active.+ # When a skip flag is set and we land on this fallback (direct+ # apply_guardrail callers with no structured_messages),+ # _locate_message_texts_slice will detect the length mismatch and return+ # None, and the write-back guard below safely skips masking rather than+ # corrupting positions.+ structured_messages = cast(+ Optional[list[AllMessageValues]],+ inputs.get("structured_messages") or request_data.get("messages"),+ )+ if input_type != "request" or not structured_messages:+ # No role information available (e.g. raw-text callers like+ # /guardrails/apply_guardrail) — keep the legacy behavior of+ # scanning the latest text only.+ filter_result = self._prepare_guardrail_messages_for_role(+ messages=mock_messages+ )+ return ApplyGuardrailMessageSelection(+ filtered_messages=filter_result.payload_messages or mock_messages,+ scanned_slice=None,+ scanned_role_subset=False,+ )++ latest_user_index = self._find_latest_message_index(+ structured_messages, target_role="user"+ )+ if latest_user_index is None:+ verbose_proxy_logger.debug(+ "Bedrock Guardrail: no user-role message in request, skipping INPUT scan"+ )+ return ApplyGuardrailMessageSelection(None, None, True, skip_scan=True)++ selected_message = structured_messages[latest_user_index]+ if self._count_message_texts(selected_message) == 0:+ verbose_proxy_logger.debug(+ "Bedrock Guardrail: latest user message has no text content, skipping INPUT scan"+ )+ return ApplyGuardrailMessageSelection(None, None, True, skip_scan=True)++ return ApplyGuardrailMessageSelection(+ filtered_messages=[selected_message],+ scanned_slice=self._locate_message_texts_slice(+ structured_messages=structured_messages,+ target_index=latest_user_index,+ texts=texts,+ ),+ scanned_role_subset=True,+ )++ def _merge_masked_texts(+ self,+ masked_texts: list,+ texts: list,+ scanned_slice: Optional[tuple[int, int]],+ scanned_role_subset: bool,+ ) -> list:+ """+ Reconcile the guardrail's masked output with the flat `texts` list.++ - No masked output: keep the originals (guardrail allowed content as-is).+ - A slice was scanned: write masked content back to those positions only,+ keeping the list aligned with the caller's message↔text mappings.+ - A role-selected subset was scanned but could not be mapped back to+ flat-text positions (scanned_slice is None): keep the originals rather+ than misapply masked content to the wrong message. Guarding on+ scanned_slice rather than a length comparison also covers the case+ where the masked subset happens to match len(texts) (e.g. both length+ 1).+ - Otherwise (whole list scanned): use the masked output as-is.+ """+ if not masked_texts:+ return texts+ if scanned_slice is not None:+ offset, length = scanned_slice+ merged_texts = list(texts)+ for masked_index, masked_text in enumerate(masked_texts[:length]):+ merged_texts[offset + masked_index] = masked_text+ return merged_texts+ if scanned_role_subset:+ verbose_proxy_logger.warning(+ "Bedrock Guardrail: could not align masked texts with request texts, skipping masking write-back"+ )+ return texts+ return masked_texts+def _merge_filtered_messages(self,original_messages: Optional[List[AllMessageValues]],@@ -1639,15 +1810,17 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):masked_texts = []- mock_messages: List[AllMessageValues] = [- ChatCompletionUserMessage(role="user", content=text) for text in texts- ]-- request_messages = mock_messages- filter_result = self._prepare_guardrail_messages_for_role(- messages=request_messages+ selection = self._select_messages_for_apply_guardrail(+ texts=texts,+ inputs=inputs,+ request_data=request_data,+ input_type=input_type,)- filtered_messages = filter_result.payload_messages or mock_messages+ if selection.skip_scan:+ return inputs+ filtered_messages = selection.filtered_messages+ scanned_slice = selection.scanned_slice+ scanned_role_subset = selection.scanned_role_subset# Bedrock will throw an error if there is no text to processif filtered_messages:@@ -1715,10 +1888,14 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):masked_text = str(text_content)masked_texts.append(masked_text)- # If no output/outputs were provided, use the original texts- # This happens when the guardrail allows content without modification- if not masked_texts:- masked_texts = texts+ # Reconcile masked output with the flat `texts` list (write back to+ # the scanned slice only, or skip if it can't be aligned).+ masked_texts = self._merge_masked_texts(+ masked_texts=masked_texts,+ texts=texts,+ scanned_slice=scanned_slice,+ scanned_role_subset=scanned_role_subset,+ )verbose_proxy_logger.debug("Bedrock Guardrail: Successfully applied guardrail"diff --git a/tests/enterprise/litellm_enterprise/proxy/guardrails/test_bedrock_apply_guardrail.py b/tests/enterprise/litellm_enterprise/proxy/guardrails/test_bedrock_apply_guardrail.pyindex d1caf398540..87c5e3bf2a9 100644--- a/tests/enterprise/litellm_enterprise/proxy/guardrails/test_bedrock_apply_guardrail.py+++ b/tests/enterprise/litellm_enterprise/proxy/guardrails/test_bedrock_apply_guardrail.py@@ -358,3 +358,279 @@ async def test_bedrock_apply_guardrail_blocked_with_disable_exception_on_block())assert "unable to be answered" in str(exc_info.value.message)+++async def test_bedrock_apply_guardrail_does_not_leak_tool_content_with_flag():+ """+ Regression test for issue #23476: with+ experimental_use_latest_role_message_only enabled, a conversation ending in+ a tool message (agentic tool-calling loop) must scan the latest USER+ message — not the tool result.+ """+ guardrail = BedrockGuardrail(+ guardrail_name="test-bedrock-guard",+ guardrailIdentifier="test-guard-id",+ guardrailVersion="DRAFT",+ experimental_use_latest_role_message_only=True,+ )++ structured_messages = [+ {"role": "system", "content": "rules"},+ {"role": "user", "content": "what is the weather?"},+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [+ {+ "id": "call_1",+ "type": "function",+ "function": {"name": "get_weather", "arguments": "{}"},+ }+ ],+ },+ {"role": "tool", "tool_call_id": "call_1", "content": "TOOL OUTPUT SECRET"},+ ]+ # Flat texts as built by the unified guardrail translation handler+ texts = ["rules", "what is the weather?", "TOOL OUTPUT SECRET"]++ with patch.object(+ guardrail, "make_bedrock_api_request", new_callable=AsyncMock+ ) as mock_api:+ mock_api.return_value = {"action": "NONE", "output": []}++ await guardrail.apply_guardrail(+ inputs={"texts": texts, "structured_messages": structured_messages},+ request_data={"messages": structured_messages},+ input_type="request",+ )++ assert mock_api.called+ _, kwargs = mock_api.call_args+ # The latest USER message is scanned — not the trailing tool message+ assert kwargs["messages"] == [structured_messages[1]]+++async def test_bedrock_apply_guardrail_skips_scan_when_no_user_message_with_flag():+ """With the flag on and no user-role message in the request, there is nothing+ to scan as INPUT — the guardrail must not be called."""+ guardrail = BedrockGuardrail(+ guardrail_name="test-bedrock-guard",+ guardrailIdentifier="test-guard-id",+ guardrailVersion="DRAFT",+ experimental_use_latest_role_message_only=True,+ )++ structured_messages = [+ {"role": "assistant", "content": "assistant text"},+ {"role": "tool", "tool_call_id": "call_1", "content": "tool text"},+ ]+ texts = ["assistant text", "tool text"]++ with patch.object(+ guardrail, "make_bedrock_api_request", new_callable=AsyncMock+ ) as mock_api:+ result = await guardrail.apply_guardrail(+ inputs={"texts": texts, "structured_messages": structured_messages},+ request_data={"messages": structured_messages},+ input_type="request",+ )++ assert not mock_api.called+ assert result.get("texts") == texts+++async def test_bedrock_apply_guardrail_masking_written_back_to_correct_position():+ """When only the latest user message is scanned, masked content must be+ written back to that message's position in the flat texts list — other+ entries stay untouched."""+ guardrail = BedrockGuardrail(+ guardrail_name="test-bedrock-guard",+ guardrailIdentifier="test-guard-id",+ guardrailVersion="DRAFT",+ experimental_use_latest_role_message_only=True,+ )++ structured_messages = [+ {"role": "system", "content": "rules"},+ {"role": "user", "content": "my SSN is 123-45-6789"},+ {"role": "assistant", "content": "assistant text"},+ {"role": "tool", "tool_call_id": "call_1", "content": "tool text"},+ ]+ texts = ["rules", "my SSN is 123-45-6789", "assistant text", "tool text"]++ with patch.object(+ guardrail, "make_bedrock_api_request", new_callable=AsyncMock+ ) as mock_api:+ mock_api.return_value = {+ "action": "GUARDRAIL_INTERVENED",+ "output": [{"text": "my SSN is {SSN}"}],+ }++ guardrailed_inputs = await guardrail.apply_guardrail(+ inputs={"texts": texts, "structured_messages": structured_messages},+ request_data={"messages": structured_messages},+ input_type="request",+ )++ assert guardrailed_inputs.get("texts") == [+ "rules",+ "my SSN is {SSN}",+ "assistant text",+ "tool text",+ ]+++async def test_bedrock_apply_guardrail_skips_writeback_when_slice_unresolved_and_lengths_match():+ """Regression: a role-subset scan that can't be mapped back to flat-text+ positions (scanned_slice is None) must NOT write masked content back, even+ when the masked output happens to match len(texts) (e.g. both length 1).++ Here structured_messages carries two user texts but the flat `texts` list+ holds only one entry, so _locate_message_texts_slice returns None. The+ guardrail still scans the latest user message and returns a single masked+ text; a length-only guard would let that mask clobber the unrelated single+ `texts` entry. The slice-based guard keeps the original text instead.+ """+ guardrail = BedrockGuardrail(+ guardrail_name="test-bedrock-guard",+ guardrailIdentifier="test-guard-id",+ guardrailVersion="DRAFT",+ experimental_use_latest_role_message_only=True,+ )++ structured_messages = [+ {"role": "user", "content": "first user text"},+ {"role": "user", "content": "second user text"},+ ]+ # Flat texts is out of sync with structured_messages (one entry vs two+ # user texts) -> slice cannot be resolved.+ texts = ["unrelated flat text"]++ with patch.object(+ guardrail, "make_bedrock_api_request", new_callable=AsyncMock+ ) as mock_api:+ mock_api.return_value = {+ "action": "GUARDRAIL_INTERVENED",+ "output": [{"text": "[MASKED]"}],+ }++ guardrailed_inputs = await guardrail.apply_guardrail(+ inputs={"texts": texts, "structured_messages": structured_messages},+ request_data={"messages": structured_messages},+ input_type="request",+ )++ # The scan ran on the latest user message...+ assert mock_api.called+ # ...but because the slice was unresolved, the original flat text is kept+ # rather than clobbered by the single masked output.+ assert guardrailed_inputs.get("texts") == ["unrelated flat text"]+++async def test_bedrock_masking_writes_back_to_user_message_through_handler():+ """End-to-end through the unified translation handler (issue #23476).++ `apply_guardrail` only sees a flat `texts` list; the handler is what+ flattens messages into that list and re-inflates the guardrailed texts back+ onto messages — positionally, by the order they were extracted. This test+ exercises that whole contract with a real+ OpenAIChatCompletionsHandler.process_input_messages (only the network call+ is mocked), so a divergence between the handler's flattening and+ apply_guardrail's slice reconstruction would surface as masked content+ landing on the wrong message.++ With experimental_use_latest_role_message_only enabled and a conversation+ ending in a tool message, only the latest USER message is scanned; the+ returned mask must overwrite that user message and leave system / assistant+ / tool content untouched.+ """+ from litellm.llms.openai.chat.guardrail_translation.handler import (+ OpenAIChatCompletionsHandler,+ )++ guardrail = BedrockGuardrail(+ guardrail_name="test-bedrock-guard",+ guardrailIdentifier="test-guard-id",+ guardrailVersion="DRAFT",+ experimental_use_latest_role_message_only=True,+ )++ data = {+ "model": "test-model",+ "messages": [+ {"role": "system", "content": "SYSTEM rules"},+ {"role": "user", "content": "my SSN is 123-45-6789"},+ {"role": "assistant", "content": "ASSISTANT let me check"},+ {"role": "tool", "tool_call_id": "call_1", "content": "TOOL secret output"},+ ],+ }++ async def _fake_api(*args, **kwargs):+ # Mask every text actually scanned (the handler/fix should only send the+ # latest user message), one masked output per scanned message.+ scanned = kwargs.get("messages") or []+ return {+ "action": "GUARDRAIL_INTERVENED",+ "output": [{"text": "[MASKED]"} for _ in scanned],+ }++ with patch.object(+ guardrail, "make_bedrock_api_request", new_callable=AsyncMock+ ) as mock_api:+ mock_api.side_effect = _fake_api++ result = await OpenAIChatCompletionsHandler().process_input_messages(+ data=data, guardrail_to_apply=guardrail+ )++ # Only the latest user message was scanned...+ assert mock_api.called+ _, kwargs = mock_api.call_args+ assert kwargs["messages"] == [data["messages"][1]]++ # ...and the mask landed on the user message only — nothing else clobbered.+ msgs = result["messages"]+ assert msgs[0]["content"] == "SYSTEM rules"+ assert msgs[1]["content"] == "[MASKED]"+ assert msgs[2]["content"] == "ASSISTANT let me check"+ assert msgs[3]["content"] == "TOOL secret output"+++async def test_bedrock_handler_leaves_messages_untouched_when_no_user_message():+ """Through the real handler: no user-role message → INPUT scan skipped and+ every message is forwarded unchanged (no masking, no leak)."""+ from litellm.llms.openai.chat.guardrail_translation.handler import (+ OpenAIChatCompletionsHandler,+ )++ guardrail = BedrockGuardrail(+ guardrail_name="test-bedrock-guard",+ guardrailIdentifier="test-guard-id",+ guardrailVersion="DRAFT",+ experimental_use_latest_role_message_only=True,+ )++ data = {+ "model": "test-model",+ "messages": [+ {"role": "assistant", "content": "ASSISTANT text"},+ {"role": "tool", "tool_call_id": "call_1", "content": "TOOL output"},+ ],+ }++ with patch.object(+ guardrail, "make_bedrock_api_request", new_callable=AsyncMock+ ) as mock_api:+ result = await OpenAIChatCompletionsHandler().process_input_messages(+ data=data, guardrail_to_apply=guardrail+ )++ assert not mock_api.called+ assert result["messages"][0]["content"] == "ASSISTANT text"+ assert result["messages"][1]["content"] == "TOOL output"