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]

fix(panw_prisma_airs): scan tool call args as plain text, not a tool_event (#37038)

devin-ai-integration[bot]74a1beda777c
diff --git a/litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/panw_prisma_airs.py b/litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/panw_prisma_airs.py
index 7e641814deb..5f07f529e7a 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/panw_prisma_airs.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/panw_prisma_airs.py
@@ -10,11 +10,12 @@ import os
import re
from collections.abc import AsyncIterable, Mapping, Sequence
from datetime import datetime
-from typing import TYPE_CHECKING, Any, Final, Literal, Optional
+from typing import TYPE_CHECKING, Any, Final, Literal, Optional, TypeAlias
from urllib.parse import urlparse
import httpx
from fastapi import HTTPException
+from pydantic import BaseModel, ConfigDict, ValidationError, field_validator
from litellm._logging import verbose_proxy_logger
from litellm._uuid import uuid
@@ -40,12 +41,55 @@ from litellm.types.guardrails import GuardrailEventHooks
from litellm.types.utils import (
CallTypes,
CallTypesLiteral,
+ ChatCompletionDeltaCustomToolCall,
+ ChatCompletionDeltaToolCall,
+ ChatCompletionMessageCustomToolCall,
+ ChatCompletionMessageToolCall,
+ ChatCompletionToolCallChunk,
Choices,
GenericGuardrailAPIInputs,
ModelResponse,
ModelResponseStream,
)
+ToolCallLike: TypeAlias = (
+ ChatCompletionMessageToolCall
+ | ChatCompletionDeltaToolCall
+ | ChatCompletionMessageCustomToolCall
+ | ChatCompletionDeltaCustomToolCall
+ | ChatCompletionToolCallChunk
+)
+
+
+class _ToolCallFunctionSlice(BaseModel):
+ model_config = ConfigDict(from_attributes=True, extra="ignore")
+
+ name: str | None = None
+ arguments: str | None = None
+
+ @field_validator("name", "arguments", mode="before")
+ @classmethod
+ def _coerce_to_scannable_text(cls, value: object) -> str | None:
+ """Accept any shape a client can put here and render it scannable.
+
+ The OpenAI request path forwards client-supplied ``tool_calls`` verbatim, so a
+ client can post a dict for ``arguments`` or a non-string for ``name``. Rejecting
+ either would fail validation for the whole slice, which reads as an unscannable
+ tool call and skips it silently -- the one outcome a scanner must never have.
+ A caller could otherwise suppress the scan on a tool call just by sending
+ ``"name": 123``.
+ """
+ if value is None or isinstance(value, str):
+ return value
+ return json.dumps(value) if isinstance(value, (dict, list)) else str(value)
+
+
+class _ToolCallSlice(BaseModel):
+ model_config = ConfigDict(from_attributes=True, extra="ignore")
+
+ function: _ToolCallFunctionSlice | None = None
+
+
if TYPE_CHECKING:
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.types.proxy.guardrails.guardrail_hooks.base import GuardrailConfigModel
@@ -643,19 +687,11 @@ class PanwPrismaAirsHandler(CustomGuardrail):
self,
scan_result: Mapping[str, object],
is_response: bool = False,
- also_hide: str | None = None,
) -> Mapping[str, Mapping[str, object]]:
- """Build enhanced error detail with scan information.
-
- ``also_hide`` names one more scan field to withhold, for the caller that knows
- its AIRS verdict carries model-generated content under a key that is normally
- caller input.
- """
+ """Build enhanced error detail with scan information."""
action_type: Final = "Response" if is_response else "Prompt"
code_suffix: Final = "_response_blocked" if is_response else "_blocked"
- hidden_fields: Final = self._CLIENT_HIDDEN_SCAN_FIELDS.union(() if also_hide is None else (also_hide,))
-
category: Final = scan_result.get("category", "unknown")
default_msg: Final = f"{action_type} blocked by PANW Prisma AI Security policy (Category: {category})"
@@ -675,7 +711,7 @@ class PanwPrismaAirsHandler(CustomGuardrail):
**{
key: value
for key, value in scan_result.items()
- if not key.startswith("_") and key not in hidden_fields
+ if not key.startswith("_") and key not in self._CLIENT_HIDDEN_SCAN_FIELDS
},
"message": error_msg,
"type": "guardrail_violation",
@@ -1407,55 +1443,25 @@ class PanwPrismaAirsHandler(CustomGuardrail):
request_data: dict,
start_time: datetime,
) -> None:
- """Scan tool call arguments with allow/block/mask treatment (in-place modification).
-
- Each tool call is sent as a ``tool_event`` using the canonical PANW
- AIRS schema::
+ """Scan tool calls with allow/block/mask treatment (in-place modification).
- {
- "metadata": {
- "ecosystem": "openai",
- "method": "tools/call",
- "server_name": "litellm",
- "tool_invoked": "<function_name>",
- },
- "input": "<args_json>", # optional, omitted for empty args
- }
-
- Empty-arg invocations are still reported (without ``input``) so AIRS
- can enforce tool-name-based policies.
+ Tool name and arguments go out as plain prompt/response text, newline separated:
+ the AIRS ``tool_event`` schema only accepts ``ecosystem: "mcp"``, which
+ OpenAI-format tool calls are not. A name-only call is still scanned so
+ tool-name policies keep firing on empty arguments.
"""
for tool_call in tool_calls:
- # --- extract tool_name and args_text --------------------------
- tool_name: str | None = None
- args_text: str | None = None
-
- if hasattr(tool_call, "function") and hasattr(tool_call.function, "arguments"):
- args_text = tool_call.function.arguments
- tool_name = getattr(tool_call.function, "name", None)
- elif isinstance(tool_call, dict):
- func = tool_call.get("function", {})
- if isinstance(func, dict):
- args_text = func.get("arguments")
- tool_name = func.get("name")
-
- # --- build tool_event payload (canonical PANW schema) -----------
- tool_event: dict[str, object] = {
- "metadata": {
- "ecosystem": "openai",
- "method": "tools/call",
- "server_name": "litellm",
- "tool_invoked": tool_name or "unknown",
- },
- }
- if args_text and args_text.strip():
- tool_event["input"] = args_text
+ tool_name, args_text = self._get_tool_call_function(tool_call)
+ scanned_args = args_text if args_text and args_text.strip() else None
+ scan_text = "\n".join(part for part in (tool_name, scanned_args) if part)
+ if not scan_text.strip():
+ continue
scan_result = await self._call_panw_api(
- is_response=False, # tool_event is always request-side in AIRS schema
+ content=scan_text,
+ is_response=is_response,
metadata=metadata,
call_id=call_id,
- tool_event=tool_event,
)
if scan_result.get("_is_transient") or scan_result.get("_always_block"):
@@ -1467,44 +1473,68 @@ class PanwPrismaAirsHandler(CustomGuardrail):
event_type=event_type,
is_response=is_response,
)
- continue # fallback_on_error="allow" — leave args unchanged
+ continue
self._record_scan_id(request_data, scan_result)
action = scan_result.get("action", "block")
- # Always is_response=False for masked data lookup because
- # tool_event scans are request-side in AIRS schema and
- # AIRS returns prompt_masked_data for them.
- masked_text = self._get_masked_text(scan_result, is_response=False)
+ masked_args = self._masked_tool_call_arguments(
+ self._get_masked_text(scan_result, is_response=is_response),
+ scanned_name=bool(tool_name),
+ scanned_args=scanned_args,
+ )
if action == "allow":
- if masked_text:
- self._set_tool_call_arguments(tool_call, masked_text)
- elif masked_text and (
+ if masked_args:
+ self._set_tool_call_arguments(tool_call, masked_args)
+ elif masked_args and (
(is_response and self.mask_response_content) or (not is_response and self.mask_request_content)
):
- self._set_tool_call_arguments(tool_call, masked_text)
+ self._set_tool_call_arguments(tool_call, masked_args)
else:
- # tool_event scans are request-side in the AIRS schema, so AIRS returns
- # the model's own tool arguments under prompt_masked_data. On a
- # response-side block that is generated content, not caller input, and
- # the class-level default only withholds response_masked_data — which is
- # empty on this path. Withhold it explicitly so the 400 does not become
- # the content channel this branch declined to deliver.
- error_detail = self._build_error_detail(
- scan_result,
- is_response=is_response,
- also_hide="prompt_masked_data" if is_response else None,
- )
+ # Tool calls now go out as ordinary prompt/response text, so a
+ # response-side scan reports the model's arguments under
+ # response_masked_data, which _CLIENT_HIDDEN_SCAN_FIELDS already
+ # withholds. prompt_masked_data is the caller's own input again and
+ # must keep reaching them -- it is one of the fields LIT-5638 asks for.
+ error_detail = self._build_error_detail(scan_result, is_response=is_response)
raise HTTPException(status_code=400, detail=error_detail)
@staticmethod
- def _set_tool_call_arguments(tool_call, masked_text: str) -> None:
- """Set masked text on a tool call's function arguments, handling both object and dict forms."""
- if hasattr(tool_call, "function"):
- tool_call.function.arguments = masked_text
- elif isinstance(tool_call, dict) and isinstance(tool_call.get("function"), dict):
+ def _masked_tool_call_arguments(
+ masked_text: str | None,
+ *,
+ scanned_name: bool,
+ scanned_args: str | None,
+ ) -> str | None:
+ """Recover the arguments slice of a masked scan, or None when it cannot be applied."""
+ if masked_text is None or scanned_args is None:
+ return None
+ if not scanned_name:
+ return masked_text
+ _, separator, masked_args = masked_text.partition("\n")
+ return masked_args if separator else None
+
+ @staticmethod
+ def _get_tool_call_function(tool_call: ToolCallLike) -> tuple[str | None, str | None]:
+ """Read a tool call's function name and arguments; (None, None) for non-function shapes."""
+ try:
+ parsed: Final = _ToolCallSlice.model_validate(tool_call, from_attributes=True)
+ except ValidationError:
+ return (None, None)
+ if parsed.function is None:
+ return (None, None)
+ return (parsed.function.name, parsed.function.arguments)
+
+ @staticmethod
+ def _set_tool_call_arguments(tool_call: ToolCallLike, masked_text: str) -> None:
+ """Set masked text on the function arguments of a call that _get_tool_call_function accepted."""
+ if isinstance(tool_call, dict):
tool_call["function"]["arguments"] = masked_text
+ return
+ if isinstance(tool_call, ChatCompletionMessageCustomToolCall | ChatCompletionDeltaCustomToolCall):
+ return
+ tool_call.function.arguments = masked_text
@staticmethod
def _is_anthropic_request(
diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_panw_prisma_airs.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_panw_prisma_airs.py
index fc1465c7c14..86a7ac1dabe 100644
--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_panw_prisma_airs.py
+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_panw_prisma_airs.py
@@ -27,6 +27,8 @@ from litellm.proxy.guardrails.guardrail_hooks.panw_prisma_airs import (
)
from litellm.types.guardrails import GuardrailEventHooks, LitellmParams
from litellm.types.utils import (
+ ChatCompletionCustomToolCallPayload,
+ ChatCompletionMessageCustomToolCall,
ChatCompletionMessageToolCall,
Choices,
Delta,
@@ -1812,7 +1814,7 @@ class TestPanwAirsApplyGuardrail:
mock_api.return_value = {
"action": "block",
"category": "dlp",
- "prompt_masked_data": {"data": '{"ssn": "XXXXXXXXXX"}'},
+ "prompt_masked_data": {"data": 'get_user\n{"ssn": "XXXXXXXXXX"}'},
}
await handler_mask_request.apply_guardrail(
@@ -2145,8 +2147,8 @@ class TestPanwAirsToolEventIsResponseFix:
"""Tests for Bug A fix: tool_event scans must not set is_response metadata."""
@pytest.mark.asyncio
- async def test_scan_tool_calls_post_call_uses_request_mode_for_tool_event(self):
- """_scan_tool_calls_for_guardrail(is_response=True) must call _call_panw_api with is_response=False."""
+ async def test_scan_tool_calls_post_call_scans_args_as_response_text(self):
+ """_scan_tool_calls_for_guardrail(is_response=True) scans args as response text, never as a tool_event."""
handler = PanwPrismaAirsHandler(
guardrail_name="test_panw_airs",
api_key="test_key",
@@ -2174,7 +2176,9 @@ class TestPanwAirsToolEventIsResponseFix:
start_time=datetime.now(),
)
mock_api.assert_called_once()
- assert mock_api.call_args.kwargs.get("is_response") is False
+ assert mock_api.call_args.kwargs.get("is_response") is True
+ assert mock_api.call_args.kwargs.get("content") == 'get_weather\n{"city": "Paris"}'
+ assert mock_api.call_args.kwargs.get("tool_event") is None
@pytest.mark.asyncio
async def test_call_panw_api_tool_event_omits_is_response_metadata(self):
@@ -2687,8 +2691,8 @@ class TestPanwAirsToolEventPayload:
mock_panw_client.client.post.assert_called_once()
-class TestPanwAirsToolCallToolEvent:
- """Test _scan_tool_calls_for_guardrail sends tool_event payloads."""
+class TestPanwAirsToolCallContentScan:
+ """Test _scan_tool_calls_for_guardrail scans arguments as plain prompt/response text."""
@pytest.fixture
def handler(self):
@@ -2699,8 +2703,8 @@ class TestPanwAirsToolCallToolEvent:
return make_handler(mask_request_content=True)
@pytest.mark.asyncio
- async def test_tool_event_includes_metadata_and_input(self, handler):
- """_scan_tool_calls_for_guardrail sends canonical tool_event with metadata + input."""
+ async def test_tool_call_args_sent_as_prompt_content(self, handler):
+ """Regression (LIT-5279): args go out as prompt text, not as an ecosystem=openai tool_event."""
tool_call = ChatCompletionMessageToolCall(
id="call_1",
@@ -2726,19 +2730,13 @@ class TestPanwAirsToolCallToolEvent:
)
call_kwargs = mock_api.call_args.kwargs
- te = call_kwargs["tool_event"]
- assert_canonical_tool_event(
- te,
- ecosystem="openai",
- server_name="litellm",
- tool_invoked="get_weather",
- )
- # input field carries args
- assert te["input"] == '{"city": "San Francisco"}'
+ assert call_kwargs["content"] == 'get_weather\n{"city": "San Francisco"}'
+ assert call_kwargs["is_response"] is False
+ assert call_kwargs.get("tool_event") is None
@pytest.mark.asyncio
- async def test_tool_event_empty_args_omits_input(self, handler):
- """Empty args → tool_event has metadata but no input key."""
+ async def test_empty_args_still_scan_the_tool_name(self, handler):
+ """A name-only call is still scanned so tool-name policies keep firing."""
tool_call = ChatCompletionMessageToolCall(
id="call_1",
@@ -2763,17 +2761,112 @@ class TestPanwAirsToolCallToolEvent:
start_time=datetime.now(),
)
- # Empty args → tool_event still sent for name-based policies
+ assert mock_api.call_args.kwargs["content"] == "list_items"
+
+ @pytest.mark.asyncio
+ async def test_parsed_dict_arguments_are_still_scanned(self, handler):
+ """A client can post tool call arguments as already-parsed JSON.
+
+ The OpenAI request path forwards client-supplied tool calls verbatim, so this
+ shape reaches the scanner. It must be scanned, not dropped as unreadable, or the
+ content is a silent bypass.
+ """
+
+ tool_call = {
+ "id": "call_1",
+ "type": "function",
+ "function": {"name": "exfiltrate", "arguments": {"ssn": "123-45-6789"}},
+ }
+
+ with patch.object(handler, "_call_panw_api", new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = {"action": "allow", "category": "benign"}
+ await handler._scan_tool_calls_for_guardrail(
+ tool_calls=[tool_call],
+ is_response=False,
+ metadata={"user": "test", "model": "gpt-4"},
+ call_id="test-call-id",
+ request_data={"litellm_call_id": "test-call-id"},
+ start_time=datetime.now(),
+ )
+
mock_api.assert_called_once()
- te = mock_api.call_args.kwargs["tool_event"]
- assert_canonical_tool_event(
- te, ecosystem="openai", server_name="litellm", tool_invoked="list_items"
+ assert "123-45-6789" in mock_api.call_args.kwargs["content"]
+ assert "exfiltrate" in mock_api.call_args.kwargs["content"]
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("bad_name", [123, {"x": 1}, ["a"], True])
+ async def test_non_string_tool_name_does_not_suppress_the_scan(self, handler, bad_name):
+ """A wrong-typed ``name`` must not make the whole tool call unscannable.
+
+ ``name`` reaches us straight off the client body, same as ``arguments``. If a
+ non-string fails validation, the slice is unreadable, the call is skipped, and
+ the arguments never reach AIRS -- a scanner bypass any caller can trigger with
+ ``"name": 123``.
+ """
+
+ tool_call = {
+ "id": "call_1",
+ "type": "function",
+ "function": {"name": bad_name, "arguments": '{"ssn": "123-45-6789"}'},
+ }
+
+ with patch.object(handler, "_call_panw_api", new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = {"action": "allow", "category": "benign"}
+ await handler._scan_tool_calls_for_guardrail(
+ tool_calls=[tool_call],
+ is_response=False,
+ metadata={"user": "test", "model": "gpt-4"},
+ call_id="test-call-id",
+ request_data={"litellm_call_id": "test-call-id"},
+ start_time=datetime.now(),
)
- assert "input" not in te
+
+ mock_api.assert_called_once()
+ assert "123-45-6789" in mock_api.call_args.kwargs["content"]
+
+ @pytest.mark.asyncio
+ async def test_custom_tool_call_is_skipped(self, handler):
+ """Custom tool calls carry no function payload, so they are skipped instead of crashing."""
+
+ tool_call = ChatCompletionMessageCustomToolCall(
+ id="call_1",
+ type="custom",
+ custom=ChatCompletionCustomToolCallPayload(name="run_sql", input="select 1"),
+ )
+
+ with patch.object(handler, "_call_panw_api", new_callable=AsyncMock) as mock_api:
+ await handler._scan_tool_calls_for_guardrail(
+ tool_calls=[tool_call],
+ is_response=False,
+ metadata={"user": "test", "model": "gpt-4"},
+ call_id="test-call-id",
+ request_data={"litellm_call_id": "test-call-id"},
+ start_time=datetime.now(),
+ )
+
+ mock_api.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_tool_call_without_function_is_skipped(self, handler):
+ """A tool call with no function payload is skipped instead of raising AttributeError."""
+
+ tool_call = ChatCompletionMessageToolCall(id="call_1", type="function", function=None)
+
+ with patch.object(handler, "_call_panw_api", new_callable=AsyncMock) as mock_api:
+ await handler._scan_tool_calls_for_guardrail(
+ tool_calls=[tool_call],
+ is_response=False,
+ metadata={"user": "test", "model": "gpt-4"},
+ call_id="test-call-id",
+ request_data={"litellm_call_id": "test-call-id"},
+ start_time=datetime.now(),
+ )
+
+ mock_api.assert_not_called()
@pytest.mark.asyncio
async def test_tool_call_block_still_raises(self, handler):
- """Tool call block with tool_event raises HTTPException(400)."""
+ """Tool call block raises HTTPException(400)."""
tool_call = ChatCompletionMessageToolCall(
id="call_1",
@@ -2802,8 +2895,8 @@ class TestPanwAirsToolCallToolEvent:
assert exc_info.value.status_code == 400
@pytest.mark.asyncio
- async def test_tool_call_mask_with_tool_event(self, handler_mask_request):
- """Tool call masking still works with tool_event payloads."""
+ async def test_tool_call_mask_applies_masked_args(self, handler_mask_request):
+ """Tool call masking still rewrites the arguments in place."""
tool_call = ChatCompletionMessageToolCall(
id="call_1",
@@ -2820,7 +2913,7 @@ class TestPanwAirsToolCallToolEvent:
mock_api.return_value = {
"action": "block",
"category": "dlp",
- "prompt_masked_data": {"data": '{"ssn": "XXXXXXXXXX"}'},
+ "prompt_masked_data": {"data": 'get_user\n{"ssn": "XXXXXXXXXX"}'},
}
await handler_mask_request._scan_tool_calls_for_guardrail(
@@ -2835,8 +2928,8 @@ class TestPanwAirsToolCallToolEvent:
assert tool_call.function.arguments == '{"ssn": "XXXXXXXXXX"}'
@pytest.mark.asyncio
- async def test_dict_tool_call_extracts_name(self, handler):
- """Dict-style tool calls also extract tool_name for tool_event."""
+ async def test_dict_tool_call_extracts_args(self, handler):
+ """Dict-style tool calls also have their arguments scanned."""
tool_call = {
"function": {
@@ -2860,11 +2953,128 @@ class TestPanwAirsToolCallToolEvent:
)
call_kwargs = mock_api.call_args.kwargs
- te = call_kwargs["tool_event"]
- assert_canonical_tool_event(
- te, ecosystem="openai", server_name="litellm", tool_invoked="search"
+ assert call_kwargs["content"] == 'search\n{"query": "test"}'
+ assert call_kwargs.get("tool_event") is None
+
+ @pytest.mark.asyncio
+ async def test_allow_with_masked_args_still_rewrites_args(self, handler):
+ """An allow verdict that carries masked data applies it regardless of masking config."""
+
+ tool_call = ChatCompletionMessageToolCall(
+ id="call_1",
+ type="function",
+ function=Function(
+ name="get_user",
+ arguments='{"ssn": "123-45-6789"}',
+ ),
+ )
+
+ with patch.object(handler, "_call_panw_api", new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = {
+ "action": "allow",
+ "category": "dlp",
+ "prompt_masked_data": {"data": 'get_user\n{"ssn": "XXXXXXXXXX"}'},
+ }
+
+ await handler._scan_tool_calls_for_guardrail(
+ tool_calls=[tool_call],
+ is_response=False,
+ metadata={"user": "test", "model": "gpt-4"},
+ call_id="test-call-id",
+ request_data={"litellm_call_id": "test-call-id"},
+ start_time=datetime.now(),
+ )
+
+ assert tool_call.function.arguments == '{"ssn": "XXXXXXXXXX"}'
+
+ @pytest.mark.asyncio
+ async def test_dict_tool_call_masked_args_applied(self, handler_mask_request):
+ """Masked args are written back into dict-style tool calls too."""
+
+ tool_call = {"function": {"name": "get_user", "arguments": '{"ssn": "123-45-6789"}'}}
+
+ with patch.object(handler_mask_request, "_call_panw_api", new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = {
+ "action": "block",
+ "category": "dlp",
+ "prompt_masked_data": {"data": 'get_user\n{"ssn": "XXXXXXXXXX"}'},
+ }
+
+ await handler_mask_request._scan_tool_calls_for_guardrail(
+ tool_calls=[tool_call],
+ is_response=False,
+ metadata={"user": "test", "model": "gpt-4"},
+ call_id="test-call-id",
+ request_data={"litellm_call_id": "test-call-id"},
+ start_time=datetime.now(),
+ )
+
+ assert tool_call["function"]["arguments"] == '{"ssn": "XXXXXXXXXX"}'
+
+ @pytest.mark.asyncio
+ async def test_transient_error_with_fallback_allow_keeps_args(self):
+ """A transient AIRS failure under fallback_on_error=allow leaves the tool call untouched."""
+
+ handler = make_handler(fallback_on_error="allow")
+ tool_call = ChatCompletionMessageToolCall(
+ id="call_1",
+ type="function",
+ function=Function(
+ name="get_weather",
+ arguments='{"city": "San Francisco"}',
+ ),
+ )
+
+ with patch.object(handler, "_call_panw_api", new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = {
+ "action": "block",
+ "category": "api_error",
+ "_is_transient": True,
+ }
+
+ await handler._scan_tool_calls_for_guardrail(
+ tool_calls=[tool_call],
+ is_response=False,
+ metadata={"user": "test", "model": "gpt-4"},
+ call_id="test-call-id",
+ request_data={"litellm_call_id": "test-call-id"},
+ start_time=datetime.now(),
)
- assert te["input"] == '{"query": "test"}'
+
+ assert tool_call.function.arguments == '{"city": "San Francisco"}'
+
+ @pytest.mark.asyncio
+ async def test_permanent_error_blocks_response_side_scan(self):
+ """A permanent AIRS failure raises 500 even when it happens on the response side."""
+
+ handler = make_handler(fallback_on_error="allow")
+ tool_call = ChatCompletionMessageToolCall(
+ id="call_1",
+ type="function",
+ function=Function(
+ name="get_weather",
+ arguments='{"city": "San Francisco"}',
+ ),
+ )
+
+ with patch.object(handler, "_call_panw_api", new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = {
+ "action": "block",
+ "category": "http_400_error",
+ "_always_block": True,
+ }
+
+ with pytest.raises(HTTPException) as exc_info:
+ await handler._scan_tool_calls_for_guardrail(
+ tool_calls=[tool_call],
+ is_response=True,
+ metadata={"user": "test", "model": "gpt-4"},
+ call_id="test-call-id",
+ request_data={"litellm_call_id": "test-call-id"},
+ start_time=datetime.now(),
+ )
+
+ assert exc_info.value.status_code == 500
class TestPanwAirsMcpToolEventScan:
@@ -3292,25 +3502,20 @@ class TestPanwAirsDuplicateScanRegression:
# Expected calls:
# 1. text scan for "Hello"
- # 2. tool_calls scan for get_weather (with tool_event)
+ # 2. tool_calls scan for get_weather (plain prompt text)
# 3. MCP scan for file_reader (with tool_event)
assert mock_api.call_count == 3
- # Verify ordering: first is text (no tool_event), second is tool_call, third is MCP
+ # Verify ordering: first is text, second is tool_call args, third is MCP
calls = mock_api.call_args_list
# First call: text scan (content="Hello", no tool_event)
assert calls[0].kwargs.get("content") == "Hello"
assert calls[0].kwargs.get("tool_event") is None
- # Second call: tool_calls scan (tool_event with get_weather)
- assert (
- calls[1].kwargs["tool_event"]["metadata"]["tool_invoked"]
- == "get_weather"
- )
- assert calls[1].kwargs["tool_event"]["metadata"]["ecosystem"] == "openai"
- assert calls[1].kwargs["tool_event"]["metadata"]["method"] == "tools/call"
- assert "tool_name" not in calls[1].kwargs["tool_event"]
+ # Second call: tool_calls scan (args as prompt text, no tool_event)
+ assert calls[1].kwargs.get("tool_event") is None
+ assert calls[1].kwargs["content"] == 'get_weather\n{"city": "NYC"}'
# Third call: MCP scan (tool_event with file_reader)
assert (
@@ -3840,11 +4045,11 @@ class TestPanwAirsDeveloperRoleGuardrail:
class TestPanwAirsEmptyToolArgsBlock:
- """Test empty-arg tool call blocking by name policy."""
+ """Test empty-arg tool call handling."""
@pytest.mark.asyncio
async def test_tool_call_empty_args_block_by_name_policy(self):
- """Empty-args tool call where PANW returns block raises HTTPException."""
+ """An empty-args call is still scanned by name, so a name policy can block it."""
handler = make_handler()
@@ -3873,6 +4078,7 @@ class TestPanwAirsEmptyToolArgsBlock:
)
assert exc_info.value.status_code == 400
+ assert mock_api.call_args.kwargs["content"] == "dangerous_tool"
class TestPanwAirsDictChunkStreaming:
@@ -4150,13 +4356,10 @@ class TestPanwAirsUnifiedToolsScan:
# Exactly 1 API call: the tool_call invocation, not the definitions
assert mock_api.call_count == 1
- te = mock_api.call_args.kwargs["tool_event"]
- # Must carry the exact function name — not "unknown"
- assert te["metadata"]["tool_invoked"] == "get_weather"
- # Must NOT carry definition-shaped keys
- assert "type" not in te
- assert "server_label" not in te
- assert "server_url" not in te
+ call_kwargs = mock_api.call_args.kwargs
+ # Must carry the invocation arguments, not definition-shaped payloads
+ assert call_kwargs["content"] == 'get_weather\n{"location": "NYC"}'
+ assert call_kwargs.get("tool_event") is None
class TestPanwAirsMcpRestToolInvoked:
@@ -5240,20 +5443,21 @@ class TestPanwAirsMcpMasking:
class TestPanwAirsResponseToolCallMasking:
- """Tests for response-side tool-call masking using prompt_masked_data."""
+ """Tests for response-side tool-call masking using response_masked_data."""
@pytest.fixture
def handler(self):
return make_handler(mask_response_content=True)
@pytest.mark.asyncio
- async def test_response_side_tool_call_uses_prompt_masked_data(self, handler):
- """_scan_tool_calls_for_guardrail(is_response=True) should look up
- prompt_masked_data (not response_masked_data) and mask instead of blocking."""
- tool_call = MagicMock()
- tool_call.function = MagicMock()
- tool_call.function.arguments = '{"query": "sensitive-data"}'
- tool_call.function.name = "search"
+ async def test_response_side_tool_call_uses_response_masked_data(self, handler):
+ """_scan_tool_calls_for_guardrail(is_response=True) scans args as response text,
+ so masked output comes from response_masked_data and masks instead of blocking."""
+ tool_call = ChatCompletionMessageToolCall(
+ id="call_1",
+ type="function",
+ function=Function(name="search", arguments='{"query": "sensitive-data"}'),
+ )
with patch.object(
handler, "_call_panw_api", new_callable=AsyncMock
@@ -5261,8 +5465,7 @@ class TestPanwAirsResponseToolCallMasking:
mock_api.return_value = {
"action": "block",
"category": "dlp",
- # AIRS returns prompt_masked_data for tool_event scans
- "prompt_masked_data": {"data": '{"query": "****"}'},
+ "response_masked_data": {"data": 'search\n{"query": "****"}'},
}
await handler._scan_tool_calls_for_guardrail(
@@ -5802,26 +6005,41 @@ class TestPanwAirsErrorDetailWithheldFields:
assert detail["error"]["scan_id"] == "scan-2"
-class TestPanwAirsToolCallBlockWithholdsGeneratedArgs:
- """A response-side tool-call block must not ship the model's tool arguments.
+class TestPanwAirsToolCallBlockMaskedDataRouting:
+ """A tool-call block must withhold model output and keep caller input.
+
+ Tool calls are scanned as ordinary prompt/response text, so the side of the scan
+ decides which key holds what: a response-side scan reports the model's generated
+ arguments under ``response_masked_data`` (withheld by
+ ``_CLIENT_HIDDEN_SCAN_FIELDS``), while ``prompt_masked_data`` is the caller's own
+ input and is one of the fields LIT-5638 asks for.
- ``_scan_tool_calls_for_guardrail`` calls AIRS with ``is_response=False`` because
- tool_event is request-side in the AIRS schema, so AIRS returns the scanned tool
- arguments under ``prompt_masked_data``. When the tool calls being scanned are the
- model's own output, that key holds generated content, and the class-level
- ``_CLIENT_HIDDEN_SCAN_FIELDS`` default (``response_masked_data``, empty on this
- path) does not cover it.
+ Regression guard for the interaction with #37036. That PR withheld
+ ``prompt_masked_data`` on response-side tool blocks, correctly, while tool calls
+ still went out as a request-side ``tool_event``. Once this PR routes them by side,
+ that withholding drops a caller-facing audit field instead. The two PRs merge
+ without a conflict, so nothing but this test catches it.
"""
- MASKED_ARGS = '{"to_account": "XXXXXXXXXX", "amount": 5000}'
+ MODEL_ARGS = '{"to_account": "XXXXXXXXXX", "amount": 5000}'
+ CALLER_INPUT = "my ssn is XXX-XX-XXXX"
- SCAN_RESULT = {
+ RESPONSE_SIDE_SCAN = {
"action": "block",
"category": "sensitive_data",
"scan_id": "scan-tool-1",
"prompt_detected": {"dlp": True},
- "prompt_masked_data": {"data": MASKED_ARGS},
- "response_masked_data": {},
+ "response_detected": {"dlp": True},
+ "prompt_masked_data": {"data": CALLER_INPUT},
+ "response_masked_data": {"data": MODEL_ARGS},
+ }
+
+ REQUEST_SIDE_SCAN = {
+ "action": "block",
+ "category": "sensitive_data",
+ "scan_id": "scan-tool-2",
+ "prompt_detected": {"dlp": True},
+ "prompt_masked_data": {"data": MODEL_ARGS},
}
@staticmethod
@@ -5835,9 +6053,9 @@ class TestPanwAirsToolCallBlockWithholdsGeneratedArgs:
),
)
- async def _block(self, handler, is_response):
+ async def _block(self, handler, is_response, scan_result):
with patch.object(handler, "_call_panw_api", new_callable=AsyncMock) as mock_api:
- mock_api.return_value = dict(self.SCAN_RESULT)
+ mock_api.return_value = dict(scan_result)
with pytest.raises(HTTPException) as exc_info:
await handler._scan_tool_calls_for_guardrail(
tool_calls=[self._tool_call()],
@@ -5855,27 +6073,34 @@ class TestPanwAirsToolCallBlockWithholdsGeneratedArgs:
# The block branch is only reached with masking off; guard the premise.
assert handler.mask_response_content is False
- exc = await self._block(handler, is_response=True)
+ exc = await self._block(handler, True, self.RESPONSE_SIDE_SCAN)
error = exc.detail["error"]
assert exc.status_code == 400
- assert "prompt_masked_data" not in error
- assert self.MASKED_ARGS not in str(error)
+ assert "response_masked_data" not in error
+ assert self.MODEL_ARGS not in str(error)
- # The audit fields LIT-5638 asks for are unaffected.
+ @pytest.mark.asyncio
+ async def test_response_side_block_still_returns_caller_input(self):
+ """The caller's own masked input is an audit field, not model output."""
+ handler = make_handler(mask_response_content=False)
+
+ exc = await self._block(handler, True, self.RESPONSE_SIDE_SCAN)
+ error = exc.detail["error"]
+
+ assert error["prompt_masked_data"] == {"data": self.CALLER_INPUT}
assert error["scan_id"] == "scan-tool-1"
- assert error["prompt_detected"] == {"dlp": True}
@pytest.mark.asyncio
async def test_request_side_block_still_returns_masked_tool_args(self):
"""Caller-supplied tool arguments stay in the verdict — that is the ticket's ask."""
handler = make_handler(mask_request_content=False)
- exc = await self._block(handler, is_response=False)
+ exc = await self._block(handler, False, self.REQUEST_SIDE_SCAN)
error = exc.detail["error"]
- assert error["prompt_masked_data"] == {"data": self.MASKED_ARGS}
- assert error["scan_id"] == "scan-tool-1"
+ assert error["prompt_masked_data"] == {"data": self.MODEL_ARGS}
+ assert error["scan_id"] == "scan-tool-2"
if __name__ == "__main__":