The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(model_armor): sanitize error details by default (#33908)
yucheng-berri049c6836d205
diff --git a/litellm/proxy/guardrails/guardrail_hooks/model_armor/__init__.py b/litellm/proxy/guardrails/guardrail_hooks/model_armor/__init__.pyindex 5e62ab96f0c..d91ddffa0c1 100644--- a/litellm/proxy/guardrails/guardrail_hooks/model_armor/__init__.py+++ b/litellm/proxy/guardrails/guardrail_hooks/model_armor/__init__.py@@ -27,6 +27,7 @@ def initialize_guardrail(litellm_params: "LitellmParams", guardrail: "Guardrail"mask_response_content=litellm_params.mask_response_content,fail_on_error=litellm_params.fail_on_error,skip_unscannable_attachments=litellm_params.skip_unscannable_attachments,+ sanitize_error_detail=litellm_params.sanitize_error_detail,)litellm.logging_callback_manager.add_litellm_callback(_model_armor_callback)diff --git a/litellm/proxy/guardrails/guardrail_hooks/model_armor/model_armor.py b/litellm/proxy/guardrails/guardrail_hooks/model_armor/model_armor.pyindex 32a3cebfca0..31535a5b569 100644--- a/litellm/proxy/guardrails/guardrail_hooks/model_armor/model_armor.py+++ b/litellm/proxy/guardrails/guardrail_hooks/model_armor/model_armor.py@@ -11,6 +11,7 @@ from typing import (Union,)+import httpxfrom fastapi import HTTPExceptionif TYPE_CHECKING:@@ -35,7 +36,8 @@ from litellm.proxy.guardrails.guardrail_hooks.model_armor.file_scanning import (MODEL_ARMOR_MAX_FILE_SIZE_BYTES,plan_file_scans,)-from litellm.types.guardrails import GuardrailEventHooks+from litellm.constants import DEFAULT_MAX_RECURSE_DEPTH+from litellm.types.guardrails import GuardrailEventHooks, LitellmParamsfrom litellm.types.llms.openai import AllMessageValuesfrom litellm.types.utils import (CallTypes,@@ -50,6 +52,33 @@ from litellm.types.utils import (GUARDRAIL_NAME = "model_armor"+class ModelArmorAPIError(Exception):+ """Model Armor API failure (non-2xx), distinct from a content-block decision so+ hooks can honor fail_on_error. The detail is already sanitized per configuration."""++ def __init__(self, detail: str):+ super().__init__(detail)+ self.detail = detail+++_SCANNED_CONTENT_KEYS = frozenset({"text", "sanitizedText", "findings", "maliciousUriMatchedItems"})++RedactablePayload = Union[dict, list, str, int, float, bool, None]+++def _redact_scanned_content(payload: RedactablePayload, depth: int = 0) -> RedactablePayload:+ if depth >= DEFAULT_MAX_RECURSE_DEPTH:+ return "[REDACTED]"+ if isinstance(payload, dict):+ return {+ key: "[REDACTED]" if key in _SCANNED_CONTENT_KEYS else _redact_scanned_content(value, depth + 1)+ for key, value in payload.items()+ }+ if isinstance(payload, list):+ return [_redact_scanned_content(item, depth + 1) for item in payload]+ return payload++class ModelArmorGuardrail(CustomGuardrail, VertexBase):"""Google Cloud Model Armor Guardrail integration for LiteLLM.@@ -76,6 +105,7 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):location: Optional[str] = None,credentials: Optional[Any] = None,api_endpoint: Optional[str] = None,+ sanitize_error_detail: "bool | None" = True,**kwargs,):# Set supported event hooks if not already provided@@ -98,6 +128,7 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):self.location = location or "us-central1"self.credentials = credentialsself.api_endpoint = api_endpoint+ self.sanitize_error_detail = sanitize_error_detail is not False# Store optional paramsself.optional_params = kwargs@@ -141,6 +172,67 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):verbose_proxy_logger.debug("Model Armor: Skipping non-ModelResponse type: %s", type(response).__name__)return ""+ def _build_api_error_detail(self, status_code: int, response_text: str) -> str:+ if self.sanitize_error_detail:+ return f"Model Armor API error (upstream {status_code})"+ return f"Model Armor API error (upstream {status_code}): {response_text}"++ def _build_block_error_detail(self, message: str, armor_response: RedactablePayload) -> dict:+ if self.sanitize_error_detail:+ return {"error": message}+ return {"error": message, "model_armor_response": armor_response}++ def _build_logging_response(self, armor_response: RedactablePayload) -> RedactablePayload:+ if self.sanitize_error_detail:+ return _redact_scanned_content(armor_response)+ return armor_response++ def _raise_if_fail_closed(self, e: ModelArmorAPIError) -> None:+ if self.optional_params.get("fail_on_error", True):+ raise e from None++ def update_in_memory_litellm_params(self, litellm_params: LitellmParams) -> None:+ super().update_in_memory_litellm_params(litellm_params)+ self.sanitize_error_detail = self.sanitize_error_detail is not False++ def _log_request_debug(+ self,+ url: str,+ body: dict,+ file_bytes: "bytes | None",+ file_type: "str | None",+ ) -> None:+ # Never log byteData: it is the full base64 of the scanned document. Log only its+ # type and size so debug deployments cannot leak the contents the guardrail inspects.+ if file_bytes is not None and file_type is not None:+ verbose_proxy_logger.debug(+ "Model Armor file request - URL: %s, byteDataType: %s, bytes: %d",+ url,+ file_type,+ len(file_bytes),+ )+ elif self.sanitize_error_detail:+ verbose_proxy_logger.debug("Model Armor request - URL: %s", url)+ else:+ verbose_proxy_logger.debug(+ "Model Armor request - URL: %s, Body: %s",+ url,+ body,+ )++ def _log_response_debug(self, status_code: int, response_text: str) -> None:+ if self.sanitize_error_detail:+ verbose_proxy_logger.debug(+ "Model Armor response - Status: %s",+ status_code,+ )+ else:+ verbose_proxy_logger.debug(+ "Model Armor response - Status: %s, Body: %s",+ status_code,+ response_text,+ )+async def make_model_armor_request(self,content: Optional[str] = None,@@ -185,48 +277,37 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):"Authorization": f"Bearer {access_token}",}- # Never log byteData: it is the full base64 of the scanned document. Log only its- # type and size so debug deployments cannot leak the contents the guardrail inspects.- if file_bytes is not None and file_type is not None:- verbose_proxy_logger.debug(- "Model Armor file request - URL: %s, byteDataType: %s, bytes: %d",- url,- file_type,- len(file_bytes),- )- else:- verbose_proxy_logger.debug(- "Model Armor request - URL: %s, Body: %s",- url,- body,- )+ self._log_request_debug(url=url, body=body, file_bytes=file_bytes, file_type=file_type)# Make requestif self.async_handler is None:raise ValueError("Async handler not initialized")- response = await self.async_handler.post(- url=url,- json=body,- headers=headers,- )+ try:+ response = await self.async_handler.post(+ url=url,+ json=body,+ headers=headers,+ )+ except httpx.HTTPStatusError as e:+ detail = self._build_api_error_detail(e.response.status_code, e.response.text)+ verbose_proxy_logger.error(+ "Model Armor API error - Status: %s, Detail: %s",+ e.response.status_code,+ detail,+ )+ raise ModelArmorAPIError(detail) from None- verbose_proxy_logger.debug(- "Model Armor response - Status: %s, Body: %s",- response.status_code,- response.text,- )+ self._log_response_debug(status_code=response.status_code, response_text=response.text)if response.status_code != 200:+ detail = self._build_api_error_detail(response.status_code, response.text)verbose_proxy_logger.error(- "Model Armor API error - Status: %s, Response: %s",+ "Model Armor API error - Status: %s, Detail: %s",response.status_code,- response.text,- )- raise HTTPException(- status_code=400,- detail=f"Model Armor API error (upstream {response.status_code}): {response.text}",+ detail,)+ raise ModelArmorAPIError(detail)json_response = response.json()if hasattr(json_response, "__await__"):@@ -351,9 +432,7 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):Override to store only the Model Armor API response, not the entire data dict.This prevents circular references in logging."""- # Retrieve the Model Armor response & status stored on the per-request `metadata` object.metadata = request_data.get("metadata", {}) if isinstance(request_data, dict) else {}-guardrail_response = metadata.get("_model_armor_response", {})# Determine status – default to "success" but prefer the explicit value if present.@@ -444,6 +523,9 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):file_bytes=attachment.file_bytes,file_type=attachment.byte_data_type,)+ except ModelArmorAPIError as e:+ self._raise_if_fail_closed(e)+ continueexcept HTTPException:raiseexcept Exception as e:@@ -459,7 +541,8 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):# otherwise a PII-only (SDP deidentify) document would pass through unscrubbed.blocked = self._should_block_content(armor_response, allow_sanitization=False)metadata["_model_armor_response"] = self._append_armor_response(- metadata.get("_model_armor_response"), armor_response+ metadata.get("_model_armor_response"),+ self._build_logging_response(armor_response),)if blocked or metadata.get("_model_armor_status") == "blocked":metadata["_model_armor_status"] = "blocked"@@ -469,10 +552,7 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):if blocked:raise HTTPException(status_code=400,- detail={- "error": "Content blocked by Model Armor",- "model_armor_response": armor_response,- },+ detail=self._build_block_error_detail("Content blocked by Model Armor", armor_response),)@log_guardrail_information@@ -530,7 +610,8 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):metadata = data.setdefault("metadata", {}) # ensures metadata exists and is unique per request# Accumulate so a prior file scan on the same request is not overwritten by this text scan.metadata["_model_armor_response"] = self._append_armor_response(- metadata.get("_model_armor_response"), armor_response+ metadata.get("_model_armor_response"),+ self._build_logging_response(armor_response),)# Pre-compute guardrail status for downstream logging. A blocked response will eventually raise# an HTTPException, however in scenarios where the caller decides to ignore the exception (e.g.@@ -548,10 +629,7 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):if blocked:raise HTTPException(status_code=400,- detail={- "error": "Content blocked by Model Armor",- "model_armor_response": armor_response,- },+ detail=self._build_block_error_detail("Content blocked by Model Armor", armor_response),)# If mask_request_content is enabled, update messages with sanitized content@@ -565,6 +643,8 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):data["messages"] = set_last_user_message(messages, sanitized_content)+ except ModelArmorAPIError as e:+ self._raise_if_fail_closed(e)except HTTPException:raiseexcept Exception as e:@@ -625,7 +705,8 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):metadata = data.setdefault("metadata", {})# Accumulate so a prior file scan on the same request is not overwritten by this text scan.metadata["_model_armor_response"] = self._append_armor_response(- metadata.get("_model_armor_response"), armor_response+ metadata.get("_model_armor_response"),+ self._build_logging_response(armor_response),)if blocked or metadata.get("_model_armor_status") == "blocked":metadata["_model_armor_status"] = "blocked"@@ -640,10 +721,7 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):if blocked:raise HTTPException(status_code=400,- detail={- "error": "Content blocked by Model Armor",- "model_armor_response": armor_response,- },+ detail=self._build_block_error_detail("Content blocked by Model Armor", armor_response),)# If mask_request_content is enabled, update messages with sanitized content@@ -656,6 +734,8 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):data["messages"] = set_last_user_message(messages, sanitized_content)+ except ModelArmorAPIError as e:+ self._raise_if_fail_closed(e)except HTTPException:raiseexcept Exception as e:@@ -698,7 +778,7 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):# Attach Model Armor response & status to this request's metadata to prevent race conditionsif isinstance(armor_response, dict):model_armor_logged_object = {- "model_armor_response": armor_response,+ "model_armor_response": self._build_logging_response(armor_response),"model_armor_status": ("blocked"if self._should_block_content(@@ -729,10 +809,7 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):if self._should_block_content(armor_response, allow_sanitization=self.mask_response_content):raise HTTPException(status_code=400,- detail={- "error": "Response blocked by Model Armor",- "model_armor_response": armor_response,- },+ detail=self._build_block_error_detail("Response blocked by Model Armor", armor_response),)# If mask_response_content is enabled, update response with sanitized content@@ -746,6 +823,8 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):if choice.message.content:choice.message.content = sanitized_content+ except ModelArmorAPIError as e:+ self._raise_if_fail_closed(e)except HTTPException:raiseexcept Exception as e:@@ -790,7 +869,7 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):# Attach Model Armor response & status to this request's metadata to avoid race conditionsif isinstance(request_data, dict):metadata = request_data.setdefault("metadata", {})- metadata["_model_armor_response"] = armor_response+ metadata["_model_armor_response"] = self._build_logging_response(armor_response)metadata["_model_armor_status"] = ("blocked" if self._should_block_content(armor_response) else "success")@@ -809,10 +888,10 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):if self._should_block_content(armor_response):raise HTTPException(status_code=400,- detail={- "error": "Streaming response blocked by Model Armor",- "model_armor_response": armor_response,- },+ detail=self._build_block_error_detail(+ "Streaming response blocked by Model Armor",+ armor_response,+ ),)# Apply sanitization if enabled@@ -831,6 +910,11 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):yield chunkreturn+ except ModelArmorAPIError as e:+ if self.optional_params.get("fail_on_error", True):+ error_obj = {"message": e.detail, "code": "500"}+ yield f"data: {json.dumps({'error': error_obj})}\n\n"+ returnexcept HTTPException as e:# Yield error as SSE event so create_response() detects it and# returns a proper JSON error response with the correct status code.diff --git a/litellm/types/guardrails.py b/litellm/types/guardrails.pyindex 3605ab95d1b..47d93fc2d7a 100644--- a/litellm/types/guardrails.py+++ b/litellm/types/guardrails.py@@ -826,6 +826,13 @@ class BaseLitellmParams(ContentFilterConfigModel): # works for new and patch up"while fail_on_error still governs real Model Armor API errors. Default False blocks them."),)+ sanitize_error_detail: Optional[bool] = Field(+ default=True,+ description=(+ "For guardrail='model_armor': omit the raw Model Armor response from "+ "caller-facing errors and logs by default. Set False to restore verbose output."+ ),+ )additional_provider_specific_params: Optional[Dict[str, Any]] = Field(default=None,diff --git a/litellm/types/proxy/guardrails/guardrail_hooks/model_armor.py b/litellm/types/proxy/guardrails/guardrail_hooks/model_armor.pyindex 628ac0442de..d5e601ce8ea 100644--- a/litellm/types/proxy/guardrails/guardrail_hooks/model_armor.py+++ b/litellm/types/proxy/guardrails/guardrail_hooks/model_armor.py@@ -20,6 +20,13 @@ class ModelArmorGuardrailConfigModel(GuardrailConfigModel):default=True,description="Whether to fail the request if Model Armor encounters an error",)+ sanitize_error_detail: Optional[bool] = Field(+ default=True,+ description=(+ "Omit the raw Model Armor response from caller-facing errors and logs "+ "by default. Set False to restore verbose output."+ ),+ )@staticmethoddef ui_friendly_name() -> str:diff --git a/tests/code_coverage_tests/recursive_detector.py b/tests/code_coverage_tests/recursive_detector.pyindex e08d703d21f..fa81efde5db 100644--- a/tests/code_coverage_tests/recursive_detector.py+++ b/tests/code_coverage_tests/recursive_detector.py@@ -55,6 +55,7 @@ IGNORE_FUNCTIONS = ["_freeze_for_dedupe", # OTEL: max depth set (default 16, _FREEZE_MAX_DEPTH); fails closed by returning repr(value) at the cap."apply_json_merge_patch", # max depth set (_MAX_MERGE_DEPTH=64); fails closed by raising ValueError at the cap."_filter_mcp_argument_value", # max depth set (DEFAULT_MAX_RECURSE_DEPTH); fails closed by blocking the MCP call at the cap.+ "_redact_scanned_content", # max depth set (DEFAULT_MAX_RECURSE_DEPTH); fails closed by returning "[REDACTED]" at the cap.]diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_model_armor.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_model_armor.pyindex 07c40aa763d..4021f922877 100644--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_model_armor.py+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_model_armor.py@@ -10,14 +10,19 @@ import pytestsys.path.insert(0, os.path.abspath("../../../../.."))+import httpxfrom fastapi import HTTPExceptionimport litellmimport litellm.types.utilsfrom litellm._logging import verbose_proxy_loggerfrom litellm.caching import DualCache+from litellm.llms.custom_httpx.http_handler import MaskedHTTPStatusErrorfrom litellm.proxy._types import UserAPIKeyAuthfrom litellm.proxy.guardrails.guardrail_hooks.model_armor import ModelArmorGuardrail+from litellm.proxy.guardrails.guardrail_hooks.model_armor.model_armor import (+ ModelArmorAPIError,+)from litellm.types.guardrails import GuardrailEventHooks@@ -403,8 +408,9 @@ async def test_model_armor_api_error_handling():"metadata": {"guardrails": ["model-armor-test"]},}- # Should raise HTTPException for API error- with pytest.raises(HTTPException) as exc_info:+ # An API failure propagates as ModelArmorAPIError, not a content-block+ # HTTPException, so guardrail trace status stays guardrail_failed_to_respond+ with pytest.raises(ModelArmorAPIError) as exc_info:await guardrail.async_pre_call_hook(user_api_key_dict=mock_user_api_key_dict,cache=mock_cache,@@ -412,9 +418,8 @@ async def test_model_armor_api_error_handling():call_type="completion",)- assert exc_info.value.status_code == 400- assert "Model Armor API error" in str(exc_info.value.detail)- assert "upstream 500" in str(exc_info.value.detail)+ assert exc_info.value.detail == "Model Armor API error (upstream 500)"+ assert "Internal Server Error" not in str(exc_info.value.detail)@pytest.mark.asyncio@@ -622,7 +627,7 @@ async def test_model_armor_streaming_block_yields_sse_error():@pytest.mark.asyncio-async def test_model_armor_api_failure_returns_400():+async def test_model_armor_api_failure_raises_sanitized_error():"""Test that Model Armor API failures raise HTTP 400, not the upstream status code."""guardrail = ModelArmorGuardrail(template_id="test-template",@@ -643,15 +648,544 @@ async def test_model_armor_api_failure_returns_400():with patch.object(guardrail.async_handler, "post", AsyncMock(return_value=mock_response)):- with pytest.raises(HTTPException) as exc_info:+ with pytest.raises(ModelArmorAPIError) as exc_info:await guardrail.make_model_armor_request(content="test content",source="user_prompt",)- # Should be 400, NOT the upstream 500- assert exc_info.value.status_code == 400- assert "upstream 500" in str(exc_info.value.detail)+ assert exc_info.value.detail == "Model Armor API error (upstream 500)"+ assert "Internal Server Error" not in str(exc_info.value.detail)++[email protected]("sanitize", [True, False])+async def test_model_armor_error_output_sanitization(sanitize: bool):+ marker = "SYNTHETIC_MODEL_ARMOR_MARKER"+ guardrail = ModelArmorGuardrail(+ template_id="test-template",+ project_id="test-project",+ guardrail_name="model-armor-test",+ sanitize_error_detail=sanitize,+ )+ guardrail._ensure_access_token_async = AsyncMock(+ return_value=("test-token", "test-project")+ )++ error_response = AsyncMock(status_code=500, text=marker)+ with patch.object(+ guardrail.async_handler, "post", AsyncMock(return_value=error_response)+ ), patch.object(verbose_proxy_logger, "debug") as debug_log, patch.object(+ verbose_proxy_logger, "error"+ ) as error_log, pytest.raises(ModelArmorAPIError) as exc_info:+ await guardrail.make_model_armor_request(content=marker)++ direct_log = f"{debug_log.call_args_list} {error_log.call_args_list}"+ if sanitize:+ assert marker not in str(exc_info.value.detail)+ assert marker not in direct_log+ else:+ assert marker in str(exc_info.value.detail)+ assert marker in direct_log++[email protected]("fail_on_error", [True, False])+async def test_model_armor_api_error_honors_fail_open(fail_on_error: bool):+ """An upstream API failure (raised by the real handler as MaskedHTTPStatusError)+ must block with a sanitized 400 when fail_on_error is true and let the request+ proceed when the operator configured fail-open."""+ marker = "SYNTHETIC_FAIL_OPEN_MARKER"+ guardrail = ModelArmorGuardrail(+ template_id="test-template",+ project_id="test-project",+ guardrail_name="model-armor-test",+ fail_on_error=fail_on_error,+ )+ guardrail._ensure_access_token_async = AsyncMock(+ return_value=("test-token", "test-project")+ )+ guardrail.should_run_guardrail = Mock(return_value=True)++ request = httpx.Request("POST", "https://modelarmor.example.test/v1")+ upstream = httpx.Response(503, content=marker.encode(), request=request)+ original = httpx.HTTPStatusError("Service Unavailable", request=request, response=upstream)+ masked = MaskedHTTPStatusError(original, message=marker, text=marker)++ request_data = {+ "model": "gpt-4",+ "messages": [{"role": "user", "content": "synthetic input"}],+ "metadata": {},+ }++ with patch.object(guardrail.async_handler, "post", AsyncMock(side_effect=masked)):+ if fail_on_error:+ with pytest.raises(ModelArmorAPIError) as exc_info:+ await guardrail.async_pre_call_hook(+ user_api_key_dict=UserAPIKeyAuth(),+ cache=MagicMock(spec=DualCache),+ data=request_data,+ call_type="completion",+ )+ assert exc_info.value.detail == "Model Armor API error (upstream 503)"+ assert marker not in str(exc_info.value.detail)+ else:+ result = await guardrail.async_pre_call_hook(+ user_api_key_dict=UserAPIKeyAuth(),+ cache=MagicMock(spec=DualCache),+ data=request_data,+ call_type="completion",+ )+ assert result is request_data++[email protected]("fail_on_error", [True, False])+async def test_model_armor_api_error_fail_open_moderation_and_post_call(fail_on_error: bool):+ """The during-call and post-call hooks route API failures through fail_on_error+ exactly like pre-call: sanitized 400 when failing closed, pass-through when open."""+ api_error = ModelArmorAPIError("Model Armor API error (upstream 503)")+ guardrail = ModelArmorGuardrail(+ template_id="test-template",+ project_id="test-project",+ guardrail_name="model-armor-test",+ fail_on_error=fail_on_error,+ )+ guardrail.make_model_armor_request = AsyncMock(side_effect=api_error)+ guardrail.should_run_guardrail = Mock(return_value=True)++ request_data = {+ "model": "gpt-4",+ "messages": [{"role": "user", "content": "synthetic input"}],+ "metadata": {},+ }+ mock_llm_response = litellm.ModelResponse()+ mock_llm_response.choices = [+ litellm.Choices(message=litellm.Message(content="model output"))+ ]++ if fail_on_error:+ with pytest.raises(ModelArmorAPIError) as mod_exc:+ await guardrail.async_moderation_hook(+ data=dict(request_data),+ user_api_key_dict=UserAPIKeyAuth(),+ call_type="completion",+ )+ assert mod_exc.value.detail == "Model Armor API error (upstream 503)"++ with pytest.raises(ModelArmorAPIError) as post_exc:+ await guardrail.async_post_call_success_hook(+ data=dict(request_data),+ user_api_key_dict=UserAPIKeyAuth(),+ response=mock_llm_response,+ )+ assert post_exc.value.detail == "Model Armor API error (upstream 503)"+ else:+ moderated = await guardrail.async_moderation_hook(+ data=dict(request_data),+ user_api_key_dict=UserAPIKeyAuth(),+ call_type="completion",+ )+ assert moderated is not None++ result = await guardrail.async_post_call_success_hook(+ data=dict(request_data),+ user_api_key_dict=UserAPIKeyAuth(),+ response=mock_llm_response,+ )+ assert result is mock_llm_response++[email protected]("fail_on_error", [True, False])+async def test_model_armor_api_error_fail_open_streaming(fail_on_error: bool):+ """A streaming-path API failure yields a sanitized SSE error frame when failing+ closed and passes the original chunks through when the operator opted into fail-open."""+ api_error = ModelArmorAPIError("Model Armor API error (upstream 503)")+ guardrail = ModelArmorGuardrail(+ template_id="test-template",+ project_id="test-project",+ guardrail_name="model-armor-test",+ fail_on_error=fail_on_error,+ )+ guardrail.make_model_armor_request = AsyncMock(side_effect=api_error)+ guardrail.should_run_guardrail = Mock(return_value=True)++ async def mock_stream():+ yield litellm.ModelResponseStream(+ choices=[+ litellm.types.utils.StreamingChoices(+ delta=litellm.types.utils.Delta(content="streamed output")+ )+ ]+ )++ chunks = []+ async for chunk in guardrail.async_post_call_streaming_iterator_hook(+ user_api_key_dict=UserAPIKeyAuth(),+ response=mock_stream(),+ request_data={+ "model": "gpt-4",+ "messages": [{"role": "user", "content": "synthetic input"}],+ "metadata": {},+ },+ ):+ chunks.append(chunk)++ if fail_on_error:+ assert len(chunks) == 1+ assert isinstance(chunks[0], str)+ assert "Model Armor API error (upstream 503)" in chunks[0]+ assert '"code": "500"' in chunks[0]+ else:+ assert len(chunks) == 1+ assert isinstance(chunks[0], litellm.ModelResponseStream)++[email protected]("fail_on_error", [True, False])+async def test_model_armor_api_error_fail_open_file_scan(fail_on_error: bool):+ """A file-scan API failure blocks with the sanitized detail when failing closed+ and skips the attachment when the operator opted into fail-open."""+ api_error = ModelArmorAPIError("Model Armor API error (upstream 503)")+ guardrail = ModelArmorGuardrail(+ template_id="test-template",+ project_id="test-project",+ guardrail_name="model-armor-test",+ fail_on_error=fail_on_error,+ )+ guardrail.make_model_armor_request = AsyncMock(side_effect=api_error)++ pdf_b64 = base64.b64encode(b"%PDF-1.4 synthetic").decode()+ messages = [+ {+ "role": "user",+ "content": [+ {+ "type": "file",+ "file": {+ "file_data": f"data:application/pdf;base64,{pdf_b64}",+ "filename": "synthetic.pdf",+ "format": "application/pdf",+ },+ }+ ],+ }+ ]+ data = {"metadata": {}}++ if fail_on_error:+ with pytest.raises(ModelArmorAPIError) as exc_info:+ await guardrail._scan_request_files(messages=messages, data=data)+ assert exc_info.value.detail == "Model Armor API error (upstream 503)"+ else:+ assert await guardrail._scan_request_files(messages=messages, data=data) is None+++def test_model_armor_hot_reload_null_stays_sanitized():+ """update_in_memory_litellm_params assigns raw fields; an explicit null in a+ hot-reloaded config must not disable sanitization."""+ from litellm.types.guardrails import LitellmParams++ guardrail = ModelArmorGuardrail(+ template_id="test-template",+ project_id="test-project",+ guardrail_name="model-armor-test",+ )+ guardrail.update_in_memory_litellm_params(+ LitellmParams(guardrail="model_armor", mode="pre_call", sanitize_error_detail=None)+ )+ assert guardrail.sanitize_error_detail is True++ guardrail.update_in_memory_litellm_params(+ LitellmParams(guardrail="model_armor", mode="pre_call", sanitize_error_detail=False)+ )+ assert guardrail.sanitize_error_detail is False+++def test_model_armor_redactor_depth_cap_fails_closed():+ """Past the recursion cap the redactor must return the redaction sentinel,+ never raw content, and must not raise RecursionError."""+ from litellm.constants import DEFAULT_MAX_RECURSE_DEPTH+ from litellm.proxy.guardrails.guardrail_hooks.model_armor.model_armor import (+ _redact_scanned_content,+ )++ marker = "SYNTHETIC_DEEP_MARKER"+ payload: dict = {"safe_key": marker, "items": [{"safe_key": marker}]}+ for _ in range(DEFAULT_MAX_RECURSE_DEPTH + 5):+ payload = {"nested": payload}++ redacted = _redact_scanned_content(payload)+ assert marker not in str(redacted)++ shallow = _redact_scanned_content({"filterResults": [{"text": marker, "matchState": "MATCH_FOUND"}]})+ assert shallow == {"filterResults": [{"text": "[REDACTED]", "matchState": "MATCH_FOUND"}]}++ uri_payload = _redact_scanned_content(+ {+ "maliciousUriFilterResult": {+ "matchState": "MATCH_FOUND",+ "maliciousUriMatchedItems": [{"uri": f"https://evil.example/{marker}"}],+ }+ }+ )+ assert uri_payload == {+ "maliciousUriFilterResult": {+ "matchState": "MATCH_FOUND",+ "maliciousUriMatchedItems": "[REDACTED]",+ }+ }++[email protected]("sanitize", [True, False])+async def test_model_armor_handler_raised_http_error_sanitized(sanitize: bool):+ """The real AsyncHTTPHandler raises on non-2xx via raise_for_status, so a non-200+ never returns a response object. The raised MaskedHTTPStatusError carries the raw+ upstream body in its message; the guardrail must convert it to a sanitized+ HTTPException instead of letting it bubble raw to callers and logs."""+ marker = "SYNTHETIC_MODEL_ARMOR_MARKER"+ guardrail = ModelArmorGuardrail(+ template_id="test-template",+ project_id="test-project",+ guardrail_name="model-armor-test",+ sanitize_error_detail=sanitize,+ )+ guardrail._ensure_access_token_async = AsyncMock(+ return_value=("test-token", "test-project")+ )++ request = httpx.Request("POST", "https://modelarmor.example.test/v1")+ upstream = httpx.Response(403, content=marker.encode(), request=request)+ original = httpx.HTTPStatusError("Forbidden", request=request, response=upstream)+ masked = MaskedHTTPStatusError(original, message=marker, text=marker)++ with patch.object(+ guardrail.async_handler, "post", AsyncMock(side_effect=masked)+ ), patch.object(verbose_proxy_logger, "debug") as debug_log, patch.object(+ verbose_proxy_logger, "error"+ ) as error_log, pytest.raises(ModelArmorAPIError) as exc_info:+ await guardrail.make_model_armor_request(content=marker)++ direct_log = f"{debug_log.call_args_list} {error_log.call_args_list}"+ assert "403" in str(exc_info.value.detail)+ if sanitize:+ assert marker not in str(exc_info.value.detail)+ assert marker not in direct_log+ else:+ assert marker in str(exc_info.value.detail)++[email protected]("sanitize", [True, False])+async def test_model_armor_post_call_logging_redacts_scanned_content(sanitize: bool):+ marker = "SYNTHETIC_POST_CALL_MARKER"+ armor_response = {+ "sanitizationResult": {+ "filterMatchState": "NO_MATCH_FOUND",+ "filterResults": {+ "sdp": {+ "sdpFilterResult": {+ "deidentifyResult": {+ "matchState": "MATCH_FOUND",+ "data": {"text": marker},+ }+ }+ }+ },+ }+ }+ guardrail = ModelArmorGuardrail(+ template_id="test-template",+ project_id="test-project",+ guardrail_name="model-armor-test",+ mask_response_content=True,+ sanitize_error_detail=sanitize,+ )+ guardrail.make_model_armor_request = AsyncMock(return_value=armor_response)+ guardrail.should_run_guardrail = Mock(return_value=True)++ mock_llm_response = litellm.ModelResponse()+ mock_llm_response.choices = [+ litellm.Choices(message=litellm.Message(content="model output"))+ ]+ request_data = {+ "model": "gpt-4",+ "messages": [{"role": "user", "content": "synthetic input"}],+ "metadata": {},+ "litellm_logging_obj": MagicMock(),+ }++ with patch(+ "litellm.proxy.common_utils.callback_utils.add_guardrail_response_to_standard_logging_object"+ ) as add_logging:+ await guardrail.async_post_call_success_hook(+ data=request_data,+ user_api_key_dict=UserAPIKeyAuth(),+ response=mock_llm_response,+ )++ logged = add_logging.call_args.kwargs["guardrail_response"]+ assert logged["guardrail_status"] == "success"+ logged_armor_response = logged["guardrail_response"]["model_armor_response"]+ if sanitize:+ assert marker not in str(logged_armor_response)+ assert (+ logged_armor_response["sanitizationResult"]["filterResults"]["sdp"][+ "sdpFilterResult"+ ]["deidentifyResult"]["matchState"]+ == "MATCH_FOUND"+ )+ else:+ assert logged_armor_response == armor_response++[email protected]("sanitize", [True, False])+async def test_model_armor_streaming_logging_redacts_scanned_content(sanitize: bool):+ marker = "SYNTHETIC_STREAMING_MARKER"+ armor_response = {+ "sanitizationResult": {+ "filterMatchState": "NO_MATCH_FOUND",+ "sanitizedText": marker,+ }+ }+ guardrail = ModelArmorGuardrail(+ template_id="test-template",+ project_id="test-project",+ guardrail_name="model-armor-test",+ sanitize_error_detail=sanitize,+ )+ guardrail.make_model_armor_request = AsyncMock(return_value=armor_response)+ guardrail.should_run_guardrail = Mock(return_value=True)++ async def mock_stream():+ yield litellm.ModelResponseStream(+ choices=[+ litellm.types.utils.StreamingChoices(+ delta=litellm.types.utils.Delta(content="streamed output")+ )+ ]+ )++ request_data = {+ "model": "gpt-4",+ "messages": [{"role": "user", "content": "synthetic input"}],+ "metadata": {},+ }++ async for _ in guardrail.async_post_call_streaming_iterator_hook(+ user_api_key_dict=UserAPIKeyAuth(),+ response=mock_stream(),+ request_data=request_data,+ ):+ pass++ logged_response = request_data["metadata"]["_model_armor_response"]+ if sanitize:+ assert logged_response == {+ "sanitizationResult": {+ "filterMatchState": "NO_MATCH_FOUND",+ "sanitizedText": "[REDACTED]",+ }+ }+ assert marker not in str(logged_response)+ else:+ assert logged_response == armor_response++[email protected]("sanitize", [True, False])+async def test_model_armor_match_found_sanitizes_caller_and_logging(sanitize: bool):+ marker = "SYNTHETIC_MATCH_FOUND_MARKER"+ armor_response = {+ "sanitizationResult": {+ "filterResults": {+ "sdp": {+ "sdpFilterResult": {+ "inspectResult": {+ "matchState": "MATCH_FOUND",+ "findings": [{"marker": marker}],+ }+ }+ }+ }+ }+ }+ guardrail = ModelArmorGuardrail(+ template_id="test-template",+ project_id="test-project",+ guardrail_name="model-armor-test",+ event_hook=[GuardrailEventHooks.pre_mcp_call],+ sanitize_error_detail=sanitize,+ )+ guardrail.make_model_armor_request = AsyncMock(return_value=armor_response)+ guardrail.should_run_guardrail = Mock(return_value=True)+ request_data = {+ "messages": [{"role": "user", "content": "synthetic input"}],+ "metadata": {},+ }++ with pytest.raises(HTTPException) as exc_info:+ await guardrail.async_pre_call_hook(+ user_api_key_dict=UserAPIKeyAuth(),+ cache=MagicMock(spec=DualCache),+ data=request_data,+ call_type=litellm.types.utils.CallTypes.call_mcp_tool.value,+ )++ detail = exc_info.value.detail+ logged_response = request_data["metadata"]["_model_armor_response"]+ if sanitize:+ assert detail == {"error": "Content blocked by Model Armor"}+ assert logged_response == {+ "sanitizationResult": {+ "filterResults": {+ "sdp": {+ "sdpFilterResult": {+ "inspectResult": {+ "matchState": "MATCH_FOUND",+ "findings": "[REDACTED]",+ }+ }+ }+ }+ }+ }+ assert marker not in str(detail)+ assert marker not in str(logged_response)+ else:+ assert detail["model_armor_response"] == armor_response+ assert logged_response == armor_response+ assert marker in str(detail)+ assert marker in str(logged_response)+++def test_model_armor_sanitize_error_detail_config_wiring():+ from litellm.proxy.guardrails.guardrail_hooks.model_armor import (+ initialize_guardrail,+ )+ from litellm.types.guardrails import LitellmParams++ config = {"guardrail_name": "model-armor-test"}+ params = {+ "guardrail": "model_armor",+ "mode": "pre_mcp_call",+ "template_id": "test-template",+ "project_id": "test-project",+ }+ opted_out = initialize_guardrail(+ LitellmParams(**params, sanitize_error_detail=False), config+ )+ explicit_null = initialize_guardrail(+ LitellmParams(**params, sanitize_error_detail=None), config+ )+ default = initialize_guardrail(LitellmParams(**params), config)++ assert opted_out.sanitize_error_detail is False+ assert explicit_null.sanitize_error_detail is True+ assert default.sanitize_error_detail is Truedef test_model_armor_ui_friendly_name():@@ -1394,7 +1928,10 @@ async def test_model_armor_guardrail_status_intervened_vs_failed():)info = request_data["metadata"]["standard_logging_guardrail_information"]+ assert info[0]["guardrail_name"] == guardrail.guardrail_nameassert info[0]["guardrail_status"] == "guardrail_intervened"+ assert "model_armor_response" not in info[0]["guardrail_response"]+ assert "sanitizationResult" not in info[0]["guardrail_response"]# 2: if an API error - guardrail status should be guardrail_failed_to_respond"guardrail2 = ModelArmorGuardrail(