The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(guardrails): close post-call coverage gaps
userf909fa79b50d
diff --git a/enterprise/enterprise_hooks/banned_keywords.py b/enterprise/enterprise_hooks/banned_keywords.pyindex a86b59daf56..621fde011d2 100644--- a/enterprise/enterprise_hooks/banned_keywords.py+++ b/enterprise/enterprise_hooks/banned_keywords.py@@ -94,11 +94,16 @@ class _ENTERPRISE_BannedKeywords(CustomLogger):user_api_key_dict: UserAPIKeyAuth,response,):- if isinstance(response, litellm.ModelResponse) and isinstance(- response.choices[0], litellm.utils.Choices- ):- for word in self.banned_keywords_list:- self.test_violation(test_str=response.choices[0].message.content or "")+ if not isinstance(response, litellm.ModelResponse):+ return++ for choice in response.choices:+ if not isinstance(choice, litellm.utils.Choices):+ continue+ message = getattr(choice, "message", None)+ content = getattr(message, "content", None)+ if isinstance(content, str):+ self.test_violation(test_str=content)async def async_post_call_streaming_hook(self,diff --git a/litellm/proxy/guardrails/guardrail_hooks/lasso/lasso.py b/litellm/proxy/guardrails/guardrail_hooks/lasso/lasso.pyindex 04697981085..e64b69efcc0 100644--- a/litellm/proxy/guardrails/guardrail_hooks/lasso/lasso.py+++ b/litellm/proxy/guardrails/guardrail_hooks/lasso/lasso.py@@ -51,6 +51,7 @@ from litellm.llms.custom_httpx.http_handler import ()from litellm.proxy._types import UserAPIKeyAuthfrom litellm.proxy.guardrails._content_utils import (+ apply_redacted_messages_back,build_inspection_messages,has_non_string_content,)@@ -420,8 +421,9 @@ class LassoGuardrail(CustomGuardrail):self._process_lasso_response(response)# Apply masking to messages if violations detected and masked messages are available- if response.get("violations_detected") and response.get("messages"):- data["messages"] = response["messages"]+ redacted_messages = response.get("messages")+ if response.get("violations_detected") and redacted_messages:+ apply_redacted_messages_back(data, list(redacted_messages))self._log_masking_applied(message_type, dict(response))return datadiff --git a/litellm/proxy/hooks/azure_content_safety.py b/litellm/proxy/hooks/azure_content_safety.pyindex a21f0566ccd..844bbc11af5 100644--- a/litellm/proxy/hooks/azure_content_safety.py+++ b/litellm/proxy/hooks/azure_content_safety.py@@ -141,12 +141,16 @@ class _PROXY_AzureContentSafety(response,):verbose_proxy_logger.debug("Inside Azure Content-Safety Post-Call Hook")- if isinstance(response, litellm.ModelResponse) and isinstance(- response.choices[0], litellm.utils.Choices- ):- await self.test_violation(- content=response.choices[0].message.content or "", source="output"- )+ if not isinstance(response, litellm.ModelResponse):+ return++ for choice in response.choices:+ if not isinstance(choice, litellm.utils.Choices):+ continue+ message = getattr(choice, "message", None)+ content = getattr(message, "content", None)+ if isinstance(content, str):+ await self.test_violation(content=content, source="output")# async def async_post_call_streaming_hook(# self,diff --git a/tests/test_litellm/proxy/guardrails/test_guardrail_coverage.py b/tests/test_litellm/proxy/guardrails/test_guardrail_coverage.pyindex 04bd57fa32a..329f78bf504 100644--- a/tests/test_litellm/proxy/guardrails/test_guardrail_coverage.py+++ b/tests/test_litellm/proxy/guardrails/test_guardrail_coverage.py@@ -399,6 +399,36 @@ async def test_lasso_inspects_responses_api_input(user_api_key, monkeypatch):assert seen_messages == [[{"role": "user", "content": "responses-api content"}]]+async def test_lasso_masking_writes_back_responses_api_input(user_api_key, monkeypatch):+ """Krrish blocker: Lasso classifix masking must update ``data["input"]``+ for Responses-API requests, not only ``data["messages"]``."""+ monkeypatch.setenv("LASSO_API_KEY", "ls-test")+ from litellm.proxy.guardrails.guardrail_hooks.lasso.lasso import LassoGuardrail++ guard = LassoGuardrail(lasso_api_key="ls-test", mask=True)+ lasso_response = {+ "violations_detected": True,+ "deputies": {"pii": True},+ "findings": {"pii": [{"action": "AUTO_MASKING"}]},+ "messages": [{"role": "user", "content": "[REDACTED]"}],+ }++ async def fake_call_lasso_api(headers, payload, api_url=None):+ return lasso_response++ data = {"input": "[email protected] leaked"}++ with patch.object(guard, "_call_lasso_api", side_effect=fake_call_lasso_api):+ await guard._run_lasso_guardrail(+ data=data,+ cache=DualCache(),+ message_type="PROMPT",+ )++ assert data["input"] == "[REDACTED]"++# ── Banned Keywords ───────────────────────────────────────────────────────────@@ -456,6 +486,69 @@ def test_banned_keywords_blocks_responses_api_input(monkeypatch):asyncio.run(_run())+async def test_banned_keywords_post_call_checks_all_choices(monkeypatch, user_api_key):+ """Krrish blocker: ``n>1`` responses must not bypass post-call checks by+ placing the banned text in ``choices[1+]``."""+ monkeypatch.setattr("litellm.banned_keywords_list", ["forbidden"], raising=False)+ from enterprise.enterprise_hooks.banned_keywords import _ENTERPRISE_BannedKeywords+ from fastapi import HTTPException++ guard = _ENTERPRISE_BannedKeywords()+ response = ModelResponse(+ choices=[+ Choices(index=0, message=Message(role="assistant", content="clean")),+ Choices(index=1, message=Message(role="assistant", content="forbidden")),+ ]+ )++ with pytest.raises(HTTPException) as exc:+ await guard.async_post_call_success_hook(+ data={},+ user_api_key_dict=user_api_key,+ response=response,+ )++ assert "forbidden" in str(exc.value.detail).lower()+++# ── Azure Content Safety ──────────────────────────────────────────────────────+++async def test_azure_content_safety_post_call_checks_all_choices(user_api_key):+ """Krrish blocker: ``n>1`` responses must not bypass Azure Content Safety+ by placing the unsafe text in ``choices[1+]``."""+ from fastapi import HTTPException+ from litellm.proxy.hooks.azure_content_safety import _PROXY_AzureContentSafety++ guard = _PROXY_AzureContentSafety.__new__(_PROXY_AzureContentSafety)+ seen_outputs = []++ async def fake_test_violation(content, source=None):+ seen_outputs.append((content, source))+ if "unsafe" in content:+ raise HTTPException(status_code=400, detail={"error": "unsafe"})++ guard.test_violation = fake_test_violation+ response = ModelResponse(+ choices=[+ Choices(index=0, message=Message(role="assistant", content="clean")),+ Choices(index=1, message=Message(role="assistant", content="unsafe")),+ Choices(index=2, message=Message(role="assistant", content="later")),+ ]+ )++ with pytest.raises(HTTPException):+ await guard.async_post_call_success_hook(+ data={},+ user_api_key_dict=user_api_key,+ response=response,+ )++ assert seen_outputs == [("clean", "output"), ("unsafe", "output")]++# ── Secret Detection ──────────────────────────────────────────────────────────