Skip to content

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]

feat(proxy): enforce key/team guardrails on bedrock passthrough routes (#30194)

Sameer Kankute7519e37d267f
diff --git a/litellm/llms/bedrock/passthrough/guardrail_translation/__init__.py b/litellm/llms/bedrock/passthrough/guardrail_translation/__init__.py
new file mode 100644
index 00000000000..e38044afb36
--- /dev/null
+++ b/litellm/llms/bedrock/passthrough/guardrail_translation/__init__.py
@@ -0,0 +1,5 @@
+from litellm.llms.bedrock.passthrough.guardrail_translation.handler import (
+ BedrockPassthroughGuardrailHandler,
+)
+
+__all__ = ["BedrockPassthroughGuardrailHandler"]
diff --git a/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py b/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py
new file mode 100644
index 00000000000..2d6bdb5298a
--- /dev/null
+++ b/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py
@@ -0,0 +1,507 @@
+from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union
+
+from litellm._logging import verbose_proxy_logger
+from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
+from litellm.llms.base_llm.guardrail_translation.utils import (
+ effective_skip_system_message_for_guardrail,
+ effective_skip_tool_message_for_guardrail,
+)
+from litellm.types.utils import GenericGuardrailAPIInputs
+
+if TYPE_CHECKING:
+ from litellm.integrations.custom_guardrail import CustomGuardrail
+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+ from litellm.proxy._types import UserAPIKeyAuth
+ from litellm.proxy.utils import ProxyLogging
+
+_CONVERSE_ACTIONS = frozenset({"converse", "converse-stream"})
+_EVENT_STREAM_CONTENT_TYPE = "vnd.amazon.eventstream"
+_EVENT_STREAM_MEDIA_TYPE = "application/vnd.amazon.eventstream"
+
+
+def _is_converse_endpoint(endpoint: str) -> bool:
+ parts = endpoint.rstrip("/").split("/")
+ return bool(parts) and parts[-1] in _CONVERSE_ACTIONS
+
+
+def _generic_passthrough_handler() -> BaseTranslation:
+ """
+ Fallback for non-Converse Bedrock routes (e.g. invoke). The generic
+ handler scans the full request/response payload so blocking guardrails
+ still run, matching how other passthrough providers are guarded.
+ """
+ from litellm.llms.pass_through.guardrail_translation.handler import (
+ PassThroughEndpointHandler,
+ )
+
+ return PassThroughEndpointHandler()
+
+
+_StringHolder = Tuple[Any, Union[str, int]]
+
+
+def _collect_strings(node: Any, holders: List[_StringHolder]) -> None:
+ """
+ Record a (container, key) holder for every non-empty string value nested
+ under an arbitrary JSON node, so prompt content a caller hides in fields
+ like ``toolUse.input`` or ``toolResult.content[].json`` is still scanned
+ and can be written back in place. Iterative to avoid unbounded recursion
+ on deeply nested payloads.
+ """
+ stack: List[Any] = [node]
+ while stack:
+ current = stack.pop()
+ if isinstance(current, dict):
+ for key, value in current.items():
+ if isinstance(value, str):
+ if value:
+ holders.append((current, key))
+ else:
+ stack.append(value)
+ elif isinstance(current, list):
+ for index, value in enumerate(current):
+ if isinstance(value, str):
+ if value:
+ holders.append((current, index))
+ else:
+ stack.append(value)
+
+
+def _collect_block_text(block: dict, holders: List[_StringHolder]) -> None:
+ text = block.get("text")
+ if isinstance(text, str) and text:
+ holders.append((block, "text"))
+
+
+def _extract_converse_texts(
+ body: dict,
+ skip_system: bool,
+ skip_tool: bool,
+) -> Tuple[List[str], List[_StringHolder]]:
+ """
+ Walk a Bedrock Converse request body and collect text content.
+
+ Returns (texts, holders) where each holder is the (container, key) pair
+ that owns the extracted string, so write-back mutates it in place. Besides
+ top-level ``text`` blocks this scans the arbitrary-JSON fields a caller can
+ hide prompt content in -- ``toolUse.input`` and
+ ``toolResult.content[].json`` (alongside ``toolResult.content[].text``) --
+ as well as the request-level fields still forwarded to Bedrock that a caller
+ can route blocked content through: ``toolConfig.tools`` (tool names,
+ descriptions and input schemas) and ``additionalModelRequestFields``. Tool
+ message blocks are skipped when tool messages are excluded, but tool
+ definitions are always scanned to match the chat-completions guardrail path.
+ """
+ holders: List[_StringHolder] = []
+
+ if not skip_system:
+ for block in body.get("system") or []:
+ if isinstance(block, dict):
+ _collect_block_text(block, holders)
+
+ for message in body.get("messages") or []:
+ if not isinstance(message, dict):
+ continue
+ for block in message.get("content") or []:
+ if not isinstance(block, dict):
+ continue
+ if skip_tool and ("toolUse" in block or "toolResult" in block):
+ continue
+ _collect_block_text(block, holders)
+ tool_use = block.get("toolUse")
+ if isinstance(tool_use, dict):
+ _collect_strings(tool_use.get("input"), holders)
+ tool_result = block.get("toolResult")
+ if isinstance(tool_result, dict):
+ for inner in tool_result.get("content") or []:
+ if isinstance(inner, dict):
+ _collect_block_text(inner, holders)
+ _collect_strings(inner.get("json"), holders)
+
+ tool_config = body.get("toolConfig")
+ if isinstance(tool_config, dict):
+ _collect_strings(tool_config.get("tools"), holders)
+
+ _collect_strings(body.get("additionalModelRequestFields"), holders)
+
+ texts = [container[key] for container, key in holders]
+ return texts, holders
+
+
+def _extract_converse_output_texts(
+ content_blocks: List[Any],
+) -> Tuple[List[str], List[_StringHolder]]:
+ """
+ Collect user-visible text from Bedrock Converse output content blocks.
+
+ Covers ``text`` blocks plus the other content-bearing fields a model can
+ emit -- ``toolUse.input``, ``reasoningContent.reasoningText.text`` and
+ ``citationsContent.content[].text`` -- while leaving structural values such
+ as reasoning signatures and citation sources untouched.
+ """
+ holders: List[_StringHolder] = []
+ for block in content_blocks:
+ if not isinstance(block, dict):
+ continue
+ _collect_block_text(block, holders)
+ tool_use = block.get("toolUse")
+ if isinstance(tool_use, dict):
+ _collect_strings(tool_use.get("input"), holders)
+ reasoning = block.get("reasoningContent")
+ if isinstance(reasoning, dict):
+ reasoning_text = reasoning.get("reasoningText")
+ if isinstance(reasoning_text, dict):
+ _collect_block_text(reasoning_text, holders)
+ citations = block.get("citationsContent")
+ if isinstance(citations, dict):
+ for cited in citations.get("content") or []:
+ if isinstance(cited, dict):
+ _collect_block_text(cited, holders)
+ texts = [container[key] for container, key in holders]
+ return texts, holders
+
+
+def _write_back_texts(
+ guardrailed_texts: List[str],
+ holders: List[_StringHolder],
+) -> None:
+ if len(guardrailed_texts) < len(holders):
+ verbose_proxy_logger.warning(
+ "BedrockPassthroughGuardrailHandler: guardrail returned %d texts for %d "
+ "extracted fields; the unreturned fields keep their original text",
+ len(guardrailed_texts),
+ len(holders),
+ )
+ for idx, (container, key) in enumerate(holders):
+ if idx >= len(guardrailed_texts):
+ break
+ container[key] = guardrailed_texts[idx]
+
+
+_DeltaHolder = Tuple[Any, Any, Union[str, int]]
+
+
+def _collect_stream_delta_text_holders(delta: Any) -> List[_DeltaHolder]:
+ """
+ Collect the user-visible text strings a Bedrock Converse ``contentBlockDelta``
+ can carry, matching the coverage of the non-streaming output handler.
+
+ Each holder is ``(group_key, container, key)`` where ``container[key]`` is the
+ text. ``group_key`` ties together fragments that belong to the same logical
+ stream (e.g. a single mask token split across frames) so they are
+ concatenated before guardrailing and redistributed afterwards. Structural
+ values such as reasoning signatures, redacted reasoning and citation sources
+ are left out so they are never rewritten.
+ """
+ holders: List[_DeltaHolder] = []
+ if not isinstance(delta, dict):
+ return holders
+ if isinstance(delta.get("text"), str):
+ holders.append(("text", delta, "text"))
+ tool_use = delta.get("toolUse")
+ if isinstance(tool_use, dict) and isinstance(tool_use.get("input"), str):
+ holders.append(("tool", tool_use, "input"))
+ reasoning = delta.get("reasoningContent")
+ if isinstance(reasoning, dict) and isinstance(reasoning.get("text"), str):
+ holders.append(("reasoning", reasoning, "text"))
+ citations = delta.get("citationsContent")
+ if isinstance(citations, dict):
+ for index, cited in enumerate(citations.get("content") or []):
+ if isinstance(cited, dict) and isinstance(cited.get("text"), str):
+ holders.append((("citation", index), cited, "text"))
+ return holders
+
+
+class BedrockPassthroughGuardrailHandler(BaseTranslation):
+ @staticmethod
+ def is_event_stream_content_type(content_type: str) -> bool:
+ return _EVENT_STREAM_CONTENT_TYPE in content_type
+
+ @staticmethod
+ def event_stream_media_type() -> str:
+ return _EVENT_STREAM_MEDIA_TYPE
+
+ @staticmethod
+ def event_stream_endpoint_is_de_anonymizable(endpoint: str) -> bool:
+ return _is_converse_endpoint(endpoint)
+
+ @staticmethod
+ async def de_anonymize_event_stream( # noqa: PLR0915
+ body_bytes: bytes,
+ proxy_logging_obj: "ProxyLogging",
+ user_api_key_dict: "UserAPIKeyAuth",
+ data: dict,
+ ) -> bytes:
+ import json as _json
+ import struct
+ from binascii import crc32 as esm_crc32
+
+ from botocore.eventstream import EventStreamBuffer
+
+ frames: list[dict] = []
+ offset = 0
+
+ while offset + 16 <= len(body_bytes):
+ total_length = struct.unpack("!I", body_bytes[offset : offset + 4])[0]
+ if total_length < 16 or offset + total_length > len(body_bytes):
+ break
+ frame_raw = body_bytes[offset : offset + total_length]
+ offset += total_length
+
+ try:
+ buf = EventStreamBuffer()
+ buf.add_data(frame_raw)
+ msg = next(iter(buf))
+ event_type = msg.headers.get(":event-type")
+ payload_bytes = msg.payload
+ except Exception as e:
+ verbose_proxy_logger.debug(
+ "BedrockPassthroughGuardrailHandler: could not decode event-stream "
+ "frame, forwarding it unmodified: %s",
+ e,
+ )
+ frames.append({"raw": frame_raw, "texts": []})
+ continue
+
+ texts: List[Tuple[Any, str]] = []
+ if event_type == "contentBlockDelta":
+ try:
+ payload_dict = _json.loads(payload_bytes)
+ texts = [
+ (group_key, container[key])
+ for group_key, container, key in _collect_stream_delta_text_holders(
+ payload_dict.get("delta")
+ )
+ ]
+ except Exception as e:
+ verbose_proxy_logger.debug(
+ "BedrockPassthroughGuardrailHandler: could not parse "
+ "contentBlockDelta payload, forwarding frame unmodified: %s",
+ e,
+ )
+
+ frames.append({"raw": frame_raw, "texts": texts})
+
+ trailing_bytes = body_bytes[offset:]
+
+ group_order: List[Any] = []
+ group_members: dict[Any, list[Tuple[int, int]]] = {}
+ group_texts: dict[Any, list[str]] = {}
+ for frame_idx, frame in enumerate(frames):
+ for local_idx, (group_key, text) in enumerate(frame["texts"]):
+ if group_key not in group_members:
+ group_members[group_key] = []
+ group_texts[group_key] = []
+ group_order.append(group_key)
+ group_members[group_key].append((frame_idx, local_idx))
+ group_texts[group_key].append(text)
+
+ active_groups = [gk for gk in group_order if "".join(group_texts[gk])]
+ if not active_groups:
+ return body_bytes
+
+ synthetic_response: dict = {
+ "output": {
+ "message": {
+ "role": "assistant",
+ "content": [
+ {"text": "".join(group_texts[gk])} for gk in active_groups
+ ],
+ }
+ },
+ "stopReason": "end_turn",
+ }
+
+ processed = await proxy_logging_obj.post_call_success_hook(
+ data=data,
+ user_api_key_dict=user_api_key_dict,
+ response=synthetic_response, # type: ignore[arg-type]
+ )
+
+ if not isinstance(processed, dict):
+ verbose_proxy_logger.debug(
+ "BedrockPassthroughGuardrailHandler: post_call_success_hook returned %s, "
+ "leaving event stream unmodified",
+ type(processed).__name__,
+ )
+ return body_bytes
+
+ try:
+ processed_blocks = processed["output"]["message"]["content"] # type: ignore[index]
+ de_anonymized_texts = [
+ processed_blocks[i]["text"] for i in range(len(active_groups))
+ ]
+ except (KeyError, IndexError, TypeError):
+ return body_bytes
+
+ new_text_map: dict[Tuple[int, int], str] = {}
+ for group_key, de_anonymized_text in zip(active_groups, de_anonymized_texts):
+ members = group_members[group_key]
+ orig_texts = group_texts[group_key]
+ total_orig = sum(len(t) for t in orig_texts) or 1
+ de_anon_len = len(de_anonymized_text)
+ pos = 0
+ for k, member in enumerate(members):
+ if k == len(members) - 1:
+ new_text_map[member] = de_anonymized_text[pos:]
+ else:
+ end = pos + round(de_anon_len * len(orig_texts[k]) / total_orig)
+ new_text_map[member] = de_anonymized_text[pos:end]
+ pos = end
+
+ result_parts: list[bytes] = []
+
+ for frame_idx, frame in enumerate(frames):
+ if not frame["texts"]:
+ result_parts.append(frame["raw"])
+ continue
+
+ frame_raw = frame["raw"]
+ orig_total = struct.unpack("!I", frame_raw[0:4])[0]
+ orig_hdrs_len = struct.unpack("!I", frame_raw[4:8])[0]
+ headers_bytes = frame_raw[12 : 12 + orig_hdrs_len]
+
+ try:
+ payload_dict = _json.loads(
+ frame_raw[12 + orig_hdrs_len : orig_total - 4]
+ )
+ for local_idx, (_, container, key) in enumerate(
+ _collect_stream_delta_text_holders(payload_dict.get("delta"))
+ ):
+ new_text = new_text_map.get((frame_idx, local_idx))
+ if new_text is not None:
+ container[key] = new_text
+ new_payload = _json.dumps(payload_dict, separators=(",", ":")).encode()
+ except Exception:
+ result_parts.append(frame_raw)
+ continue
+
+ new_total = 12 + orig_hdrs_len + len(new_payload) + 4
+ prelude = struct.pack("!II", new_total, orig_hdrs_len)
+ prelude_crc_val = esm_crc32(prelude) & 0xFFFFFFFF
+ prelude_crc_b = struct.pack("!I", prelude_crc_val)
+ part_for_msg_crc = prelude_crc_b + headers_bytes + new_payload
+ msg_crc_val = esm_crc32(part_for_msg_crc, prelude_crc_val) & 0xFFFFFFFF
+ msg_crc_b = struct.pack("!I", msg_crc_val)
+
+ result_parts.append(
+ prelude + prelude_crc_b + headers_bytes + new_payload + msg_crc_b
+ )
+
+ result_parts.append(trailing_bytes)
+ return b"".join(result_parts)
+
+ async def process_input_messages(
+ self,
+ data: dict,
+ guardrail_to_apply: "CustomGuardrail",
+ litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None,
+ ) -> Any:
+ endpoint = data.get("endpoint", "")
+ body = data.get("data")
+
+ if not _is_converse_endpoint(endpoint):
+ return await _generic_passthrough_handler().process_input_messages(
+ data=data,
+ guardrail_to_apply=guardrail_to_apply,
+ litellm_logging_obj=litellm_logging_obj,
+ )
+
+ if not isinstance(body, dict) or not isinstance(body.get("messages"), list):
+ return data
+
+ skip_system = effective_skip_system_message_for_guardrail(guardrail_to_apply)
+ skip_tool = effective_skip_tool_message_for_guardrail(guardrail_to_apply)
+
+ texts, holders = _extract_converse_texts(body, skip_system, skip_tool)
+
+ if not texts:
+ return data
+
+ inputs = GenericGuardrailAPIInputs(texts=texts)
+ model = data.get("model")
+ if model:
+ inputs["model"] = model
+
+ guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
+ inputs=inputs,
+ request_data=data,
+ input_type="request",
+ logging_obj=litellm_logging_obj,
+ )
+
+ guardrailed_texts = guardrailed_inputs.get("texts", [])
+ if guardrailed_texts:
+ _write_back_texts(guardrailed_texts, holders)
+
+ return data
+
+ async def process_output_response(
+ self,
+ response: Any,
+ guardrail_to_apply: "CustomGuardrail",
+ litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None,
+ user_api_key_dict: Optional[Any] = None,
+ request_data: Optional[dict] = None,
+ ) -> Any:
+ endpoint = (request_data or {}).get("endpoint", "")
+ if endpoint and not _is_converse_endpoint(endpoint):
+ return await _generic_passthrough_handler().process_output_response(
+ response=response,
+ guardrail_to_apply=guardrail_to_apply,
+ litellm_logging_obj=litellm_logging_obj,
+ user_api_key_dict=user_api_key_dict,
+ request_data=request_data,
+ )
+
+ if not isinstance(response, dict):
+ return response
+
+ output_message = (
+ response.get("output", {}).get("message", {})
+ if isinstance(response.get("output"), dict)
+ else {}
+ )
+ content_blocks = (
+ output_message.get("content") if isinstance(output_message, dict) else None
+ )
+
+ if not isinstance(content_blocks, list):
+ return response
+
+ texts, holders = _extract_converse_output_texts(content_blocks)
+
+ if not texts:
+ return response
+
+ effective_request_data = request_data or {}
+ if (
+ "litellm_metadata" not in effective_request_data
+ and user_api_key_dict is not None
+ ):
+ user_metadata = self.transform_user_api_key_dict_to_metadata(
+ user_api_key_dict
+ )
+ if user_metadata:
+ effective_request_data = {
+ **effective_request_data,
+ "litellm_metadata": user_metadata,
+ }
+
+ inputs = GenericGuardrailAPIInputs(texts=texts)
+ model = effective_request_data.get("model") if effective_request_data else None
+ if model:
+ inputs["model"] = model
+
+ guardrailed_inputs = await guardrail_to_apply.apply_guardrail(
+ inputs=inputs,
+ request_data=effective_request_data,
+ input_type="response",
+ logging_obj=litellm_logging_obj,
+ )
+
+ guardrailed_texts = guardrailed_inputs.get("texts", [])
+ if guardrailed_texts:
+ _write_back_texts(guardrailed_texts, holders)
+
+ return response
diff --git a/litellm/llms/pass_through/guardrail_translation/__init__.py b/litellm/llms/pass_through/guardrail_translation/__init__.py
index db69c8e378a..46fea242c13 100644
--- a/litellm/llms/pass_through/guardrail_translation/__init__.py
+++ b/litellm/llms/pass_through/guardrail_translation/__init__.py
@@ -1,15 +1,18 @@
"""Pass-Through Endpoint guardrail translation handler."""
from litellm.llms.pass_through.guardrail_translation.handler import (
+ LlmPassthroughRouteHandler,
PassThroughEndpointHandler,
)
from litellm.types.utils import CallTypes
guardrail_translation_mappings = {
CallTypes.pass_through: PassThroughEndpointHandler,
+ CallTypes.allm_passthrough_route: LlmPassthroughRouteHandler,
}
__all__ = [
"guardrail_translation_mappings",
+ "LlmPassthroughRouteHandler",
"PassThroughEndpointHandler",
]
diff --git a/litellm/llms/pass_through/guardrail_translation/handler.py b/litellm/llms/pass_through/guardrail_translation/handler.py
index a8cc42d7c54..db8d519d9be 100644
--- a/litellm/llms/pass_through/guardrail_translation/handler.py
+++ b/litellm/llms/pass_through/guardrail_translation/handler.py
@@ -6,7 +6,7 @@ It uses the field targeting configuration from litellm_logging_obj
to extract specific fields for guardrail processing.
"""
-from typing import TYPE_CHECKING, Any, List, Optional
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type
from litellm._logging import verbose_proxy_logger
from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
@@ -16,6 +16,8 @@ from litellm.types.utils import GenericGuardrailAPIInputs
if TYPE_CHECKING:
from litellm.integrations.custom_guardrail import CustomGuardrail
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+ from litellm.proxy._types import UserAPIKeyAuth
+ from litellm.proxy.utils import ProxyLogging
class PassThroughEndpointHandler(BaseTranslation):
@@ -208,3 +210,128 @@ class PassThroughEndpointHandler(BaseTranslation):
)
return response
+
+
+_PROVIDER_HANDLERS: Dict[str, Type[BaseTranslation]] = {}
+
+
+def _get_provider_handlers() -> Dict[str, Type[BaseTranslation]]:
+ global _PROVIDER_HANDLERS
+ if not _PROVIDER_HANDLERS:
+ from litellm.llms.bedrock.passthrough.guardrail_translation.handler import (
+ BedrockPassthroughGuardrailHandler,
+ )
+
+ _PROVIDER_HANDLERS = {"bedrock": BedrockPassthroughGuardrailHandler}
+ return _PROVIDER_HANDLERS
+
+
+class LlmPassthroughRouteHandler(BaseTranslation):
+ """
+ Dispatcher for allm_passthrough_route guardrail translation.
+
+ Routes to a per-provider handler based on data["custom_llm_provider"].
+ Unknown providers are skipped with a debug log.
+ """
+
+ async def process_input_messages(
+ self,
+ data: dict,
+ guardrail_to_apply: "CustomGuardrail",
+ litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None,
+ ) -> Any:
+ provider = data.get("custom_llm_provider")
+ handler_cls = _get_provider_handlers().get(provider or "")
+ if handler_cls is None:
+ verbose_proxy_logger.debug(
+ "LlmPassthroughRouteHandler: no handler for provider=%s, skipping guardrail",
+ provider,
+ )
+ return data
+ return await handler_cls().process_input_messages(
+ data=data,
+ guardrail_to_apply=guardrail_to_apply,
+ litellm_logging_obj=litellm_logging_obj,
+ )
+
+ async def process_output_response(
+ self,
+ response: Any,
+ guardrail_to_apply: "CustomGuardrail",
+ litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None,
+ user_api_key_dict: Optional[Any] = None,
+ request_data: Optional[dict] = None,
+ ) -> Any:
+ provider = (request_data or {}).get("custom_llm_provider")
+ handler_cls = _get_provider_handlers().get(provider or "")
+ if handler_cls is None:
+ verbose_proxy_logger.debug(
+ "LlmPassthroughRouteHandler: no handler for provider=%s, skipping guardrail",
+ provider,
+ )
+ return response
+ return await handler_cls().process_output_response(
+ response=response,
+ guardrail_to_apply=guardrail_to_apply,
+ litellm_logging_obj=litellm_logging_obj,
+ user_api_key_dict=user_api_key_dict,
+ request_data=request_data,
+ )
+
+ @staticmethod
+ def is_event_stream_response(provider: Optional[str], content_type: str) -> bool:
+ handler_cls = _get_provider_handlers().get(provider or "")
+ detector = getattr(handler_cls, "is_event_stream_content_type", None)
+ if detector is None:
+ return False
+ return detector(content_type)
+
+ @staticmethod
+ def event_stream_media_type(provider: Optional[str]) -> Optional[str]:
+ handler_cls = _get_provider_handlers().get(provider or "")
+ getter = getattr(handler_cls, "event_stream_media_type", None)
+ if getter is None:
+ return None
+ return getter()
+
+ @staticmethod
+ def _resolve_event_stream_de_anonymizer(provider: Optional[str]):
+ handler_cls = _get_provider_handlers().get(provider or "")
+ return getattr(handler_cls, "de_anonymize_event_stream", None)
+
+ @staticmethod
+ def supports_event_stream_de_anonymization(
+ provider: Optional[str], endpoint: Optional[str]
+ ) -> bool:
+ handler_cls = _get_provider_handlers().get(provider or "")
+ endpoint_check = getattr(
+ handler_cls, "event_stream_endpoint_is_de_anonymizable", None
+ )
+ if endpoint_check is None:
+ return False
+ return endpoint_check(endpoint or "")
+
+ @staticmethod
+ async def de_anonymize_event_stream(
+ body_bytes: bytes,
+ proxy_logging_obj: "ProxyLogging",
+ user_api_key_dict: "UserAPIKeyAuth",
+ data: dict,
+ ) -> bytes:
+ provider = data.get("custom_llm_provider")
+ de_anonymize = LlmPassthroughRouteHandler._resolve_event_stream_de_anonymizer(
+ provider
+ )
+ if de_anonymize is None:
+ verbose_proxy_logger.debug(
+ "LlmPassthroughRouteHandler: no event-stream handler for provider=%s, "
+ "leaving stream unmodified",
+ provider,
+ )
+ return body_bytes
+ return await de_anonymize(
+ body_bytes=body_bytes,
+ proxy_logging_obj=proxy_logging_obj,
+ user_api_key_dict=user_api_key_dict,
+ data=data,
+ )
diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.py
index c257073b4fa..d81668a7804 100644
--- a/litellm/proxy/common_request_processing.py
+++ b/litellm/proxy/common_request_processing.py
@@ -968,7 +968,9 @@ class ProxyBaseLLMRequestProcessing:
self.data["litellm_logging_obj"] = logging_obj
self.data = await proxy_logging_obj.pre_call_hook( # type: ignore
- user_api_key_dict=user_api_key_dict, data=self.data, call_type=route_type # type: ignore
+ user_api_key_dict=user_api_key_dict,
+ data=self.data,
+ call_type=route_type, # type: ignore
)
# Apply hierarchical router_settings (Key > Team)
@@ -1336,6 +1338,32 @@ class ProxyBaseLLMRequestProcessing:
else:
generator = response
+ if (
+ self._has_post_call_guardrails_for_passthrough()
+ and self._passthrough_endpoint_has_stream_guardrail_handler()
+ ):
+ body_bytes = b"".join(
+ [chunk async for chunk in generator] # type: ignore[union-attr]
+ )
+ modified_bytes = (
+ await self._handle_event_stream_allm_passthrough_route(
+ body_bytes=body_bytes,
+ proxy_logging_obj=proxy_logging_obj,
+ user_api_key_dict=user_api_key_dict,
+ )
+ )
+ response_headers = {
+ k: v
+ for k, v in custom_headers.items()
+ if k.lower() != "content-length"
+ }
+ return Response(
+ content=modified_bytes,
+ status_code=status.HTTP_200_OK,
+ media_type=self._passthrough_event_stream_media_type(),
+ headers=response_headers,
+ )
+
# For passthrough routes, stream directly without error parsing
# since we're dealing with raw binary data (e.g., AWS event streams)
return StreamingResponse(
@@ -1344,7 +1372,17 @@ class ProxyBaseLLMRequestProcessing:
headers=custom_headers,
)
else:
- # Traditional HTTP response with aiter_bytes
+ _early = (
+ await self._handle_non_streaming_allm_passthrough_route(
+ response=response,
+ proxy_logging_obj=proxy_logging_obj,
+ user_api_key_dict=user_api_key_dict,
+ custom_headers=custom_headers,
+ request_headers=dict(request.headers),
+ )
+ )
+ if _early is not None:
+ return _early
return StreamingResponse(
content=response.aiter_bytes(), # type: ignore[union-attr]
status_code=response.status_code, # type: ignore[union-attr]
@@ -1404,6 +1442,33 @@ class ProxyBaseLLMRequestProcessing:
# preserves blocking behavior and avoids double invocation.
if getattr(logging_obj, "_on_deferred_stream_complete", None):
logging_obj._on_deferred_stream_complete = None # type: ignore[union-attr]
+
+ if route_type == "allm_passthrough_route":
+ _non_streaming_custom_headers = ProxyBaseLLMRequestProcessing.get_custom_headers(
+ user_api_key_dict=user_api_key_dict,
+ call_id=logging_obj.litellm_call_id,
+ model_id=model_id,
+ cache_key=cache_key,
+ api_base=api_base,
+ version=version,
+ response_cost=response_cost,
+ model_region=getattr(user_api_key_dict, "allowed_model_region", ""),
+ fastest_response_batch_completion=fastest_response_batch_completion,
+ request_data=self.data,
+ hidden_params=hidden_params,
+ litellm_logging_obj=logging_obj,
+ **additional_headers,
+ )
+ _early = await self._handle_non_streaming_allm_passthrough_route(
+ response=response,
+ proxy_logging_obj=proxy_logging_obj,
+ user_api_key_dict=user_api_key_dict,
+ custom_headers=_non_streaming_custom_headers,
+ request_headers=dict(request.headers),
+ )
+ if _early is not None:
+ return _early
+
response = await proxy_logging_obj.post_call_success_hook(
data=self.data,
user_api_key_dict=user_api_key_dict,
@@ -1623,6 +1688,11 @@ class ProxyBaseLLMRequestProcessing:
if isinstance(result, StreamingResponse):
return result
+ # base_process_llm_request may return a FastAPI Response directly after
+ # post-call guardrails buffer and rewrite JSON (e.g. Bedrock Converse passthrough).
+ if isinstance(result, Response):
+ return result
+
content = await result.aread()
return Response(
content=content,
@@ -1684,6 +1754,177 @@ class ProxyBaseLLMRequestProcessing:
return True
return False
+ def _has_post_call_guardrails_for_passthrough(self) -> bool:
+ """
+ True when a post_call guardrail will actually run for THIS request.
+
+ Mirrors the gate in ProxyLogging.post_call_success_hook
+ (should_run_guardrail against the request's merged guardrails) so that a
+ guardrail registered globally but not configured for this key/team does
+ not force the passthrough stream to be buffered into a single
+ non-streaming response. An event_hook=None guardrail still counts here
+ because should_run_guardrail treats it as matching every hook.
+ """
+ from litellm.proxy.proxy_server import llm_router
+ from litellm.proxy.utils import _check_and_merge_model_level_guardrails
+
+ guardrail_data = _check_and_merge_model_level_guardrails(
+ data=self.data, llm_router=llm_router
+ )
+ for cb in litellm.callbacks:
+ if not isinstance(cb, CustomGuardrail):
+ continue
+ if cb.should_run_guardrail(
+ data=guardrail_data,
+ event_type=GuardrailEventHooks.post_call,
+ ):
+ return True
+ return False
+
+ def _passthrough_endpoint_has_stream_guardrail_handler(self) -> bool:
+ """
+ True when the resolved passthrough provider AND endpoint have an
+ event-stream guardrail handler that can rewrite buffered frames. Only such
+ endpoints may have their stream buffered for post-call guardrails; every
+ other endpoint must keep streaming so the response is not silently turned
+ into a non-streaming body when no content modification would occur (e.g.
+ Bedrock invoke-with-response-stream, whose frames the Converse handler
+ leaves untouched).
+ """
+ from litellm.llms.pass_through.guardrail_translation.handler import (
+ LlmPassthroughRouteHandler,
+ )
+
+ return LlmPassthroughRouteHandler.supports_event_stream_de_anonymization(
+ self.data.get("custom_llm_provider"),
+ self.data.get("endpoint"),
+ )
+
+ def _passthrough_event_stream_media_type(self) -> Optional[str]:
+ """
+ Content-type for a buffered passthrough event-stream response, resolved
+ from the provider handler so the proxy stays provider-agnostic. Mirrors
+ the upstream content-type the non-streaming path forwards, since the
+ buffered streaming generator carries no headers of its own.
+ """
+ from litellm.llms.pass_through.guardrail_translation.handler import (
+ LlmPassthroughRouteHandler,
+ )
+
+ return LlmPassthroughRouteHandler.event_stream_media_type(
+ self.data.get("custom_llm_provider")
+ )
+
+ async def _handle_non_streaming_allm_passthrough_route(
+ self,
+ response: Any,
+ proxy_logging_obj: "ProxyLogging",
+ user_api_key_dict: "UserAPIKeyAuth",
+ custom_headers: dict,
+ request_headers: Dict[str, str],
+ ) -> Optional[Response]:
+ if not self._has_post_call_guardrails_for_passthrough():
+ return None
+
+ import json as _json
+
+ from litellm.llms.pass_through.guardrail_translation.handler import (
+ LlmPassthroughRouteHandler,
+ )
+ from litellm.proxy.pass_through_endpoints.pass_through_endpoints import (
+ HttpPassThroughEndpointHelpers,
+ )
+
+ try:
+ response_status: int = response.status_code # type: ignore[union-attr]
+ content_type: str = response.headers.get("content-type", "") # type: ignore[union-attr]
+ except AttributeError:
+ return None
+
+ if response_status >= 300:
+ return None
+
+ is_event_stream = LlmPassthroughRouteHandler.is_event_stream_response(
+ self.data.get("custom_llm_provider"), content_type
+ )
+ if not is_event_stream and "application/json" not in content_type:
+ return None
+
+ response_headers = HttpPassThroughEndpointHelpers.get_response_headers(
+ headers=response.headers, # type: ignore[union-attr]
+ custom_headers=custom_headers,
+ )
+ callback_headers = await proxy_logging_obj.post_call_response_headers_hook(
+ data=self.data,
+ user_api_key_dict=user_api_key_dict,
+ response=response,
+ request_headers=request_headers,
+ )
+ if callback_headers:
+ response_headers.update(callback_headers)
+
+ if is_event_stream:
+ body_bytes = await response.aread() # type: ignore[union-attr]
+ modified_bytes = await self._handle_event_stream_allm_passthrough_route(
+ body_bytes=body_bytes,
+ proxy_logging_obj=proxy_logging_obj,
+ user_api_key_dict=user_api_key_dict,
+ )
+ return Response(
+ content=modified_bytes,
+ status_code=response_status,
+ media_type=content_type,
+ headers=response_headers,
+ )
+
+ body_bytes = await response.aread() # type: ignore[union-attr]
+ try:
+ parsed = _json.loads(body_bytes)
+ except (_json.JSONDecodeError, UnicodeDecodeError):
+ return Response(
+ content=body_bytes,
+ status_code=response_status,
+ media_type="application/json",
+ headers=response_headers,
+ )
+ processed = await proxy_logging_obj.post_call_success_hook(
+ data=self.data,
+ user_api_key_dict=user_api_key_dict,
+ response=parsed,
+ )
+ if isinstance(processed, dict):
+ content = _json.dumps(processed).encode()
+ else:
+ verbose_proxy_logger.debug(
+ "allm_passthrough_route: post_call_success_hook returned %s, "
+ "leaving JSON response unmodified",
+ type(processed).__name__,
+ )
+ content = body_bytes
+ return Response(
+ content=content,
+ status_code=response_status,
+ media_type="application/json",
+ headers=response_headers,
+ )
+
+ async def _handle_event_stream_allm_passthrough_route(
+ self,
+ body_bytes: bytes,
+ proxy_logging_obj: "ProxyLogging",
+ user_api_key_dict: "UserAPIKeyAuth",
+ ) -> bytes:
+ from litellm.llms.pass_through.guardrail_translation.handler import (
+ LlmPassthroughRouteHandler,
+ )
+
+ return await LlmPassthroughRouteHandler.de_anonymize_event_stream(
+ body_bytes=body_bytes,
+ proxy_logging_obj=proxy_logging_obj,
+ user_api_key_dict=user_api_key_dict,
+ data=self.data,
+ )
+
@staticmethod
def _flush_deferred_async_logging(
logging_obj: Any,
@@ -2136,7 +2377,9 @@ class ProxyBaseLLMRequestProcessing:
request_data=request_data,
proxy_logging_obj=proxy_logging_obj,
serialize_chunk=ProxyBaseLLMRequestProcessing.return_sse_chunk,
- serialize_error=lambda proxy_exc: f"{STREAM_SSE_DATA_PREFIX}{json.dumps({'error': proxy_exc.to_dict()})}\n\n",
+ serialize_error=lambda proxy_exc: (
+ f"{STREAM_SSE_DATA_PREFIX}{json.dumps({'error': proxy_exc.to_dict()})}\n\n"
+ ),
)
@staticmethod
diff --git a/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py b/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py
index bc46beabc65..2a2c758fa8a 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py
@@ -248,12 +248,16 @@ class UnifiedLLMGuardrails(CustomLogger):
# Fallback: resolve call_type from logging_obj for pass-through endpoints
if call_type is None:
litellm_logging_obj = data.get("litellm_logging_obj")
- if (
- litellm_logging_obj is not None
- and getattr(litellm_logging_obj, "call_type", None)
- == CallTypes.pass_through.value
+ logging_call_type = (
+ getattr(litellm_logging_obj, "call_type", None)
+ if litellm_logging_obj is not None
+ else None
+ )
+ if logging_call_type in (
+ CallTypes.pass_through.value,
+ CallTypes.allm_passthrough_route.value,
):
- call_type = CallTypes.pass_through.value
+ call_type = logging_call_type
if call_type is None:
return response
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index a11ea965f34..644ad2cb905 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -499,6 +499,7 @@ CallTypesLiteral = Literal[
"create_batch",
"acreate_batch",
"pass_through_endpoint",
+ "allm_passthrough_route",
"anthropic_messages",
"aretrieve_batch",
"retrieve_batch",
diff --git a/tests/local_testing/test_azure_anthropic_sync_post.py b/tests/local_testing/test_azure_anthropic_sync_post.py
index 5ceb9ae3ed9..d621a224ef4 100644
--- a/tests/local_testing/test_azure_anthropic_sync_post.py
+++ b/tests/local_testing/test_azure_anthropic_sync_post.py
@@ -18,7 +18,10 @@ import pytest
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
from litellm.exceptions import Timeout as LitellmTimeout
-from litellm.llms.custom_httpx.http_handler import _get_httpx_client
+from litellm.llms.custom_httpx.http_handler import (
+ MaskedHTTPStatusError,
+ _get_httpx_client,
+)
_HTTPBIN_DELAY_S = 10
_PER_REQUEST_TIMEOUT_S = 5.0
@@ -40,5 +43,7 @@ def test_post_delay_exceeds_per_request_timeout_raises():
data=json.dumps({"model": "claude", "messages": []}),
timeout=_PER_REQUEST_TIMEOUT_S,
)
+ except MaskedHTTPStatusError as e:
+ pytest.skip(f"httpbin.org unavailable: {e}")
finally:
handler.close()
diff --git a/tests/test_litellm/llms/bedrock/passthrough/guardrail_translation/__init__.py b/tests/test_litellm/llms/bedrock/passthrough/guardrail_translation/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/test_litellm/llms/bedrock/passthrough/guardrail_translation/test_handler.py b/tests/test_litellm/llms/bedrock/passthrough/guardrail_translation/test_handler.py
new file mode 100644
index 00000000000..744ed50dbcb
--- /dev/null
+++ b/tests/test_litellm/llms/bedrock/passthrough/guardrail_translation/test_handler.py
@@ -0,0 +1,1163 @@
+"""
+Tests for BedrockPassthroughGuardrailHandler.
+
+Validates that:
+- Text content is extracted from Converse messages and system blocks
+- apply_guardrail receives the correct texts
+- Modified texts are written back in-place; non-text fields are untouched
+- Blocking raises and propagates
+- Non-converse endpoints skip guardrail execution
+"""
+
+import copy
+import pytest
+from unittest.mock import AsyncMock, MagicMock
+
+from litellm.llms.bedrock.passthrough.guardrail_translation.handler import (
+ BedrockPassthroughGuardrailHandler,
+ _extract_converse_texts,
+ _is_converse_endpoint,
+ _write_back_texts,
+)
+
+
+class GuardrailBlocked(Exception):
+ """Stand-in for a guardrail rejecting a request; the handler must let it propagate."""
+
+
+def _make_guardrail(apply_result: dict) -> MagicMock:
+ g = MagicMock()
+ g.guardrail_name = "test-guard"
+ g.apply_guardrail = AsyncMock(return_value=apply_result)
+ g.skip_system_message_in_guardrail = False
+ g.skip_tool_message_in_guardrail = False
+ return g
+
+
+def _converse_data(endpoint: str = "model/anthropic.claude-3-sonnet/converse") -> dict:
+ return {
+ "endpoint": endpoint,
+ "custom_llm_provider": "bedrock",
+ "model": "anthropic.claude-3-sonnet",
+ "data": {
+ "system": [{"text": "You are helpful."}],
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {"text": "Hello world"},
+ {"toolUse": {"toolUseId": "t1", "name": "search", "input": {}}},
+ ],
+ }
+ ],
+ "inferenceConfig": {"maxTokens": 100},
+ },
+ }
+
+
+class TestIsConverseEndpoint:
+ def test_converse(self):
+ assert _is_converse_endpoint("model/foo/converse") is True
+
+ def test_converse_stream(self):
+ assert _is_converse_endpoint("model/foo/converse-stream") is True
+
+ def test_invoke(self):
+ assert _is_converse_endpoint("model/foo/invoke") is False
+
+ def test_invoke_with_response_stream(self):
+ assert _is_converse_endpoint("model/foo/invoke-with-response-stream") is False
+
+
+class TestExtractConverseTexts:
+ def test_extracts_system_and_message_text(self):
+ body = {
+ "system": [{"text": "sys text"}],
+ "messages": [{"role": "user", "content": [{"text": "user text"}]}],
+ }
+ texts, holders = _extract_converse_texts(body, skip_system=False, skip_tool=False)
+ assert texts == ["sys text", "user text"]
+ assert holders[0] == (body["system"][0], "text")
+ assert holders[1] == (body["messages"][0]["content"][0], "text")
+
+ def test_skip_system(self):
+ body = {
+ "system": [{"text": "sys text"}],
+ "messages": [{"role": "user", "content": [{"text": "user text"}]}],
+ }
+ texts, holders = _extract_converse_texts(body, skip_system=True, skip_tool=False)
+ assert texts == ["user text"]
+ assert holders == [(body["messages"][0]["content"][0], "text")]
+
+ def test_skip_tool_blocks(self):
+ body = {
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {"text": "hello"},
+ {"toolUse": {"toolUseId": "1", "name": "fn", "input": {}}},
+ {
+ "toolResult": {
+ "toolUseId": "1",
+ "content": [{"text": "result"}],
+ }
+ },
+ ],
+ }
+ ]
+ }
+ texts, _ = _extract_converse_texts(body, skip_system=False, skip_tool=True)
+ assert texts == ["hello"]
+
+ def test_extracts_nested_tool_result_text_and_json(self):
+ body = {
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {"text": "hello"},
+ {
+ "toolResult": {
+ "toolUseId": "1",
+ "content": [
+ {"text": "blocked tool text"},
+ {"json": {"k": "blocked json value"}},
+ ],
+ }
+ },
+ ],
+ }
+ ]
+ }
+ texts, holders = _extract_converse_texts(body, skip_system=False, skip_tool=False)
+ assert texts == ["hello", "blocked tool text", "blocked json value"]
+ tool_content = body["messages"][0]["content"][1]["toolResult"]["content"]
+ assert holders[1] == (tool_content[0], "text")
+ assert holders[2] == (tool_content[1]["json"], "k")
+
+ def test_extracts_tool_use_input_strings(self):
+ body = {
+ "messages": [
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "toolUse": {
+ "toolUseId": "1",
+ "name": "lookup",
+ "input": {"query": "blocked input value", "limit": 5},
+ }
+ }
+ ],
+ }
+ ]
+ }
+ texts, holders = _extract_converse_texts(body, skip_system=False, skip_tool=False)
+ assert texts == ["blocked input value"]
+ tool_use_input = body["messages"][0]["content"][0]["toolUse"]["input"]
+ assert holders[0] == (tool_use_input, "query")
+
+ def test_non_text_content_blocks_ignored(self):
+ body = {
+ "messages": [
+ {
+ "role": "user",
+ "content": [{"image": {"format": "png", "source": {}}}],
+ }
+ ]
+ }
+ texts, _ = _extract_converse_texts(body, skip_system=False, skip_tool=False)
+ assert texts == []
+
+ def test_extracts_tool_config_description_and_schema(self):
+ body = {
+ "messages": [{"role": "user", "content": [{"text": "hi"}]}],
+ "toolConfig": {
+ "tools": [
+ {
+ "toolSpec": {
+ "name": "lookup",
+ "description": "blocked tool description",
+ "inputSchema": {
+ "json": {
+ "type": "object",
+ "properties": {
+ "q": {
+ "type": "string",
+ "description": "blocked schema description",
+ }
+ },
+ }
+ },
+ }
+ }
+ ]
+ },
+ }
+ texts, _ = _extract_converse_texts(body, skip_system=False, skip_tool=False)
+ assert "blocked tool description" in texts
+ assert "blocked schema description" in texts
+
+ def test_tool_config_scanned_even_when_tool_messages_skipped(self):
+ body = {
+ "messages": [{"role": "user", "content": [{"text": "hi"}]}],
+ "toolConfig": {
+ "tools": [
+ {"toolSpec": {"name": "fn", "description": "blocked description"}}
+ ]
+ },
+ }
+ texts, _ = _extract_converse_texts(body, skip_system=False, skip_tool=True)
+ assert "blocked description" in texts
+
+ def test_extracts_additional_model_request_fields(self):
+ body = {
+ "messages": [{"role": "user", "content": [{"text": "hi"}]}],
+ "additionalModelRequestFields": {
+ "reasoning_config": {"prompt": "blocked extra field"}
+ },
+ }
+ texts, _ = _extract_converse_texts(body, skip_system=False, skip_tool=False)
+ assert "blocked extra field" in texts
+
+
+class TestWriteBackTexts:
+ def test_writes_system_text(self):
+ body = {"system": [{"text": "original"}], "messages": []}
+ _, holders = _extract_converse_texts(body, skip_system=False, skip_tool=False)
+ _write_back_texts(["replaced"], holders)
+ assert body["system"][0]["text"] == "replaced"
+
+ def test_writes_message_text(self):
+ body = {"messages": [{"role": "user", "content": [{"text": "original"}]}]}
+ _, holders = _extract_converse_texts(body, skip_system=False, skip_tool=False)
+ _write_back_texts(["replaced"], holders)
+ assert body["messages"][0]["content"][0]["text"] == "replaced"
+
+ def test_writes_nested_tool_result_text(self):
+ body = {
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {
+ "toolResult": {
+ "toolUseId": "1",
+ "content": [{"text": "original"}],
+ }
+ }
+ ],
+ }
+ ]
+ }
+ _, holders = _extract_converse_texts(body, skip_system=False, skip_tool=False)
+ _write_back_texts(["masked"], holders)
+ assert body["messages"][0]["content"][0]["toolResult"]["content"][0]["text"] == "masked"
+
+ def test_extra_non_text_fields_untouched(self):
+ body = {
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {"text": "hello"},
+ {
+ "toolUse": {
+ "toolUseId": "1",
+ "name": "fn",
+ "input": {"key": "val"},
+ }
+ },
+ ],
+ }
+ ],
+ "inferenceConfig": {"maxTokens": 100},
+ }
+ original = copy.deepcopy(body)
+ _, holders = _extract_converse_texts(body, skip_system=False, skip_tool=False)
+ _write_back_texts(["replaced"], holders)
+ assert body["messages"][0]["content"][0]["text"] == "replaced"
+ assert body["messages"][0]["content"][1] == original["messages"][0]["content"][1]
+ assert body["inferenceConfig"] == original["inferenceConfig"]
+
+ def test_fewer_guardrailed_texts_logs_warning(self, monkeypatch):
+ body = {
+ "messages": [
+ {"role": "user", "content": [{"text": "a"}, {"text": "b"}]}
+ ]
+ }
+ _, holders = _extract_converse_texts(body, skip_system=False, skip_tool=False)
+ assert len(holders) == 2
+
+ warnings = []
+ monkeypatch.setattr(
+ "litellm.llms.bedrock.passthrough.guardrail_translation.handler.verbose_proxy_logger.warning",
+ lambda *args, **kwargs: warnings.append(args),
+ )
+
+ _write_back_texts(["masked"], holders)
+
+ assert warnings, "mismatched guardrail output count must not be silently dropped"
+ assert body["messages"][0]["content"][0]["text"] == "masked"
+ assert body["messages"][0]["content"][1]["text"] == "b"
+
+
+class TestBedrockPassthroughGuardrailHandlerInput:
+ @pytest.mark.asyncio
+ async def test_texts_extracted_and_apply_guardrail_called(self):
+ handler = BedrockPassthroughGuardrailHandler()
+ data = _converse_data()
+ guardrail = _make_guardrail({"texts": ["You are helpful.", "Hello world"]})
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ call_args = guardrail.apply_guardrail.call_args
+ assert call_args.kwargs["input_type"] == "request"
+ sent_texts = call_args.kwargs["inputs"]["texts"]
+ assert "You are helpful." in sent_texts
+ assert "Hello world" in sent_texts
+ # toolUse block not included
+ assert len(sent_texts) == 2
+
+ @pytest.mark.asyncio
+ async def test_masking_writes_back_in_place(self):
+ handler = BedrockPassthroughGuardrailHandler()
+ data = _converse_data()
+ guardrail = _make_guardrail({"texts": ["[REDACTED]", "[REDACTED]"]})
+
+ result = await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ body = result["data"]
+ assert body["system"][0]["text"] == "[REDACTED]"
+ assert body["messages"][0]["content"][0]["text"] == "[REDACTED]"
+ # toolUse unchanged
+ assert body["messages"][0]["content"][1].get("toolUse") is not None
+ # inferenceConfig untouched
+ assert body["inferenceConfig"] == {"maxTokens": 100}
+
+ @pytest.mark.asyncio
+ async def test_blocking_guardrail_propagates_exception(self):
+ handler = BedrockPassthroughGuardrailHandler()
+ data = _converse_data()
+ guardrail = MagicMock()
+ guardrail.guardrail_name = "block-guard"
+ guardrail.skip_system_message_in_guardrail = False
+ guardrail.skip_tool_message_in_guardrail = False
+ guardrail.apply_guardrail = AsyncMock(side_effect=GuardrailBlocked("Blocked"))
+
+ with pytest.raises(GuardrailBlocked):
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ @pytest.mark.asyncio
+ async def test_tool_result_text_scanned_and_masked(self):
+ handler = BedrockPassthroughGuardrailHandler()
+ data = _converse_data()
+ data["data"]["messages"][0]["content"].append(
+ {
+ "toolResult": {
+ "toolUseId": "t1",
+ "content": [{"text": "My SSN is 123-45-6789"}],
+ }
+ }
+ )
+ guardrail = _make_guardrail(
+ {"texts": ["You are helpful.", "Hello world", "[REDACTED]"]}
+ )
+
+ result = await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ sent_texts = guardrail.apply_guardrail.call_args.kwargs["inputs"]["texts"]
+ assert "My SSN is 123-45-6789" in sent_texts
+ tool_result = result["data"]["messages"][0]["content"][2]["toolResult"]
+ assert tool_result["content"][0]["text"] == "[REDACTED]"
+
+ @pytest.mark.asyncio
+ async def test_tool_result_json_scanned_and_masked(self):
+ """A caller can hide blocked text under toolResult.content[].json; the
+ guardrail must still see it and write the masked value back in place."""
+ handler = BedrockPassthroughGuardrailHandler()
+ data = _converse_data()
+ data["data"]["messages"][0]["content"].append(
+ {
+ "toolResult": {
+ "toolUseId": "t1",
+ "content": [{"json": {"note": "SSN 123-45-6789"}}],
+ }
+ }
+ )
+ guardrail = _make_guardrail(
+ {"texts": ["You are helpful.", "Hello world", "[REDACTED]"]}
+ )
+
+ result = await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ sent_texts = guardrail.apply_guardrail.call_args.kwargs["inputs"]["texts"]
+ assert "SSN 123-45-6789" in sent_texts
+ tool_result = result["data"]["messages"][0]["content"][2]["toolResult"]
+ assert tool_result["content"][0]["json"]["note"] == "[REDACTED]"
+
+ @pytest.mark.asyncio
+ async def test_tool_use_input_scanned_and_masked(self):
+ """Blocked text hidden in toolUse.input must be scanned and masked."""
+ handler = BedrockPassthroughGuardrailHandler()
+ data = _converse_data()
+ data["data"]["messages"][0]["content"][1]["toolUse"]["input"] = {
+ "query": "email [email protected]"
+ }
+ guardrail = _make_guardrail(
+ {"texts": ["You are helpful.", "Hello world", "[REDACTED]"]}
+ )
+
+ result = await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ sent_texts = guardrail.apply_guardrail.call_args.kwargs["inputs"]["texts"]
+ assert "email [email protected]" in sent_texts
+ tool_use = result["data"]["messages"][0]["content"][1]["toolUse"]
+ assert tool_use["input"]["query"] == "[REDACTED]"
+
+ @pytest.mark.asyncio
+ async def test_tool_use_input_blocking_propagates(self):
+ """A blocking guardrail must reject content hidden in toolUse.input."""
+ handler = BedrockPassthroughGuardrailHandler()
+ data = _converse_data()
+ data["data"]["messages"][0]["content"][1]["toolUse"]["input"] = {
+ "query": "blocked content"
+ }
+ guardrail = MagicMock()
+ guardrail.guardrail_name = "block-guard"
+ guardrail.skip_system_message_in_guardrail = False
+ guardrail.skip_tool_message_in_guardrail = False
+ guardrail.apply_guardrail = AsyncMock(side_effect=GuardrailBlocked("Blocked"))
+
+ with pytest.raises(GuardrailBlocked):
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ sent_texts = guardrail.apply_guardrail.call_args.kwargs["inputs"]["texts"]
+ assert "blocked content" in sent_texts
+
+ @pytest.mark.asyncio
+ async def test_tool_config_description_scanned_and_masked(self):
+ """Blocked text hidden in toolConfig.tools[].toolSpec.description is still
+ forwarded to Bedrock, so the guardrail must see it and mask it in place."""
+ handler = BedrockPassthroughGuardrailHandler()
+ data = _converse_data()
+ data["data"]["toolConfig"] = {
+ "tools": [
+ {
+ "toolSpec": {
+ "name": "lookup",
+ "description": "email [email protected]",
+ "inputSchema": {"json": {"type": "object"}},
+ }
+ }
+ ]
+ }
+ guardrail = _make_guardrail(
+ {"texts": ["You are helpful.", "Hello world", "lookup", "[REDACTED]", "object"]}
+ )
+
+ result = await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ sent_texts = guardrail.apply_guardrail.call_args.kwargs["inputs"]["texts"]
+ assert "email [email protected]" in sent_texts
+ tool_spec = result["data"]["toolConfig"]["tools"][0]["toolSpec"]
+ assert tool_spec["description"] == "[REDACTED]"
+
+ @pytest.mark.asyncio
+ async def test_tool_config_description_blocking_propagates(self):
+ """A blocking guardrail must reject content hidden in a tool description."""
+ handler = BedrockPassthroughGuardrailHandler()
+ data = _converse_data()
+ data["data"]["toolConfig"] = {
+ "tools": [{"toolSpec": {"name": "fn", "description": "blocked content"}}]
+ }
+ guardrail = MagicMock()
+ guardrail.guardrail_name = "block-guard"
+ guardrail.skip_system_message_in_guardrail = False
+ guardrail.skip_tool_message_in_guardrail = False
+ guardrail.apply_guardrail = AsyncMock(side_effect=GuardrailBlocked("Blocked"))
+
+ with pytest.raises(GuardrailBlocked):
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ sent_texts = guardrail.apply_guardrail.call_args.kwargs["inputs"]["texts"]
+ assert "blocked content" in sent_texts
+
+ @pytest.mark.asyncio
+ async def test_additional_model_request_fields_scanned_and_masked(self):
+ """Blocked text hidden in additionalModelRequestFields is forwarded to
+ Bedrock, so the guardrail must scan it and mask it in place."""
+ handler = BedrockPassthroughGuardrailHandler()
+ data = _converse_data()
+ data["data"]["additionalModelRequestFields"] = {"note": "ssn 123-45-6789"}
+ guardrail = _make_guardrail(
+ {"texts": ["You are helpful.", "Hello world", "[REDACTED]"]}
+ )
+
+ result = await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ sent_texts = guardrail.apply_guardrail.call_args.kwargs["inputs"]["texts"]
+ assert "ssn 123-45-6789" in sent_texts
+ assert result["data"]["additionalModelRequestFields"]["note"] == "[REDACTED]"
+
+ @pytest.mark.asyncio
+ async def test_non_converse_endpoint_scans_full_payload(self):
+ """Invoke routes must not bypass guardrails: the full request payload is
+ scanned so blocking guardrails still see user-controlled text."""
+ handler = BedrockPassthroughGuardrailHandler()
+ data = {
+ "endpoint": "model/anthropic.claude-3-sonnet/invoke",
+ "custom_llm_provider": "bedrock",
+ "model": "anthropic.claude-3-sonnet",
+ "data": {"messages": [{"role": "user", "content": "blocked invoke text"}]},
+ }
+ guardrail = _make_guardrail({"texts": []})
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ guardrail.apply_guardrail.assert_called_once()
+ sent_texts = guardrail.apply_guardrail.call_args.kwargs["inputs"]["texts"]
+ assert "blocked invoke text" in sent_texts[0]
+
+ @pytest.mark.asyncio
+ async def test_non_converse_endpoint_blocking_propagates(self):
+ handler = BedrockPassthroughGuardrailHandler()
+ data = {
+ "endpoint": "model/anthropic.claude-3-sonnet/invoke-with-response-stream",
+ "custom_llm_provider": "bedrock",
+ "data": {"prompt": "blocked"},
+ }
+ guardrail = MagicMock()
+ guardrail.guardrail_name = "block-guard"
+ guardrail.apply_guardrail = AsyncMock(side_effect=GuardrailBlocked("Blocked"))
+
+ with pytest.raises(GuardrailBlocked):
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ @pytest.mark.asyncio
+ async def test_missing_messages_field_skips(self):
+ handler = BedrockPassthroughGuardrailHandler()
+ data = {
+ "endpoint": "model/foo/converse",
+ "custom_llm_provider": "bedrock",
+ "data": {"system": [{"text": "sys"}]},
+ }
+ guardrail = _make_guardrail({"texts": []})
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ guardrail.apply_guardrail.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_model_passed_to_apply_guardrail(self):
+ handler = BedrockPassthroughGuardrailHandler()
+ data = _converse_data()
+ guardrail = _make_guardrail({"texts": ["You are helpful.", "Hello world"]})
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ call_args = guardrail.apply_guardrail.call_args
+ assert call_args.kwargs["inputs"].get("model") == "anthropic.claude-3-sonnet"
+
+
+class TestBedrockPassthroughGuardrailHandlerOutput:
+ def _converse_response(self, text: str = "Model reply") -> dict:
+ return {
+ "output": {
+ "message": {
+ "role": "assistant",
+ "content": [{"text": text}],
+ }
+ },
+ "stopReason": "end_turn",
+ "usage": {"inputTokens": 10, "outputTokens": 5},
+ }
+
+ @pytest.mark.asyncio
+ async def test_response_text_extracted_and_apply_guardrail_called(self):
+ handler = BedrockPassthroughGuardrailHandler()
+ response = self._converse_response("Model reply")
+ guardrail = _make_guardrail({"texts": ["Model reply"]})
+
+ await handler.process_output_response(response=response, guardrail_to_apply=guardrail)
+
+ call_args = guardrail.apply_guardrail.call_args
+ assert call_args.kwargs["input_type"] == "response"
+ assert call_args.kwargs["inputs"]["texts"] == ["Model reply"]
+
+ @pytest.mark.asyncio
+ async def test_response_masking_writes_back(self):
+ handler = BedrockPassthroughGuardrailHandler()
+ response = self._converse_response("Bad content")
+ guardrail = _make_guardrail({"texts": ["[MASKED]"]})
+
+ result = await handler.process_output_response(response=response, guardrail_to_apply=guardrail)
+
+ assert result["output"]["message"]["content"][0]["text"] == "[MASKED]"
+ assert result["stopReason"] == "end_turn"
+
+ @pytest.mark.asyncio
+ async def test_response_guardrail_returning_no_texts_preserves_output(self, monkeypatch):
+ """A guardrail that returns no texts must leave the response untouched and
+ not warn, mirroring the request path's empty-result guard."""
+ handler = BedrockPassthroughGuardrailHandler()
+ response = self._converse_response("Model reply")
+ guardrail = _make_guardrail({"texts": []})
+
+ warnings = []
+ monkeypatch.setattr(
+ "litellm.llms.bedrock.passthrough.guardrail_translation.handler.verbose_proxy_logger.warning",
+ lambda *args, **kwargs: warnings.append(args),
+ )
+
+ result = await handler.process_output_response(response=response, guardrail_to_apply=guardrail)
+
+ assert not warnings
+ assert result["output"]["message"]["content"][0]["text"] == "Model reply"
+
+ @pytest.mark.asyncio
+ async def test_response_reasoning_and_tooluse_extracted_and_masked(self):
+ """Model output hidden in reasoningContent.reasoningText.text and
+ toolUse.input must be scanned and masked, but the reasoning signature
+ must be left untouched."""
+ handler = BedrockPassthroughGuardrailHandler()
+ response = {
+ "output": {
+ "message": {
+ "role": "assistant",
+ "content": [
+ {"text": "visible"},
+ {
+ "reasoningContent": {
+ "reasoningText": {
+ "text": "thinking about [email protected]",
+ "signature": "sig-do-not-touch",
+ }
+ }
+ },
+ {
+ "toolUse": {
+ "toolUseId": "1",
+ "name": "lookup",
+ "input": {"q": "ssn 123-45-6789"},
+ }
+ },
+ ],
+ }
+ },
+ "stopReason": "end_turn",
+ }
+ guardrail = _make_guardrail(
+ {"texts": ["[V]", "[REASON]", "[INPUT]"]}
+ )
+
+ result = await handler.process_output_response(
+ response=response, guardrail_to_apply=guardrail
+ )
+
+ sent_texts = guardrail.apply_guardrail.call_args.kwargs["inputs"]["texts"]
+ assert "thinking about [email protected]" in sent_texts
+ assert "ssn 123-45-6789" in sent_texts
+ blocks = result["output"]["message"]["content"]
+ assert blocks[0]["text"] == "[V]"
+ reasoning_text = blocks[1]["reasoningContent"]["reasoningText"]
+ assert reasoning_text["text"] == "[REASON]"
+ assert reasoning_text["signature"] == "sig-do-not-touch"
+ assert blocks[2]["toolUse"]["input"]["q"] == "[INPUT]"
+
+ @pytest.mark.asyncio
+ async def test_response_citations_content_extracted_and_masked(self):
+ """citationsContent.content[].text is grounded answer text and must be
+ scanned, while citation sources/titles are left untouched."""
+ handler = BedrockPassthroughGuardrailHandler()
+ response = {
+ "output": {
+ "message": {
+ "role": "assistant",
+ "content": [
+ {
+ "citationsContent": {
+ "content": [{"text": "Contact [email protected]"}],
+ "citations": [
+ {"source": "https://example.com", "title": "Example"}
+ ],
+ }
+ }
+ ],
+ }
+ },
+ "stopReason": "end_turn",
+ }
+ guardrail = _make_guardrail({"texts": ["[CITED]"]})
+
+ result = await handler.process_output_response(
+ response=response, guardrail_to_apply=guardrail
+ )
+
+ sent_texts = guardrail.apply_guardrail.call_args.kwargs["inputs"]["texts"]
+ assert sent_texts == ["Contact [email protected]"]
+ citations = result["output"]["message"]["content"][0]["citationsContent"]
+ assert citations["content"][0]["text"] == "[CITED]"
+ assert citations["citations"][0]["source"] == "https://example.com"
+ assert citations["citations"][0]["title"] == "Example"
+
+ @pytest.mark.asyncio
+ async def test_non_dict_response_returned_unchanged(self):
+ handler = BedrockPassthroughGuardrailHandler()
+ guardrail = _make_guardrail({"texts": []})
+
+ result = await handler.process_output_response(response="raw string", guardrail_to_apply=guardrail)
+
+ assert result == "raw string"
+ guardrail.apply_guardrail.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_missing_output_structure_skips(self):
+ handler = BedrockPassthroughGuardrailHandler()
+ response = {"stopReason": "end_turn"}
+ guardrail = _make_guardrail({"texts": []})
+
+ result = await handler.process_output_response(response=response, guardrail_to_apply=guardrail)
+
+ assert result == {"stopReason": "end_turn"}
+ guardrail.apply_guardrail.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_non_converse_response_scanned_via_generic_handler(self):
+ """Invoke responses are not Converse-shaped; they must still be scanned
+ through the generic passthrough handler rather than skipped."""
+ handler = BedrockPassthroughGuardrailHandler()
+ response = {"completion": "blocked model output"}
+ guardrail = _make_guardrail({"texts": []})
+
+ await handler.process_output_response(
+ response=response,
+ guardrail_to_apply=guardrail,
+ request_data={"endpoint": "model/anthropic.claude-3-sonnet/invoke"},
+ )
+
+ guardrail.apply_guardrail.assert_called_once()
+ sent_texts = guardrail.apply_guardrail.call_args.kwargs["inputs"]["texts"]
+ assert "blocked model output" in sent_texts[0]
+
+
+def _build_event_stream_frame(event_type: str, payload: dict) -> bytes:
+ import json
+ import struct
+ from binascii import crc32 as esm_crc32
+
+ payload_bytes = json.dumps(payload, separators=(",", ":")).encode()
+
+ def _encode_str_header(name: str, value: str) -> bytes:
+ name_b = name.encode()
+ value_b = value.encode()
+ return (
+ struct.pack("!B", len(name_b)) + name_b + struct.pack("!B", 7) + struct.pack("!H", len(value_b)) + value_b
+ )
+
+ headers_bytes = (
+ _encode_str_header(":event-type", event_type)
+ + _encode_str_header(":content-type", "application/json")
+ + _encode_str_header(":message-type", "event")
+ )
+
+ headers_length = len(headers_bytes)
+ total_length = 12 + headers_length + len(payload_bytes) + 4
+ prelude = struct.pack("!II", total_length, headers_length)
+ prelude_crc_val = esm_crc32(prelude) & 0xFFFFFFFF
+ prelude_crc_b = struct.pack("!I", prelude_crc_val)
+ part_for_msg = prelude_crc_b + headers_bytes + payload_bytes
+ msg_crc_val = esm_crc32(part_for_msg, prelude_crc_val) & 0xFFFFFFFF
+ msg_crc_b = struct.pack("!I", msg_crc_val)
+ return prelude + prelude_crc_b + headers_bytes + payload_bytes + msg_crc_b
+
+
+class TestDeAnonymizeConverseStream:
+ def _make_proxy_logging(self, mock_hook) -> MagicMock:
+ proxy_logging_obj = MagicMock()
+ proxy_logging_obj.post_call_success_hook = mock_hook
+ return proxy_logging_obj
+
+ @pytest.mark.asyncio
+ async def test_text_delta_de_anonymized_in_modified_bytes(self):
+ import json
+ from botocore.eventstream import EventStreamBuffer
+
+ stream_bytes = (
+ _build_event_stream_frame("messageStart", {"role": "assistant"})
+ + _build_event_stream_frame(
+ "contentBlockDelta",
+ {"contentBlockIndex": 0, "delta": {"text": "<PERSON_1> works at <ORG_2>"}},
+ )
+ + _build_event_stream_frame("contentBlockStop", {"contentBlockIndex": 0})
+ + _build_event_stream_frame("messageStop", {"stopReason": "end_turn"})
+ )
+
+ de_anon_response = {
+ "output": {
+ "message": {
+ "role": "assistant",
+ "content": [{"text": "John Doe works at Acme Corp"}],
+ }
+ },
+ "stopReason": "end_turn",
+ }
+
+ async def mock_hook(data, user_api_key_dict, response):
+ return de_anon_response
+
+ result = await BedrockPassthroughGuardrailHandler.de_anonymize_event_stream(
+ body_bytes=stream_bytes,
+ proxy_logging_obj=self._make_proxy_logging(mock_hook),
+ user_api_key_dict=MagicMock(),
+ data={},
+ )
+
+ buf = EventStreamBuffer()
+ buf.add_data(result)
+ texts = [
+ json.loads(msg.payload)["delta"]["text"]
+ for msg in buf
+ if msg.headers.get(":event-type") == "contentBlockDelta"
+ ]
+ assert "".join(texts) == "John Doe works at Acme Corp"
+
+ @pytest.mark.asyncio
+ async def test_tokens_split_across_chunks_reassembled(self):
+ import json
+ from botocore.eventstream import EventStreamBuffer
+
+ stream_bytes = _build_event_stream_frame(
+ "contentBlockDelta",
+ {"contentBlockIndex": 0, "delta": {"text": "<PERSON_"}},
+ ) + _build_event_stream_frame(
+ "contentBlockDelta",
+ {"contentBlockIndex": 0, "delta": {"text": "1> called."}},
+ )
+
+ de_anon_response = {
+ "output": {
+ "message": {
+ "role": "assistant",
+ "content": [{"text": "Alice called."}],
+ }
+ },
+ "stopReason": "end_turn",
+ }
+
+ async def mock_hook(data, user_api_key_dict, response):
+ assert response["output"]["message"]["content"][0]["text"] == "<PERSON_1> called."
+ return de_anon_response
+
+ result = await BedrockPassthroughGuardrailHandler.de_anonymize_event_stream(
+ body_bytes=stream_bytes,
+ proxy_logging_obj=self._make_proxy_logging(mock_hook),
+ user_api_key_dict=MagicMock(),
+ data={},
+ )
+
+ buf = EventStreamBuffer()
+ buf.add_data(result)
+ texts = [
+ json.loads(msg.payload)["delta"]["text"]
+ for msg in buf
+ if msg.headers.get(":event-type") == "contentBlockDelta"
+ ]
+ assert "".join(texts) == "Alice called."
+
+ @pytest.mark.asyncio
+ async def test_non_text_frames_preserved_unchanged(self):
+ from botocore.eventstream import EventStreamBuffer
+
+ stream_bytes = (
+ _build_event_stream_frame("messageStart", {"role": "assistant"})
+ + _build_event_stream_frame(
+ "contentBlockDelta",
+ {"contentBlockIndex": 0, "delta": {"text": "<PERSON_1>"}},
+ )
+ + _build_event_stream_frame("messageStop", {"stopReason": "end_turn"})
+ )
+
+ de_anon_response = {
+ "output": {"message": {"role": "assistant", "content": [{"text": "Bob"}]}},
+ "stopReason": "end_turn",
+ }
+
+ async def mock_hook(data, user_api_key_dict, response):
+ return de_anon_response
+
+ result = await BedrockPassthroughGuardrailHandler.de_anonymize_event_stream(
+ body_bytes=stream_bytes,
+ proxy_logging_obj=self._make_proxy_logging(mock_hook),
+ user_api_key_dict=MagicMock(),
+ data={},
+ )
+
+ buf = EventStreamBuffer()
+ buf.add_data(result)
+ event_types = [msg.headers.get(":event-type") for msg in buf]
+ assert "messageStart" in event_types
+ assert "messageStop" in event_types
+ assert event_types.count("contentBlockDelta") == 1
+
+ @pytest.mark.asyncio
+ async def test_no_text_deltas_returns_original_bytes(self):
+ stream_bytes = _build_event_stream_frame("messageStart", {"role": "assistant"})
+
+ hook_spy = AsyncMock()
+
+ result = await BedrockPassthroughGuardrailHandler.de_anonymize_event_stream(
+ body_bytes=stream_bytes,
+ proxy_logging_obj=self._make_proxy_logging(hook_spy),
+ user_api_key_dict=MagicMock(),
+ data={},
+ )
+
+ hook_spy.assert_not_called()
+ assert result is stream_bytes
+
+ @pytest.mark.asyncio
+ async def test_text_distributed_proportionally_across_chunks(self):
+ import json
+ from botocore.eventstream import EventStreamBuffer
+
+ stream_bytes = _build_event_stream_frame(
+ "contentBlockDelta",
+ {"contentBlockIndex": 0, "delta": {"text": "<PERSON_1>"}},
+ ) + _build_event_stream_frame(
+ "contentBlockDelta",
+ {"contentBlockIndex": 0, "delta": {"text": "<ORG>"}},
+ )
+
+ de_anon_response = {
+ "output": {
+ "message": {
+ "role": "assistant",
+ "content": [{"text": "John Acme"}],
+ }
+ },
+ "stopReason": "end_turn",
+ }
+
+ async def mock_hook(data, user_api_key_dict, response):
+ return de_anon_response
+
+ result = await BedrockPassthroughGuardrailHandler.de_anonymize_event_stream(
+ body_bytes=stream_bytes,
+ proxy_logging_obj=self._make_proxy_logging(mock_hook),
+ user_api_key_dict=MagicMock(),
+ data={},
+ )
+
+ buf = EventStreamBuffer()
+ buf.add_data(result)
+ texts = [
+ json.loads(msg.payload)["delta"]["text"]
+ for msg in buf
+ if msg.headers.get(":event-type") == "contentBlockDelta"
+ ]
+ assert "".join(texts) == "John Acme"
+ assert all(t != "" for t in texts), f"Expected no empty chunks, got: {texts}"
+
+ @pytest.mark.asyncio
+ async def test_trailing_bytes_after_last_frame_preserved(self):
+ import json
+ from botocore.eventstream import EventStreamBuffer
+
+ trailing = b"\xde\xad\xbe"
+ stream_bytes = (
+ _build_event_stream_frame(
+ "contentBlockDelta",
+ {"contentBlockIndex": 0, "delta": {"text": "<PERSON_1>"}},
+ )
+ + trailing
+ )
+
+ de_anon_response = {
+ "output": {"message": {"role": "assistant", "content": [{"text": "Jane"}]}},
+ "stopReason": "end_turn",
+ }
+
+ async def mock_hook(data, user_api_key_dict, response):
+ return de_anon_response
+
+ result = await BedrockPassthroughGuardrailHandler.de_anonymize_event_stream(
+ body_bytes=stream_bytes,
+ proxy_logging_obj=self._make_proxy_logging(mock_hook),
+ user_api_key_dict=MagicMock(),
+ data={},
+ )
+
+ assert result.endswith(trailing)
+ buf = EventStreamBuffer()
+ buf.add_data(result[: -len(trailing)])
+ texts = [
+ json.loads(msg.payload)["delta"]["text"]
+ for msg in buf
+ if msg.headers.get(":event-type") == "contentBlockDelta"
+ ]
+ assert "".join(texts) == "Jane"
+
+ @staticmethod
+ def _token_replacing_hook(mapping: dict):
+ async def mock_hook(data, user_api_key_dict, response):
+ for block in response["output"]["message"]["content"]:
+ text = block["text"]
+ for token, value in mapping.items():
+ text = text.replace(token, value)
+ block["text"] = text
+ return response
+
+ return mock_hook
+
+ def _decode_deltas(self, result: bytes) -> list:
+ import json
+ from botocore.eventstream import EventStreamBuffer
+
+ buf = EventStreamBuffer()
+ buf.add_data(result)
+ return [
+ json.loads(msg.payload)["delta"]
+ for msg in buf
+ if msg.headers.get(":event-type") == "contentBlockDelta"
+ ]
+
+ @pytest.mark.asyncio
+ async def test_reasoning_text_delta_de_anonymized(self):
+ """Reasoning deltas carry model output; their text must be guardrailed while the reasoning signature is left untouched."""
+ stream_bytes = (
+ _build_event_stream_frame("messageStart", {"role": "assistant"})
+ + _build_event_stream_frame(
+ "contentBlockDelta",
+ {
+ "contentBlockIndex": 0,
+ "delta": {
+ "reasoningContent": {
+ "text": "thinking about <PERSON_1>",
+ "signature": "sig-do-not-touch",
+ }
+ },
+ },
+ )
+ + _build_event_stream_frame("messageStop", {"stopReason": "end_turn"})
+ )
+
+ result = await BedrockPassthroughGuardrailHandler.de_anonymize_event_stream(
+ body_bytes=stream_bytes,
+ proxy_logging_obj=self._make_proxy_logging(
+ self._token_replacing_hook({"<PERSON_1>": "Alice"})
+ ),
+ user_api_key_dict=MagicMock(),
+ data={},
+ )
+
+ deltas = self._decode_deltas(result)
+ assert deltas[0]["reasoningContent"]["text"] == "thinking about Alice"
+ assert deltas[0]["reasoningContent"]["signature"] == "sig-do-not-touch"
+
+ @pytest.mark.asyncio
+ async def test_tool_use_input_delta_de_anonymized(self):
+ """toolUse.input deltas carry model-generated tool arguments and must be guardrailed instead of being forwarded raw."""
+ stream_bytes = _build_event_stream_frame(
+ "contentBlockDelta",
+ {"contentBlockIndex": 0, "delta": {"toolUse": {"input": '{"q":"<PERSON_1>"}'}}},
+ )
+
+ result = await BedrockPassthroughGuardrailHandler.de_anonymize_event_stream(
+ body_bytes=stream_bytes,
+ proxy_logging_obj=self._make_proxy_logging(
+ self._token_replacing_hook({"<PERSON_1>": "Alice"})
+ ),
+ user_api_key_dict=MagicMock(),
+ data={},
+ )
+
+ deltas = self._decode_deltas(result)
+ assert deltas[0]["toolUse"]["input"] == '{"q":"Alice"}'
+
+ @pytest.mark.asyncio
+ async def test_citations_content_delta_de_anonymized(self):
+ """citationsContent grounded text must be guardrailed while citation sources are preserved."""
+ stream_bytes = _build_event_stream_frame(
+ "contentBlockDelta",
+ {
+ "contentBlockIndex": 0,
+ "delta": {
+ "citationsContent": {
+ "content": [{"text": "Contact <PERSON_1>"}],
+ "citations": [{"source": "https://example.com", "title": "Example"}],
+ }
+ },
+ },
+ )
+
+ result = await BedrockPassthroughGuardrailHandler.de_anonymize_event_stream(
+ body_bytes=stream_bytes,
+ proxy_logging_obj=self._make_proxy_logging(
+ self._token_replacing_hook({"<PERSON_1>": "Alice"})
+ ),
+ user_api_key_dict=MagicMock(),
+ data={},
+ )
+
+ citations = self._decode_deltas(result)[0]["citationsContent"]
+ assert citations["content"][0]["text"] == "Contact Alice"
+ assert citations["citations"][0]["source"] == "https://example.com"
+
+ @pytest.mark.asyncio
+ async def test_text_and_reasoning_deltas_de_anonymized_independently(self):
+ """Distinct delta kinds must each be guardrailed and written back into their own field without bleeding the de-anonymized text across kinds."""
+ captured = {}
+
+ async def mock_hook(data, user_api_key_dict, response):
+ captured["texts"] = [
+ b["text"] for b in response["output"]["message"]["content"]
+ ]
+ mapping = {"<PERSON_1>": "Alice", "<ORG_2>": "Acme"}
+ for block in response["output"]["message"]["content"]:
+ text = block["text"]
+ for token, value in mapping.items():
+ text = text.replace(token, value)
+ block["text"] = text
+ return response
+
+ stream_bytes = _build_event_stream_frame(
+ "contentBlockDelta",
+ {"contentBlockIndex": 0, "delta": {"text": "Hi <PERSON_1>"}},
+ ) + _build_event_stream_frame(
+ "contentBlockDelta",
+ {"contentBlockIndex": 1, "delta": {"reasoningContent": {"text": "works at <ORG_2>"}}},
+ )
+
+ result = await BedrockPassthroughGuardrailHandler.de_anonymize_event_stream(
+ body_bytes=stream_bytes,
+ proxy_logging_obj=self._make_proxy_logging(mock_hook),
+ user_api_key_dict=MagicMock(),
+ data={},
+ )
+
+ assert "Hi <PERSON_1>" in captured["texts"]
+ assert "works at <ORG_2>" in captured["texts"]
+ deltas = self._decode_deltas(result)
+ assert deltas[0]["text"] == "Hi Alice"
+ assert deltas[1]["reasoningContent"]["text"] == "works at Acme"
+
+ @pytest.mark.asyncio
+ async def test_reasoning_signature_only_frame_left_unmodified(self):
+ """A reasoning delta carrying only a signature has no guardrailable text; it must be forwarded untouched and the guardrail must not run."""
+ stream_bytes = _build_event_stream_frame(
+ "contentBlockDelta",
+ {"contentBlockIndex": 0, "delta": {"reasoningContent": {"signature": "sig"}}},
+ )
+ hook_spy = AsyncMock()
+
+ result = await BedrockPassthroughGuardrailHandler.de_anonymize_event_stream(
+ body_bytes=stream_bytes,
+ proxy_logging_obj=self._make_proxy_logging(hook_spy),
+ user_api_key_dict=MagicMock(),
+ data={},
+ )
+
+ hook_spy.assert_not_called()
+ assert result is stream_bytes
diff --git a/tests/test_litellm/llms/pass_through/__init__.py b/tests/test_litellm/llms/pass_through/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/test_litellm/llms/pass_through/guardrail_translation/__init__.py b/tests/test_litellm/llms/pass_through/guardrail_translation/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/test_litellm/llms/pass_through/guardrail_translation/test_handler.py b/tests/test_litellm/llms/pass_through/guardrail_translation/test_handler.py
new file mode 100644
index 00000000000..f8bd83fc7df
--- /dev/null
+++ b/tests/test_litellm/llms/pass_through/guardrail_translation/test_handler.py
@@ -0,0 +1,224 @@
+"""
+Tests for LlmPassthroughRouteHandler and the guardrail_translation_mappings registry.
+
+Validates:
+- allm_passthrough_route is registered in the mappings (regression: this was the bug)
+- Bedrock provider is dispatched to BedrockPassthroughGuardrailHandler
+- Unknown provider skips apply_guardrail
+"""
+
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from litellm.llms.pass_through.guardrail_translation import (
+ guardrail_translation_mappings,
+)
+from litellm.llms.pass_through.guardrail_translation.handler import (
+ LlmPassthroughRouteHandler,
+)
+from litellm.types.utils import CallTypes
+
+
+class TestRegistry:
+ def test_allm_passthrough_route_registered(self):
+ """Regression: missing this mapping was the root cause of the bug."""
+ assert CallTypes.allm_passthrough_route in guardrail_translation_mappings
+
+ def test_allm_passthrough_route_maps_to_llm_passthrough_route_handler(self):
+ assert (
+ guardrail_translation_mappings[CallTypes.allm_passthrough_route]
+ is LlmPassthroughRouteHandler
+ )
+
+ def test_pass_through_still_registered(self):
+ from litellm.llms.pass_through.guardrail_translation.handler import (
+ PassThroughEndpointHandler,
+ )
+
+ assert (
+ guardrail_translation_mappings[CallTypes.pass_through]
+ is PassThroughEndpointHandler
+ )
+
+
+def _make_guardrail() -> MagicMock:
+ g = MagicMock()
+ g.guardrail_name = "test-guard"
+ g.apply_guardrail = AsyncMock(return_value={"texts": []})
+ g.skip_system_message_in_guardrail = False
+ g.skip_tool_message_in_guardrail = False
+ return g
+
+
+class TestLlmPassthroughRouteHandlerInput:
+ @pytest.mark.asyncio
+ async def test_bedrock_provider_delegates_to_bedrock_handler(self):
+ handler = LlmPassthroughRouteHandler()
+ data = {
+ "custom_llm_provider": "bedrock",
+ "endpoint": "model/anthropic.claude-3-sonnet/converse",
+ "data": {"messages": [{"role": "user", "content": [{"text": "hi"}]}]},
+ }
+ guardrail = _make_guardrail()
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ guardrail.apply_guardrail.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_unknown_provider_skips_apply_guardrail(self):
+ handler = LlmPassthroughRouteHandler()
+ data = {
+ "custom_llm_provider": "some_unknown_provider",
+ "endpoint": "v1/chat/completions",
+ "data": {"messages": [{"role": "user", "content": "hi"}]},
+ }
+ guardrail = _make_guardrail()
+
+ result = await handler.process_input_messages(
+ data=data, guardrail_to_apply=guardrail
+ )
+
+ guardrail.apply_guardrail.assert_not_called()
+ assert result is data
+
+ @pytest.mark.asyncio
+ async def test_missing_provider_skips(self):
+ handler = LlmPassthroughRouteHandler()
+ data = {"endpoint": "foo/bar", "data": {}}
+ guardrail = _make_guardrail()
+
+ result = await handler.process_input_messages(
+ data=data, guardrail_to_apply=guardrail
+ )
+
+ guardrail.apply_guardrail.assert_not_called()
+ assert result is data
+
+
+class TestLlmPassthroughRouteHandlerOutput:
+ @pytest.mark.asyncio
+ async def test_bedrock_provider_delegates_output_to_bedrock_handler(self):
+ handler = LlmPassthroughRouteHandler()
+ response = {
+ "output": {
+ "message": {
+ "role": "assistant",
+ "content": [{"text": "hello"}],
+ }
+ }
+ }
+ request_data = {
+ "custom_llm_provider": "bedrock",
+ "endpoint": "model/anthropic.claude-3-sonnet/converse",
+ }
+ guardrail = _make_guardrail()
+
+ await handler.process_output_response(
+ response=response,
+ guardrail_to_apply=guardrail,
+ request_data=request_data,
+ )
+
+ guardrail.apply_guardrail.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_unknown_provider_skips_output(self):
+ handler = LlmPassthroughRouteHandler()
+ response = {"some": "response"}
+ request_data = {"custom_llm_provider": "unknown"}
+ guardrail = _make_guardrail()
+
+ result = await handler.process_output_response(
+ response=response,
+ guardrail_to_apply=guardrail,
+ request_data=request_data,
+ )
+
+ guardrail.apply_guardrail.assert_not_called()
+ assert result is response
+
+
+class TestDeAnonymizeEventStream:
+ @pytest.mark.asyncio
+ async def test_bedrock_provider_dispatches_to_handler(self):
+ body = b"original-stream-bytes"
+ expected = b"de-anonymized-bytes"
+ proxy_logging_obj = MagicMock()
+ user_api_key_dict = MagicMock()
+
+ with patch(
+ "litellm.llms.bedrock.passthrough.guardrail_translation.handler."
+ "BedrockPassthroughGuardrailHandler.de_anonymize_event_stream",
+ new=AsyncMock(return_value=expected),
+ ) as mock_handler:
+ result = await LlmPassthroughRouteHandler.de_anonymize_event_stream(
+ body_bytes=body,
+ proxy_logging_obj=proxy_logging_obj,
+ user_api_key_dict=user_api_key_dict,
+ data={"custom_llm_provider": "bedrock"},
+ )
+
+ mock_handler.assert_awaited_once()
+ assert result == expected
+
+ @pytest.mark.asyncio
+ async def test_unknown_provider_returns_original_bytes(self):
+ body = b"original-stream-bytes"
+
+ result = await LlmPassthroughRouteHandler.de_anonymize_event_stream(
+ body_bytes=body,
+ proxy_logging_obj=MagicMock(),
+ user_api_key_dict=MagicMock(),
+ data={"custom_llm_provider": "anthropic"},
+ )
+
+ assert result is body
+
+ @pytest.mark.asyncio
+ async def test_missing_provider_returns_original_bytes(self):
+ body = b"original-stream-bytes"
+
+ result = await LlmPassthroughRouteHandler.de_anonymize_event_stream(
+ body_bytes=body,
+ proxy_logging_obj=MagicMock(),
+ user_api_key_dict=MagicMock(),
+ data={},
+ )
+
+ assert result is body
+
+
+class TestSupportsEventStreamDeAnonymization:
+ def test_bedrock_converse_stream_is_supported(self):
+ assert (
+ LlmPassthroughRouteHandler.supports_event_stream_de_anonymization(
+ "bedrock", "model/us.amazon.nova-lite-v1:0/converse-stream"
+ )
+ is True
+ )
+
+ def test_bedrock_invoke_stream_is_not_supported(self):
+ assert (
+ LlmPassthroughRouteHandler.supports_event_stream_de_anonymization(
+ "bedrock",
+ "model/us.amazon.nova-lite-v1:0/invoke-with-response-stream",
+ )
+ is False
+ )
+
+ def test_unknown_provider_is_not_supported(self):
+ assert (
+ LlmPassthroughRouteHandler.supports_event_stream_de_anonymization(
+ "anthropic", "model/foo/converse-stream"
+ )
+ is False
+ )
+
+ def test_missing_provider_is_not_supported(self):
+ assert (
+ LlmPassthroughRouteHandler.supports_event_stream_de_anonymization(
+ None, "model/foo/converse-stream"
+ )
+ is False
+ )
diff --git a/tests/test_litellm/proxy/guardrails/test_deferred_guardrail_logging.py b/tests/test_litellm/proxy/guardrails/test_deferred_guardrail_logging.py
index e9ff193e044..be92b6fc6c4 100644
--- a/tests/test_litellm/proxy/guardrails/test_deferred_guardrail_logging.py
+++ b/tests/test_litellm/proxy/guardrails/test_deferred_guardrail_logging.py
@@ -154,6 +154,59 @@ class TestHasPostCallGuardrails:
assert ProxyBaseLLMRequestProcessing._has_post_call_guardrails() is False
+class TestHasPostCallGuardrailsForPassthrough:
+ """Passthrough buffering must include event_hook=None guardrails.
+
+ Those guardrails run at post_call (should_run_guardrail treats None as
+ matching every hook); skipping the buffer would forward the raw upstream
+ body and bypass output processing. The check is scoped to the request via
+ should_run_guardrail so a guardrail that exists globally but is not
+ configured for this key/team does not turn the stream non-streaming.
+ """
+
+ @staticmethod
+ def _has(data: dict) -> bool:
+ return ProxyBaseLLMRequestProcessing(
+ data=data
+ )._has_post_call_guardrails_for_passthrough()
+
+ def test_returns_true_for_event_hook_none(self):
+ with patch("litellm.callbacks", [AllEventsGuardrail()]):
+ assert self._has({}) is True
+
+ def test_returns_true_for_post_call_guardrail(self):
+ with patch("litellm.callbacks", [PostCallGuardrail()]):
+ assert self._has({}) is True
+
+ def test_returns_false_for_pre_call_only(self):
+ with patch("litellm.callbacks", [PreCallGuardrail()]):
+ assert self._has({}) is False
+
+ def test_returns_false_for_no_callbacks(self):
+ with patch("litellm.callbacks", []):
+ assert self._has({}) is False
+
+ def test_ignores_non_guardrail_callbacks(self):
+ with patch("litellm.callbacks", ["langfuse", CustomLogger()]):
+ assert self._has({}) is False
+
+ def test_request_scoped_guardrail_not_configured_for_key(self):
+ """A non-default-on post_call guardrail must not force buffering for a
+ request whose key/team does not reference it."""
+
+ class OptInPostCall(CustomGuardrail):
+ def __init__(self):
+ super().__init__(
+ guardrail_name="opt-in-post",
+ default_on=False,
+ event_hook=GuardrailEventHooks.post_call,
+ )
+
+ with patch("litellm.callbacks", [OptInPostCall()]):
+ assert self._has({"metadata": {"guardrails": []}}) is False
+ assert self._has({"metadata": {"guardrails": ["opt-in-post"]}}) is True
+
+
# ---------------------------------------------------------------------------
# 2. Non-streaming: deferral flag → closure stored, create_task skipped
# ---------------------------------------------------------------------------
diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py b/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py
index 4eab1a4bf61..8bb7b52af14 100644
--- a/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py
+++ b/tests/test_litellm/proxy/pass_through_endpoints/test_llm_pass_through_endpoints.py
@@ -1674,6 +1674,56 @@ class TestBedrockLLMProxyRoute:
# and they're available in the router's deployment
assert mock_process.called
+ @pytest.mark.asyncio
+ async def test_key_guardrail_blocks_bedrock_converse_passthrough(self):
+ """
+ Regression: key/team guardrails must fire for /bedrock/model/.../converse requests.
+ Before the fix, CallTypes.allm_passthrough_route was not in the guardrail
+ translation registry, so UnifiedLLMGuardrails silently skipped all guardrails.
+ """
+ from fastapi import HTTPException
+
+ from litellm.integrations.custom_guardrail import CustomGuardrail
+ from litellm.llms.pass_through.guardrail_translation import (
+ guardrail_translation_mappings,
+ )
+ from litellm.types.utils import CallTypes, GenericGuardrailAPIInputs
+
+ assert CallTypes.allm_passthrough_route in guardrail_translation_mappings, (
+ "allm_passthrough_route missing from guardrail_translation_mappings; "
+ "this is the regression that lets guardrails bypass bedrock passthrough"
+ )
+
+ class _BlockingGuardrail(CustomGuardrail):
+ async def apply_guardrail(
+ self,
+ inputs: GenericGuardrailAPIInputs,
+ request_data: dict,
+ input_type: str,
+ logging_obj=None,
+ ) -> GenericGuardrailAPIInputs:
+ raise HTTPException(status_code=400, detail="Blocked by guardrail")
+
+ handler_cls = guardrail_translation_mappings[CallTypes.allm_passthrough_route]
+ handler = handler_cls()
+
+ guardrail = _BlockingGuardrail(guardrail_name="block-all")
+
+ data = {
+ "custom_llm_provider": "bedrock",
+ "endpoint": "model/anthropic.claude-3-sonnet-20240229-v1:0/converse",
+ "model": "anthropic.claude-3-sonnet-20240229-v1:0",
+ "data": {
+ "messages": [{"role": "user", "content": [{"text": "Hello"}]}],
+ },
+ }
+
+ with pytest.raises(HTTPException) as exc_info:
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert exc_info.value.status_code == 400
+ assert "Blocked by guardrail" in str(exc_info.value.detail)
+
class TestLLMPassthroughFactoryProxyRoute:
@pytest.mark.asyncio
diff --git a/tests/test_litellm/proxy/test_common_request_processing.py b/tests/test_litellm/proxy/test_common_request_processing.py
index b45b31cc67c..0b3a31d2de4 100644
--- a/tests/test_litellm/proxy/test_common_request_processing.py
+++ b/tests/test_litellm/proxy/test_common_request_processing.py
@@ -71,9 +71,190 @@ class TestProxyBaseLLMRequestProcessing:
assert result.headers["x-litellm-version"] == "test-version"
@pytest.mark.asyncio
- async def test_common_processing_pre_call_logic_pre_call_hook_receives_litellm_call_id(
+ async def test_base_passthrough_process_llm_request_returns_fastapi_response_from_guardrails(self, monkeypatch):
+ """Post-call guardrails return a FastAPI Response; must not call httpx aread()."""
+ import json
+
+ processing_obj = ProxyBaseLLMRequestProcessing(data={})
+ guardrailed_body = {
+ "output": {"message": {"content": [{"text": "masked"}]}},
+ "stopReason": "end_turn",
+ }
+
+ async def fake_base_process_llm_request(**kwargs):
+ return Response(
+ content=json.dumps(guardrailed_body).encode(),
+ status_code=200,
+ media_type="application/json",
+ )
+
+ monkeypatch.setattr(
+ processing_obj,
+ "base_process_llm_request",
+ fake_base_process_llm_request,
+ )
+
+ result = await processing_obj.base_passthrough_process_llm_request(
+ request=MagicMock(spec=Request),
+ fastapi_response=Response(),
+ user_api_key_dict=MagicMock(spec=UserAPIKeyAuth),
+ proxy_logging_obj=MagicMock(spec=ProxyLogging),
+ general_settings={},
+ proxy_config=MagicMock(spec=ProxyConfig),
+ select_data_generator=MagicMock(),
+ model="bedrock-test-model",
+ )
+
+ assert isinstance(result, Response)
+ assert json.loads(result.body) == guardrailed_body
+
+ @pytest.mark.asyncio
+ async def test_handle_non_streaming_allm_passthrough_route_forwards_upstream_headers(
+ self, monkeypatch
+ ):
+ """The guardrail JSON path must forward upstream response headers (e.g.
+ x-amzn-requestid) alongside the x-litellm-* headers, matching the
+ non-guardrail passthrough path, while dropping length headers that no
+ longer match the rewritten body."""
+ processing_obj = ProxyBaseLLMRequestProcessing(
+ data={"custom_llm_provider": "bedrock"}
+ )
+ monkeypatch.setattr(
+ processing_obj,
+ "_has_post_call_guardrails_for_passthrough",
+ lambda: True,
+ )
+
+ upstream = httpx.Response(
+ status_code=200,
+ content=b'{"output": {"message": {"content": [{"text": "hi"}]}}}',
+ headers={
+ "content-type": "application/json",
+ "x-amzn-requestid": "bedrock-request-id",
+ "content-length": "999",
+ },
+ )
+
+ proxy_logging_obj = MagicMock(spec=ProxyLogging)
+
+ async def fake_post_call_success_hook(**kwargs):
+ return kwargs["response"]
+
+ proxy_logging_obj.post_call_success_hook = fake_post_call_success_hook
+ proxy_logging_obj.post_call_response_headers_hook = AsyncMock(return_value={})
+
+ result = await processing_obj._handle_non_streaming_allm_passthrough_route(
+ response=upstream,
+ proxy_logging_obj=proxy_logging_obj,
+ user_api_key_dict=MagicMock(spec=UserAPIKeyAuth),
+ custom_headers={"x-litellm-call-id": "test-call-id"},
+ request_headers={},
+ )
+
+ assert isinstance(result, Response)
+ assert result.status_code == 200
+ assert result.headers["x-amzn-requestid"] == "bedrock-request-id"
+ assert result.headers["x-litellm-call-id"] == "test-call-id"
+ assert result.headers["content-length"] == str(len(result.body))
+
+ @pytest.mark.asyncio
+ async def test_handle_event_stream_allm_passthrough_route_forwards_upstream_headers(
self, monkeypatch
):
+ """The guardrail event-stream branch must also forward upstream response
+ headers alongside the x-litellm-* headers."""
+ processing_obj = ProxyBaseLLMRequestProcessing(
+ data={"custom_llm_provider": "bedrock"}
+ )
+ monkeypatch.setattr(
+ processing_obj,
+ "_has_post_call_guardrails_for_passthrough",
+ lambda: True,
+ )
+
+ async def fake_event_stream(**kwargs):
+ return b"rewritten-frames"
+
+ monkeypatch.setattr(
+ processing_obj,
+ "_handle_event_stream_allm_passthrough_route",
+ fake_event_stream,
+ )
+
+ upstream = httpx.Response(
+ status_code=200,
+ content=b"original-frames",
+ headers={
+ "content-type": "application/vnd.amazon.eventstream",
+ "x-amzn-requestid": "bedrock-request-id",
+ },
+ )
+
+ proxy_logging_obj = MagicMock(spec=ProxyLogging)
+ proxy_logging_obj.post_call_response_headers_hook = AsyncMock(return_value={})
+
+ result = await processing_obj._handle_non_streaming_allm_passthrough_route(
+ response=upstream,
+ proxy_logging_obj=proxy_logging_obj,
+ user_api_key_dict=MagicMock(spec=UserAPIKeyAuth),
+ custom_headers={"x-litellm-call-id": "test-call-id"},
+ request_headers={},
+ )
+
+ assert isinstance(result, Response)
+ assert result.body == b"rewritten-frames"
+ assert result.headers["x-amzn-requestid"] == "bedrock-request-id"
+ assert result.headers["x-litellm-call-id"] == "test-call-id"
+
+ @pytest.mark.asyncio
+ async def test_handle_non_streaming_allm_passthrough_route_applies_response_headers_hook(
+ self, monkeypatch
+ ):
+ """Guardrailed non-streaming passthrough responses must include headers
+ injected by post_call_response_headers_hook, matching the headers a
+ non-guardrailed passthrough response would carry."""
+ processing_obj = ProxyBaseLLMRequestProcessing(
+ data={"custom_llm_provider": "bedrock"}
+ )
+ monkeypatch.setattr(
+ processing_obj,
+ "_has_post_call_guardrails_for_passthrough",
+ lambda: True,
+ )
+
+ upstream = httpx.Response(
+ status_code=200,
+ content=b'{"output": {"message": {"content": [{"text": "hi"}]}}}',
+ headers={"content-type": "application/json"},
+ )
+
+ proxy_logging_obj = MagicMock(spec=ProxyLogging)
+
+ async def fake_post_call_success_hook(**kwargs):
+ return kwargs["response"]
+
+ proxy_logging_obj.post_call_success_hook = fake_post_call_success_hook
+ proxy_logging_obj.post_call_response_headers_hook = AsyncMock(
+ return_value={"x-litellm-custom": "from-hook"}
+ )
+
+ result = await processing_obj._handle_non_streaming_allm_passthrough_route(
+ response=upstream,
+ proxy_logging_obj=proxy_logging_obj,
+ user_api_key_dict=MagicMock(spec=UserAPIKeyAuth),
+ custom_headers={"x-litellm-call-id": "test-call-id"},
+ request_headers={"authorization": "Bearer sk-test"},
+ )
+
+ assert isinstance(result, Response)
+ assert result.headers["x-litellm-custom"] == "from-hook"
+ assert result.headers["x-litellm-call-id"] == "test-call-id"
+ proxy_logging_obj.post_call_response_headers_hook.assert_awaited_once()
+ _, kwargs = proxy_logging_obj.post_call_response_headers_hook.call_args
+ assert kwargs["request_headers"] == {"authorization": "Bearer sk-test"}
+
+ @pytest.mark.asyncio
+ async def test_common_processing_pre_call_logic_pre_call_hook_receives_litellm_call_id(self, monkeypatch):
processing_obj = ProxyBaseLLMRequestProcessing(data={})
mock_request = MagicMock(spec=Request)
mock_request.headers = {}
@@ -81,16 +262,12 @@ class TestProxyBaseLLMRequestProcessing:
async def mock_add_litellm_data_to_request(*args, **kwargs):
return {}
- async def mock_common_processing_pre_call_logic(
- user_api_key_dict, data, call_type
- ):
+ async def mock_common_processing_pre_call_logic(user_api_key_dict, data, call_type):
data_copy = copy.deepcopy(data)
return data_copy
mock_proxy_logging_obj = MagicMock(spec=ProxyLogging)
- mock_proxy_logging_obj.pre_call_hook = AsyncMock(
- side_effect=mock_common_processing_pre_call_logic
- )
+ mock_proxy_logging_obj.pre_call_hook = AsyncMock(side_effect=mock_common_processing_pre_call_logic)
monkeypatch.setattr(
litellm.proxy.common_request_processing,
"add_litellm_data_to_request",
@@ -126,9 +303,7 @@ class TestProxyBaseLLMRequestProcessing:
pytest.fail("litellm_call_id is not a valid UUID")
assert data_passed["litellm_call_id"] == returned_data["litellm_call_id"]
- def test_add_dd_apm_tags_for_litellm_call_id_uses_dd_tracing_helper(
- self, monkeypatch
- ):
+ def test_add_dd_apm_tags_for_litellm_call_id_uses_dd_tracing_helper(self, monkeypatch):
mock_set_active_span_tag = MagicMock(return_value=True)
import litellm.proxy.dd_span_tagger
@@ -140,14 +315,10 @@ class TestProxyBaseLLMRequestProcessing:
DDSpanTagger.tag_call_id("test-call-id")
- mock_set_active_span_tag.assert_called_once_with(
- "litellm.call_id", "test-call-id"
- )
+ mock_set_active_span_tag.assert_called_once_with("litellm.call_id", "test-call-id")
@pytest.mark.asyncio
- async def test_should_apply_hierarchical_router_settings_as_override(
- self, monkeypatch
- ):
+ async def test_should_apply_hierarchical_router_settings_as_override(self, monkeypatch):
"""
Test that hierarchical router settings are stored as router_settings_override
instead of creating a full user_config with model_list.
@@ -162,16 +333,12 @@ class TestProxyBaseLLMRequestProcessing:
async def mock_add_litellm_data_to_request(*args, **kwargs):
return {}
- async def mock_common_processing_pre_call_logic(
- user_api_key_dict, data, call_type
- ):
+ async def mock_common_processing_pre_call_logic(user_api_key_dict, data, call_type):
data_copy = copy.deepcopy(data)
return data_copy
mock_proxy_logging_obj = MagicMock(spec=ProxyLogging)
- mock_proxy_logging_obj.pre_call_hook = AsyncMock(
- side_effect=mock_common_processing_pre_call_logic
- )
+ mock_proxy_logging_obj.pre_call_hook = AsyncMock(side_effect=mock_common_processing_pre_call_logic)
monkeypatch.setattr(
litellm.proxy.common_request_processing,
"add_litellm_data_to_request",
@@ -187,9 +354,7 @@ class TestProxyBaseLLMRequestProcessing:
"timeout": 30.0,
"num_retries": 3,
}
- mock_proxy_config._get_hierarchical_router_settings = AsyncMock(
- return_value=mock_router_settings
- )
+ mock_proxy_config._get_hierarchical_router_settings = AsyncMock(return_value=mock_router_settings)
mock_llm_router = MagicMock()
@@ -243,24 +408,18 @@ class TestProxyBaseLLMRequestProcessing:
# Test with stream timeout header
headers_with_timeout = {"x-litellm-stream-timeout": "30.5"}
- result = LiteLLMProxyRequestSetup._get_stream_timeout_from_request(
- headers_with_timeout
- )
+ result = LiteLLMProxyRequestSetup._get_stream_timeout_from_request(headers_with_timeout)
assert result == 30.5
# Test without stream timeout header
headers_without_timeout = {}
- result = LiteLLMProxyRequestSetup._get_stream_timeout_from_request(
- headers_without_timeout
- )
+ result = LiteLLMProxyRequestSetup._get_stream_timeout_from_request(headers_without_timeout)
assert result is None
# Test with invalid header value (should raise ValueError when converting to float)
headers_with_invalid = {"x-litellm-stream-timeout": "invalid"}
with pytest.raises(ValueError):
- LiteLLMProxyRequestSetup._get_stream_timeout_from_request(
- headers_with_invalid
- )
+ LiteLLMProxyRequestSetup._get_stream_timeout_from_request(headers_with_invalid)
@pytest.mark.asyncio
async def test_build_litellm_proxy_success_headers_from_llm_response(self):
@@ -355,9 +514,7 @@ class TestProxyBaseLLMRequestProcessing:
)
assert headers["x-litellm-model-id"] == "stream-model-id"
- assert headers["x-litellm-model-api-base"] == (
- "https://generativelanguage.googleapis.com/v1beta"
- )
+ assert headers["x-litellm-model-api-base"] == ("https://generativelanguage.googleapis.com/v1beta")
assert headers["llm_provider-x"] == "y"
@pytest.mark.asyncio
@@ -797,9 +954,7 @@ class TestProxyBaseLLMRequestProcessing:
assert "x-litellm-key-spend" in headers_1
expected_spend_1 = 0.001 + 0.0005 # Initial spend + current request cost
- assert float(headers_1["x-litellm-key-spend"]) == pytest.approx(
- expected_spend_1, abs=1e-10
- )
+ assert float(headers_1["x-litellm-key-spend"]) == pytest.approx(expected_spend_1, abs=1e-10)
assert float(headers_1["x-litellm-response-cost"]) == response_cost_1
# Test case 2: response_cost is provided as string
@@ -812,9 +967,7 @@ class TestProxyBaseLLMRequestProcessing:
assert "x-litellm-key-spend" in headers_2
expected_spend_2 = 0.001 + 0.0003 # Initial spend + current request cost
- assert float(headers_2["x-litellm-key-spend"]) == pytest.approx(
- expected_spend_2, abs=1e-10
- )
+ assert float(headers_2["x-litellm-key-spend"]) == pytest.approx(expected_spend_2, abs=1e-10)
# Test case 3: response_cost is None (should use original spend)
headers_3 = ProxyBaseLLMRequestProcessing.get_custom_headers(
@@ -824,9 +977,7 @@ class TestProxyBaseLLMRequestProcessing:
)
assert "x-litellm-key-spend" in headers_3
- assert (
- float(headers_3["x-litellm-key-spend"]) == 0.001
- ) # Should use original spend
+ assert float(headers_3["x-litellm-key-spend"]) == 0.001 # Should use original spend
# Test case 4: response_cost is 0 (should not change spend)
headers_4 = ProxyBaseLLMRequestProcessing.get_custom_headers(
@@ -836,9 +987,7 @@ class TestProxyBaseLLMRequestProcessing:
)
assert "x-litellm-key-spend" in headers_4
- assert (
- float(headers_4["x-litellm-key-spend"]) == 0.001
- ) # Should remain unchanged for 0 cost
+ assert float(headers_4["x-litellm-key-spend"]) == 0.001 # Should remain unchanged for 0 cost
# Test case 5: user_api_key_dict.spend is None (should default to 0.0)
mock_user_api_key_dict.spend = None
@@ -860,9 +1009,7 @@ class TestProxyBaseLLMRequestProcessing:
)
assert "x-litellm-key-spend" in headers_6
- assert (
- float(headers_6["x-litellm-key-spend"]) == 0.001
- ) # Should use original spend
+ assert float(headers_6["x-litellm-key-spend"]) == 0.001 # Should use original spend
# Test case 7: response_cost is invalid string (should fallback to original spend)
headers_7 = ProxyBaseLLMRequestProcessing.get_custom_headers(
@@ -872,9 +1019,7 @@ class TestProxyBaseLLMRequestProcessing:
)
assert "x-litellm-key-spend" in headers_7
- assert (
- float(headers_7["x-litellm-key-spend"]) == 0.001
- ) # Should use original spend on error
+ assert float(headers_7["x-litellm-key-spend"]) == 0.001 # Should use original spend on error
@pytest.mark.asyncio
async def test_queue_time_seconds_is_set_in_metadata(self, monkeypatch):
@@ -935,12 +1080,10 @@ class TestProxyBaseLLMRequestProcessing:
# Verify queue_time_seconds is set and non-negative
metadata = returned_data.get("metadata", {})
- assert (
- "queue_time_seconds" in metadata
- ), "queue_time_seconds should be set in metadata"
- assert (
- metadata["queue_time_seconds"] >= 0.5
- ), f"queue_time_seconds should be at least 0.5, got {metadata['queue_time_seconds']}"
+ assert "queue_time_seconds" in metadata, "queue_time_seconds should be set in metadata"
+ assert metadata["queue_time_seconds"] >= 0.5, (
+ f"queue_time_seconds should be at least 0.5, got {metadata['queue_time_seconds']}"
+ )
@pytest.mark.asyncio
@@ -1091,9 +1234,7 @@ class TestCommonRequestProcessingHelpers:
the original status code instead of hardcoding 500.
"""
mock_gen = AsyncMock()
- mock_gen.__anext__.side_effect = HTTPException(
- status_code=400, detail="Content blocked by guardrail"
- )
+ mock_gen.__anext__.side_effect = HTTPException(status_code=400, detail="Content blocked by guardrail")
response = await create_response(mock_gen, "text/event-stream", {})
assert response.status_code == 400
@@ -1187,14 +1328,8 @@ class TestCommonRequestProcessingHelpers:
response = await create_response(mock_gen, "text/event-stream", {})
content = await self.consume_stream(response)
payload = json.loads(content[0][len("data: ") :].strip())
- assert (
- payload["error"]["message"]
- == "MCP request blocked: no rewritable argument field present"
- )
- assert (
- payload["error"]["provider_specific_fields"]["error"]["code"]
- == "panw_prisma_airs_blocked"
- )
+ assert payload["error"]["message"] == "MCP request blocked: no rewritable argument field present"
+ assert payload["error"]["provider_specific_fields"]["error"]["code"] == "panw_prisma_airs_blocked"
async def test_serialize_http_exception_detail_helper(self):
"""Direct unit coverage for the L1 helper across all branches."""
@@ -1205,15 +1340,11 @@ class TestCommonRequestProcessingHelpers:
assert _serialize_http_exception_detail("plain") == ("plain", None)
- msg, fields = _serialize_http_exception_detail(
- {"error": "Violated", "extra": "x"}
- )
+ msg, fields = _serialize_http_exception_detail({"error": "Violated", "extra": "x"})
assert msg == "Violated"
assert fields == {"error": "Violated", "extra": "x"}
- msg, fields = _serialize_http_exception_detail(
- {"error": {"message": "blocked", "code": "x"}}
- )
+ msg, fields = _serialize_http_exception_detail({"error": {"message": "blocked", "code": "x"}})
assert msg == "blocked"
assert fields == {"error": {"message": "blocked", "code": "x"}}
@@ -1253,9 +1384,7 @@ class TestCommonRequestProcessingHelpers:
yield "data: [DONE]\n\n"
custom_headers = {"X-Custom-Header": "TestValue"}
- response = await create_response(
- mock_generator(), "text/event-stream", custom_headers
- )
+ response = await create_response(mock_generator(), "text/event-stream", custom_headers)
assert response.headers["x-custom-header"] == "TestValue"
async def test_create_streaming_response_disables_proxy_buffering(self):
@@ -1275,9 +1404,7 @@ class TestCommonRequestProcessingHelpers:
error_stream.__anext__.side_effect = ValueError("boom")
for generator in (normal_stream(), empty_stream(), error_stream):
- response = await create_response(
- generator, "text/event-stream", {"X-Custom-Header": "keep"}
- )
+ response = await create_response(generator, "text/event-stream", {"X-Custom-Header": "keep"})
assert isinstance(response, StreamingResponse)
assert response.headers["x-accel-buffering"] == "no"
assert response.headers["cache-control"] == "no-cache"
@@ -1376,9 +1503,9 @@ class TestCommonRequestProcessingHelpers:
for i, call in enumerate(actual_calls):
args, kwargs = call
- assert (
- args[0] == "streaming.chunk.yield"
- ), f"Call {i} should have operation name 'streaming.chunk.yield', got {args[0]}"
+ assert args[0] == "streaming.chunk.yield", (
+ f"Call {i} should have operation name 'streaming.chunk.yield', got {args[0]}"
+ )
async def test_create_streaming_response_skips_dd_trace_when_disabled(self):
"""When DD tracing is disabled (the default), the per-chunk span
@@ -1559,9 +1686,7 @@ class TestOverrideOpenAIResponseModel:
# _hidden_params is an attribute (not a dict key) accessed via getattr
response_obj = MagicMock()
response_obj.model = fallback_model
- response_obj._hidden_params = {
- "additional_headers": {"x-litellm-attempted-fallbacks": 1}
- }
+ response_obj._hidden_params = {"additional_headers": {"x-litellm-attempted-fallbacks": 1}}
# Call the function - should preserve fallback model
_override_openai_response_model(
@@ -1688,9 +1813,7 @@ class TestOverrideOpenAIResponseModel:
# Create a mock object response
response_obj = MagicMock()
response_obj.model = downstream_model
- response_obj._hidden_params = {
- "additional_headers": {"x-litellm-attempted-fallbacks": None}
- }
+ response_obj._hidden_params = {"additional_headers": {"x-litellm-attempted-fallbacks": None}}
# Call the function - should override to requested model
_override_openai_response_model(
@@ -1735,9 +1858,7 @@ class TestOverrideOpenAIResponseModel:
# Create a mock object response
response_obj = MagicMock()
response_obj.model = fallback_model
- response_obj._hidden_params = {
- "additional_headers": {"x-litellm-attempted-fallbacks": 1}
- }
+ response_obj._hidden_params = {"additional_headers": {"x-litellm-attempted-fallbacks": 1}}
# Call the function with None requested_model
_override_openai_response_model(
@@ -1903,10 +2024,7 @@ class TestIsAzureModelRouterRequest:
def test_detects_model_router_with_underscore(self):
assert _is_azure_model_router_request("azure_ai/model_router") is True
- assert (
- _is_azure_model_router_request("azure_ai/model_router/my-deployment")
- is True
- )
+ assert _is_azure_model_router_request("azure_ai/model_router/my-deployment") is True
def test_detects_model_router_with_hyphen(self):
assert _is_azure_model_router_request("azure_ai/model-router") is True
@@ -2130,9 +2248,7 @@ class TestDDSpanTaggerTagRequest:
def test_tags_key_alias_and_model(self):
"""key_alias and requested_model are set on the span when present."""
- user_key = self._make_user_api_key_dict(
- key_alias="my-prod-key", token="hashed123"
- )
+ user_key = self._make_user_api_key_dict(key_alias="my-prod-key", token="hashed123")
with patch("litellm.proxy.dd_span_tagger.set_active_span_tag") as mock_set_tag:
DDSpanTagger.tag_request(
@@ -2166,9 +2282,7 @@ class TestDDSpanTaggerTagRequest:
requested_model="claude-3-5-sonnet",
)
- mock_set_tag.assert_called_once_with(
- "litellm.requested_model", "claude-3-5-sonnet"
- )
+ mock_set_tag.assert_called_once_with("litellm.requested_model", "claude-3-5-sonnet")
class TestHasAttributeErrorInChain:
@@ -2257,9 +2371,7 @@ class TestHandleLLMApiExceptionDictDetail:
)
proxy_exc = await self._invoke(exc)
assert proxy_exc.message == "Violated guardrail policy"
- assert (
- proxy_exc.provider_specific_fields["guardrail_name"] == "bedrock-pii-guard"
- )
+ assert proxy_exc.provider_specific_fields["guardrail_name"] == "bedrock-pii-guard"
# No Python repr leakage of the dict into the message field.
assert "{'error':" not in proxy_exc.message
@@ -2317,9 +2429,7 @@ class TestAsyncStreamingDataGeneratorFastPath:
proxy_logging_obj = ProxyLogging(user_api_key_cache=MagicMock())
hook_spy = AsyncMock(side_effect=lambda **kw: kw["response"])
- monkeypatch.setattr(
- proxy_logging_obj, "async_post_call_streaming_hook", hook_spy
- )
+ monkeypatch.setattr(proxy_logging_obj, "async_post_call_streaming_hook", hook_spy)
chunks = [b"event: a\ndata: {}\n\n", b"event: b\ndata: {}\n\n"]
out = [
@@ -2352,9 +2462,7 @@ class TestAsyncStreamingDataGeneratorFastPath:
proxy_logging_obj = ProxyLogging(user_api_key_cache=MagicMock())
hook_spy = AsyncMock(side_effect=lambda **kw: kw["response"])
- monkeypatch.setattr(
- proxy_logging_obj, "async_post_call_streaming_hook", hook_spy
- )
+ monkeypatch.setattr(proxy_logging_obj, "async_post_call_streaming_hook", hook_spy)
out = [
c
@@ -2372,3 +2480,458 @@ class TestAsyncStreamingDataGeneratorFastPath:
hook_spy.assert_awaited_once()
ProxyLogging._callback_capabilities_cache.clear()
+
+
+class TestAllmPassthroughRoutePostCallGuardrails:
+ """
+ Regression: non-streaming allm_passthrough_route responses are httpx.Response objects.
+ The generic post_call_success_hook path passes them as-is, but our Bedrock guardrail
+ handler short-circuits on non-dict inputs. The fix buffers JSON responses before the
+ hook so guardrails receive a dict (and output_parse_pii de-anonymisation works).
+ """
+
+ def _make_guardrail_cb(self, name: str = "presidio-pre-guard") -> MagicMock:
+ from litellm.integrations.custom_guardrail import CustomGuardrail
+ from litellm.types.guardrails import GuardrailEventHooks
+
+ cb = MagicMock(spec=CustomGuardrail)
+ cb.guardrail_name = name
+ cb.event_hook = [GuardrailEventHooks.pre_call.value, GuardrailEventHooks.post_call.value]
+ cb._event_hook_is_event_type = lambda et: et.value in cb.event_hook
+ cb.should_run_guardrail = MagicMock(return_value=True)
+ return cb
+
+ @pytest.mark.asyncio
+ async def test_post_call_hook_receives_parsed_dict_not_httpx_response(self, monkeypatch):
+ """
+ post_call_success_hook must be called with the parsed JSON dict when the
+ non-streaming allm_passthrough_route response is application/json.
+ """
+ import json
+
+ bedrock_response_body = {
+ "output": {
+ "message": {
+ "role": "assistant",
+ "content": [{"text": "Hello, <PERSON_1>!"}],
+ }
+ },
+ "stopReason": "end_turn",
+ "usage": {"inputTokens": 5, "outputTokens": 8},
+ }
+
+ httpx_response = httpx.Response(
+ status_code=200,
+ content=json.dumps(bedrock_response_body).encode(),
+ headers={"content-type": "application/json"},
+ )
+
+ received_responses = []
+
+ async def capture_hook(data, user_api_key_dict, response):
+ received_responses.append(response)
+ return response
+
+ cb = self._make_guardrail_cb()
+ monkeypatch.setattr(litellm, "callbacks", [cb])
+ ProxyLogging._callback_capabilities_cache.clear()
+
+ proxy_logging_obj = ProxyLogging(user_api_key_cache=MagicMock())
+ monkeypatch.setattr(proxy_logging_obj, "post_call_success_hook", capture_hook)
+
+ with patch.object(ProxyBaseLLMRequestProcessing, "_has_post_call_guardrails_for_passthrough", return_value=True):
+ processing_obj = ProxyBaseLLMRequestProcessing(data={})
+ result = await processing_obj._handle_non_streaming_allm_passthrough_route(
+ response=httpx_response,
+ proxy_logging_obj=proxy_logging_obj,
+ user_api_key_dict=MagicMock(spec=UserAPIKeyAuth),
+ custom_headers={},
+ request_headers={},
+ )
+
+ assert len(received_responses) == 1
+ assert isinstance(received_responses[0], dict), (
+ "post_call_success_hook must receive parsed dict, not httpx.Response"
+ )
+ assert received_responses[0]["stopReason"] == "end_turn"
+ assert isinstance(result, Response)
+ body = json.loads(result.body)
+ assert body["stopReason"] == "end_turn"
+
+ ProxyLogging._callback_capabilities_cache.clear()
+
+ @pytest.mark.asyncio
+ async def test_non_dict_hook_return_falls_back_to_original_body(self, monkeypatch):
+ """
+ When post_call_success_hook returns a non-dict (e.g. a non-serializable
+ object), the JSON branch must return the original body bytes unchanged
+ rather than raising a TypeError from json.dumps.
+ """
+ import json
+
+ original = {
+ "output": {"message": {"role": "assistant", "content": [{"text": "hi"}]}},
+ "stopReason": "end_turn",
+ }
+ httpx_response = httpx.Response(
+ status_code=200,
+ content=json.dumps(original).encode(),
+ headers={"content-type": "application/json"},
+ )
+
+ async def non_dict_hook(data, user_api_key_dict, response):
+ return object()
+
+ cb = self._make_guardrail_cb()
+ monkeypatch.setattr(litellm, "callbacks", [cb])
+ ProxyLogging._callback_capabilities_cache.clear()
+
+ proxy_logging_obj = ProxyLogging(user_api_key_cache=MagicMock())
+ monkeypatch.setattr(proxy_logging_obj, "post_call_success_hook", non_dict_hook)
+
+ with patch.object(ProxyBaseLLMRequestProcessing, "_has_post_call_guardrails_for_passthrough", return_value=True):
+ processing_obj = ProxyBaseLLMRequestProcessing(data={})
+ result = await processing_obj._handle_non_streaming_allm_passthrough_route(
+ response=httpx_response,
+ proxy_logging_obj=proxy_logging_obj,
+ user_api_key_dict=MagicMock(spec=UserAPIKeyAuth),
+ custom_headers={},
+ request_headers={},
+ )
+
+ assert isinstance(result, Response)
+ assert json.loads(result.body) == original
+
+ ProxyLogging._callback_capabilities_cache.clear()
+
+ @pytest.mark.asyncio
+ async def test_malformed_json_body_passes_through_without_500(self, monkeypatch):
+ """
+ A 2xx response advertising application/json but carrying a non-JSON body
+ must pass the original bytes through unchanged instead of raising
+ JSONDecodeError (which would surface as a 500). The post-call hook is
+ never invoked since there is no dict to guardrail.
+ """
+ malformed_body = b"not-json-at-all"
+ httpx_response = httpx.Response(
+ status_code=200,
+ content=malformed_body,
+ headers={"content-type": "application/json"},
+ )
+
+ cb = self._make_guardrail_cb()
+ monkeypatch.setattr(litellm, "callbacks", [cb])
+ ProxyLogging._callback_capabilities_cache.clear()
+
+ proxy_logging_obj = ProxyLogging(user_api_key_cache=MagicMock())
+ hook_spy = AsyncMock()
+ monkeypatch.setattr(proxy_logging_obj, "post_call_success_hook", hook_spy)
+
+ with patch.object(ProxyBaseLLMRequestProcessing, "_has_post_call_guardrails_for_passthrough", return_value=True):
+ processing_obj = ProxyBaseLLMRequestProcessing(data={})
+ result = await processing_obj._handle_non_streaming_allm_passthrough_route(
+ response=httpx_response,
+ proxy_logging_obj=proxy_logging_obj,
+ user_api_key_dict=MagicMock(spec=UserAPIKeyAuth),
+ custom_headers={},
+ request_headers={},
+ )
+
+ hook_spy.assert_not_awaited()
+ assert isinstance(result, Response)
+ assert result.status_code == 200
+ assert result.body == malformed_body
+
+ ProxyLogging._callback_capabilities_cache.clear()
+
+ @pytest.mark.asyncio
+ async def test_no_aread_when_no_post_call_guardrails(self, monkeypatch):
+ """
+ When _has_post_call_guardrails_for_passthrough() is False the httpx
+ response must not be read — the caller handles streaming or error paths
+ normally.
+ """
+ import json
+
+ httpx_response = httpx.Response(
+ status_code=200,
+ content=json.dumps({"output": "x"}).encode(),
+ headers={"content-type": "application/json"},
+ )
+ spy_read = AsyncMock(wraps=httpx_response.aread)
+ httpx_response.aread = spy_read
+
+ monkeypatch.setattr(litellm, "callbacks", [])
+ ProxyLogging._callback_capabilities_cache.clear()
+
+ proxy_logging_obj = ProxyLogging(user_api_key_cache=MagicMock())
+ hook_spy = AsyncMock()
+ monkeypatch.setattr(proxy_logging_obj, "post_call_success_hook", hook_spy)
+
+ with patch.object(ProxyBaseLLMRequestProcessing, "_has_post_call_guardrails_for_passthrough", return_value=False):
+ processing_obj = ProxyBaseLLMRequestProcessing(data={})
+ result = await processing_obj._handle_non_streaming_allm_passthrough_route(
+ response=httpx_response,
+ proxy_logging_obj=proxy_logging_obj,
+ user_api_key_dict=MagicMock(spec=UserAPIKeyAuth),
+ custom_headers={},
+ request_headers={},
+ )
+
+ spy_read.assert_not_called()
+ hook_spy.assert_not_called()
+ assert result is None
+
+ ProxyLogging._callback_capabilities_cache.clear()
+
+
+def _build_event_stream_frame(event_type: str, payload: dict) -> bytes:
+ import json
+ import struct
+ from botocore.eventstream import crc32 as esm_crc32
+
+ payload_bytes = json.dumps(payload, separators=(",", ":")).encode()
+
+ def _encode_str_header(name: str, value: str) -> bytes:
+ name_b = name.encode()
+ value_b = value.encode()
+ return (
+ struct.pack("!B", len(name_b))
+ + name_b
+ + struct.pack("!B", 7) # type 7 = string
+ + struct.pack("!H", len(value_b))
+ + value_b
+ )
+
+ headers_bytes = (
+ _encode_str_header(":event-type", event_type)
+ + _encode_str_header(":content-type", "application/json")
+ + _encode_str_header(":message-type", "event")
+ )
+
+ headers_length = len(headers_bytes)
+ total_length = 12 + headers_length + len(payload_bytes) + 4
+ prelude = struct.pack("!II", total_length, headers_length)
+ prelude_crc_val = esm_crc32(prelude) & 0xFFFFFFFF
+ prelude_crc_b = struct.pack("!I", prelude_crc_val)
+ part_for_msg = prelude_crc_b + headers_bytes + payload_bytes
+ msg_crc_val = esm_crc32(part_for_msg, prelude_crc_val) & 0xFFFFFFFF
+ msg_crc_b = struct.pack("!I", msg_crc_val)
+ return prelude + prelude_crc_b + headers_bytes + payload_bytes + msg_crc_b
+
+
+class TestEventStreamAllmPassthroughRoute:
+ @pytest.mark.asyncio
+ async def test_bedrock_provider_dispatches_to_handler(self):
+ stream_bytes = _build_event_stream_frame("messageStart", {"role": "assistant"})
+ expected_bytes = _build_event_stream_frame("messageStart", {"role": "assistant"}) + b"extra"
+
+ proxy_logging_obj = MagicMock()
+ user_api_key_dict = MagicMock(spec=UserAPIKeyAuth)
+
+ with patch(
+ "litellm.llms.bedrock.passthrough.guardrail_translation.handler.BedrockPassthroughGuardrailHandler.de_anonymize_event_stream",
+ new=AsyncMock(return_value=expected_bytes),
+ ) as mock_handler:
+ processing_obj = ProxyBaseLLMRequestProcessing(data={"custom_llm_provider": "bedrock"})
+ result = await processing_obj._handle_event_stream_allm_passthrough_route(
+ body_bytes=stream_bytes,
+ proxy_logging_obj=proxy_logging_obj,
+ user_api_key_dict=user_api_key_dict,
+ )
+
+ mock_handler.assert_awaited_once()
+ assert result == expected_bytes
+
+ @pytest.mark.asyncio
+ async def test_non_bedrock_provider_returns_original_bytes(self):
+ stream_bytes = _build_event_stream_frame("messageStart", {"role": "assistant"})
+ proxy_logging_obj = MagicMock()
+
+ processing_obj = ProxyBaseLLMRequestProcessing(data={"custom_llm_provider": "anthropic"})
+ result = await processing_obj._handle_event_stream_allm_passthrough_route(
+ body_bytes=stream_bytes,
+ proxy_logging_obj=proxy_logging_obj,
+ user_api_key_dict=MagicMock(spec=UserAPIKeyAuth),
+ )
+
+ assert result is stream_bytes
+
+ @pytest.mark.asyncio
+ async def test_non_streaming_response_includes_custom_headers(self):
+ import json
+
+ body = {"output": {"message": {"role": "assistant", "content": [{"text": "hi"}]}}}
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.headers = {"content-type": "application/json", "content-length": "99"}
+ mock_response.aread = AsyncMock(return_value=json.dumps(body).encode())
+
+ async def mock_hook(data, user_api_key_dict, response):
+ return response
+
+ proxy_logging_obj = MagicMock()
+ proxy_logging_obj.post_call_success_hook = mock_hook
+ proxy_logging_obj.post_call_response_headers_hook = AsyncMock(return_value={})
+
+ custom_headers = {
+ "x-litellm-call-id": "test-call-123",
+ "x-litellm-model-id": "bedrock/claude",
+ "content-length": "99",
+ }
+
+ with patch.object(ProxyBaseLLMRequestProcessing, "_has_post_call_guardrails_for_passthrough", return_value=True):
+ processing_obj = ProxyBaseLLMRequestProcessing(data={})
+ result = await processing_obj._handle_non_streaming_allm_passthrough_route(
+ response=mock_response,
+ proxy_logging_obj=proxy_logging_obj,
+ user_api_key_dict=MagicMock(spec=UserAPIKeyAuth),
+ custom_headers=custom_headers,
+ request_headers={},
+ )
+
+ assert result is not None
+ assert result.headers.get("x-litellm-call-id") == "test-call-123"
+ assert result.headers.get("x-litellm-model-id") == "bedrock/claude"
+ # content-length from custom_headers is filtered; Starlette sets the correct value from body
+ assert result.headers.get("content-length") != "99"
+
+
+class TestAllmPassthroughStreamingProviderGate:
+ """
+ Regression: the streaming-buffer gate for allm_passthrough_route must only
+ fire for provider+endpoint pairs that have an event-stream guardrail handler
+ able to rewrite frames (Bedrock converse-stream).
+
+ A non-Bedrock streaming passthrough response must keep streaming even when a
+ post-call guardrail is registered globally, instead of being silently
+ buffered into a non-streaming Response. A Bedrock endpoint the Converse
+ handler cannot rewrite (e.g. invoke-with-response-stream) must also keep
+ streaming. Only converse-stream is buffered so its frames can be
+ de-anonymized.
+ """
+
+ def _build_processing_obj(
+ self, custom_llm_provider: str, endpoint: str = ""
+ ) -> ProxyBaseLLMRequestProcessing:
+ logging_obj = MagicMock()
+ logging_obj.litellm_call_id = "call-123"
+ logging_obj.cost_breakdown = None
+ data = {
+ "custom_llm_provider": custom_llm_provider,
+ "endpoint": endpoint,
+ "litellm_logging_obj": logging_obj,
+ }
+ return ProxyBaseLLMRequestProcessing(data=data)
+
+ async def _run(self, processing_obj, monkeypatch, chunks):
+ import litellm.proxy.common_request_processing as crp
+ from litellm.proxy._types import UserAPIKeyAuth as RealUserAPIKeyAuth
+
+ async def streaming_response():
+ for chunk in chunks:
+ yield chunk
+
+ async def fake_route_request(**kwargs):
+ async def _llm_call():
+ return streaming_response()
+
+ return _llm_call()
+
+ monkeypatch.setattr(crp, "route_request", fake_route_request)
+
+ proxy_logging_obj = MagicMock(spec=ProxyLogging)
+ proxy_logging_obj.during_call_hook = AsyncMock(return_value=None)
+ proxy_logging_obj.update_request_status = AsyncMock(return_value=None)
+ proxy_logging_obj.post_call_response_headers_hook = AsyncMock(return_value=None)
+ proxy_logging_obj.post_call_success_hook = AsyncMock()
+
+ return await processing_obj.base_process_llm_request(
+ request=MagicMock(spec=Request, headers={}),
+ fastapi_response=Response(),
+ user_api_key_dict=RealUserAPIKeyAuth(api_key="sk-test"),
+ route_type="allm_passthrough_route",
+ proxy_logging_obj=proxy_logging_obj,
+ general_settings={},
+ proxy_config=MagicMock(spec=ProxyConfig),
+ select_data_generator=None,
+ llm_router=None,
+ skip_pre_call_logic=True,
+ )
+
+ @pytest.mark.asyncio
+ async def test_non_bedrock_stream_is_not_buffered(self, monkeypatch):
+ processing_obj = self._build_processing_obj("anthropic")
+ chunks = [b"chunk-1", b"chunk-2"]
+
+ with patch.object(
+ ProxyBaseLLMRequestProcessing,
+ "_has_post_call_guardrails",
+ return_value=False,
+ ), patch.object(
+ ProxyBaseLLMRequestProcessing,
+ "_has_post_call_guardrails_for_passthrough",
+ return_value=True,
+ ):
+ result = await self._run(processing_obj, monkeypatch, chunks)
+
+ assert isinstance(result, StreamingResponse)
+ streamed = [chunk async for chunk in result.body_iterator]
+ assert streamed == chunks
+
+ @pytest.mark.asyncio
+ async def test_bedrock_converse_stream_is_buffered_through_handler(
+ self, monkeypatch
+ ):
+ processing_obj = self._build_processing_obj(
+ "bedrock", "model/us.amazon.nova-lite-v1:0/converse-stream"
+ )
+ chunks = [b"raw-1", b"raw-2"]
+
+ with patch.object(
+ ProxyBaseLLMRequestProcessing,
+ "_has_post_call_guardrails",
+ return_value=False,
+ ), patch.object(
+ ProxyBaseLLMRequestProcessing,
+ "_has_post_call_guardrails_for_passthrough",
+ return_value=True,
+ ), patch(
+ "litellm.llms.bedrock.passthrough.guardrail_translation.handler."
+ "BedrockPassthroughGuardrailHandler.de_anonymize_event_stream",
+ new=AsyncMock(return_value=b"modified-body"),
+ ) as mock_handler:
+ result = await self._run(processing_obj, monkeypatch, chunks)
+
+ assert isinstance(result, Response)
+ assert not isinstance(result, StreamingResponse)
+ assert result.body == b"modified-body"
+ assert result.headers["content-type"] == "application/vnd.amazon.eventstream"
+ mock_handler.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_bedrock_invoke_stream_is_not_buffered(self, monkeypatch):
+ processing_obj = self._build_processing_obj(
+ "bedrock", "model/us.amazon.nova-lite-v1:0/invoke-with-response-stream"
+ )
+ chunks = [b"raw-1", b"raw-2"]
+
+ with patch.object(
+ ProxyBaseLLMRequestProcessing,
+ "_has_post_call_guardrails",
+ return_value=False,
+ ), patch.object(
+ ProxyBaseLLMRequestProcessing,
+ "_has_post_call_guardrails_for_passthrough",
+ return_value=True,
+ ), patch(
+ "litellm.llms.bedrock.passthrough.guardrail_translation.handler."
+ "BedrockPassthroughGuardrailHandler.de_anonymize_event_stream",
+ new=AsyncMock(return_value=b"modified-body"),
+ ) as mock_handler:
+ result = await self._run(processing_obj, monkeypatch, chunks)
+
+ assert isinstance(result, StreamingResponse)
+ streamed = [chunk async for chunk in result.body_iterator]
+ assert streamed == chunks
+ mock_handler.assert_not_awaited()
diff --git a/ui/litellm-dashboard/e2e_tests/helpers/navigation.ts b/ui/litellm-dashboard/e2e_tests/helpers/navigation.ts
index 6ca18890f7a..6b5e7f7bb8d 100644
--- a/ui/litellm-dashboard/e2e_tests/helpers/navigation.ts
+++ b/ui/litellm-dashboard/e2e_tests/helpers/navigation.ts
@@ -6,8 +6,20 @@ import { Page as PlaywrightPage, expect } from "@playwright/test";
* Waits for the sidebar to be visible before returning.
*/
export async function navigateToPage(page: PlaywrightPage, pageEnum: Page): Promise<void> {
- await page.goto(`/ui?page=${pageEnum}`);
- await page.waitForLoadState("networkidle");
+ // A fresh deep-link can race the auth bootstrap: the app briefly treats the
+ // session as anonymous, bounces through /ui/login, and lands back on the
+ // default page with the ?page= param dropped. Re-issue the navigation until
+ // the requested page sticks (auth is warm by the second load) so callers never
+ // assert against the default page.
+ for (let attempt = 0; attempt < 3; attempt++) {
+ await page.goto(`/ui?page=${pageEnum}`);
+ await page.waitForLoadState("networkidle");
+ const url = new URL(page.url());
+ const onLegacyRoot = url.pathname.replace(/\/+$/, "").endsWith("/ui");
+ if (!onLegacyRoot || url.searchParams.get("page") === pageEnum) {
+ break;
+ }
+ }
// Dismiss the "Quick feedback" popup if it appears
await dismissFeedbackPopup(page);
}