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): add fail-open mode to CrowdStrike AIDR guardrail (#38568)
yucheng-berri74050e03c5ab
diff --git a/litellm/proxy/_lazy_openapi_snapshot.json b/litellm/proxy/_lazy_openapi_snapshot.jsonindex 040d258f97a..0930febc449 100644--- a/litellm/proxy/_lazy_openapi_snapshot.json+++ b/litellm/proxy/_lazy_openapi_snapshot.json@@ -8744,7 +8744,7 @@}],"default": true,- "description": "Whether to fail the request if the guardrail encounters an error. Implemented by guardrail='model_armor' and 'generic_guardrail_api'. True (default) raises the error. False logs a critical error and lets the request proceed, so only a valid guardrail response can block or modify it.",+ "description": "Whether to fail the request if the guardrail encounters an error. Implemented by guardrail='model_armor', 'generic_guardrail_api' and 'crowdstrike_aidr'. True (default) raises the error. False logs a critical error and lets the request proceed, so only a valid guardrail response can block or modify it.","title": "Fail On Error"},"guard_name": {@@ -10765,7 +10765,7 @@}],"default": true,- "description": "Whether to fail the request if the guardrail encounters an error. Implemented by guardrail='model_armor' and 'generic_guardrail_api'. True (default) raises the error. False logs a critical error and lets the request proceed, so only a valid guardrail response can block or modify it.",+ "description": "Whether to fail the request if the guardrail encounters an error. Implemented by guardrail='model_armor', 'generic_guardrail_api' and 'crowdstrike_aidr'. True (default) raises the error. False logs a critical error and lets the request proceed, so only a valid guardrail response can block or modify it.","title": "Fail On Error"},"grounding_check": {diff --git a/litellm/proxy/guardrails/guardrail_hooks/crowdstrike_aidr/__init__.py b/litellm/proxy/guardrails/guardrail_hooks/crowdstrike_aidr/__init__.pyindex 2f5e62a0611..5e75b7d4d94 100644--- a/litellm/proxy/guardrails/guardrail_hooks/crowdstrike_aidr/__init__.py+++ b/litellm/proxy/guardrails/guardrail_hooks/crowdstrike_aidr/__init__.py@@ -25,6 +25,7 @@ def initialize_guardrail(litellm_params: "LitellmParams", guardrail: "Guardrail"GuardrailEventHooks.post_call.value,],default_on=litellm_params.default_on,+ fail_on_error=litellm_params.fail_on_error,)litellm.logging_callback_manager.add_litellm_callback(_crowdstrike_aidr_callback)diff --git a/litellm/proxy/guardrails/guardrail_hooks/crowdstrike_aidr/crowdstrike_aidr.py b/litellm/proxy/guardrails/guardrail_hooks/crowdstrike_aidr/crowdstrike_aidr.pyindex b1bf9159607..31dca5a7de2 100644--- a/litellm/proxy/guardrails/guardrail_hooks/crowdstrike_aidr/crowdstrike_aidr.py+++ b/litellm/proxy/guardrails/guardrail_hooks/crowdstrike_aidr/crowdstrike_aidr.py@@ -1,10 +1,11 @@import jsonimport os+import timefrom collections.abc import Mapping, Sequencefrom typing import TYPE_CHECKING, Annotated, Final, Literal, NamedTuple, Optional, castfrom fastapi import HTTPException-from pydantic import BaseModel, ConfigDict, Field+from pydantic import BaseModel, ConfigDict, Field, ValidationErrorfrom typing_extensions import Any, overridefrom litellm._logging import verbose_proxy_logger@@ -142,7 +143,7 @@ def _extract_text_from_message(message: _Message) -> str:return "\n".join(part.text for part in content if isinstance(part, _TextContentPart))-def _merge_metadata_bags(request_data: Mapping[str, Any]) -> dict[str, Any] | None:+def _merge_metadata_bags(request_data: Mapping[str, Any]) -> Mapping[str, Any] | None:merged: Final[dict[str, Any]] = {}present = Falsefor bag in (request_data.get("metadata"), request_data.get("litellm_metadata")):@@ -153,7 +154,7 @@ def _merge_metadata_bags(request_data: Mapping[str, Any]) -> dict[str, Any] | Nodef _messages_since_last_assistant(- messages: list[AllMessageValues],+ messages: Sequence[AllMessageValues],) -> _FilteredMessages:if not messages:return _FilteredMessages([], ())@@ -239,6 +240,7 @@ class CrowdStrikeAIDRHandler(CustomGuardrail):guardrail_name: str,api_key: str | None = None,api_base: str | None = None,+ fail_on_error: bool | None = True,**kwargs,) -> None:"""@@ -251,6 +253,7 @@ class CrowdStrikeAIDRHandler(CustomGuardrail):**kwargs: Additional arguments passed to the CustomGuardrail base class."""self.async_handler = get_async_httpx_client(llm_provider=httpxSpecialProvider.GuardrailCallback)+ self.fail_on_error = True if fail_on_error is None else fail_on_errorself.api_key = api_key or os.environ.get("CS_AIDR_TOKEN")if not self.api_key:@@ -306,11 +309,13 @@ class CrowdStrikeAIDRHandler(CustomGuardrail):assert response is not Noneresponse.raise_for_status()- result = _GuardChatCompletionsResponse.model_validate(response.json()).result or _GuardChatCompletionsResult()+ response_body: Final[object] = response.json()+ raw_result: Final[object] = response_body.get("result") if isinstance(response_body, dict) else None+ blocked_signal: Final[object] = raw_result.get("blocked") if isinstance(raw_result, dict) else None- if result.blocked:+ if blocked_signal:verbose_proxy_logger.warning(- "CrowdStrike AIDR Guardrail (%s): Request blocked. Response: %s", hook_name, result+ "CrowdStrike AIDR Guardrail (%s): Request blocked. Verdict: %s", hook_name, blocked_signal)raise HTTPException(status_code=400, # Bad Request, indicating violation@@ -319,6 +324,23 @@ class CrowdStrikeAIDRHandler(CustomGuardrail):"guardrail_name": self.guardrail_name,},)++ try:+ result: Final = (+ _GuardChatCompletionsResponse.model_validate(response_body).result or _GuardChatCompletionsResult()+ )+ except ValidationError as validation_error:+ transformed_signal: Final[object] = raw_result.get("transformed") if isinstance(raw_result, dict) else None+ if transformed_signal:+ raise HTTPException(+ status_code=500,+ detail={ # mutable-ok: one-shot HTTPException detail payload, never mutated after construction+ "error": "CrowdStrike AIDR returned a transformed response litellm could not parse; "+ "failing closed instead of dropping the delivered redactions",+ "guardrail_name": self.guardrail_name,+ },+ ) from validation_error+ raiseverbose_proxy_logger.debug("CrowdStrike AIDR Guardrail (%s): Request passed. Response: %s", hook_name, result.detectors)@@ -362,6 +384,34 @@ class CrowdStrikeAIDRHandler(CustomGuardrail):tail: Final = guard_output.messages[-num_assistant_messages:] if num_assistant_messages > 0 else []return [_extract_text_from_message(msg) for msg in tail]+ async def _call_or_fail_open(+ self, payload: dict[str, Any], hook_name: str, request_data: dict+ ) -> _GuardChatCompletionsResult:+ start_time: Final = time.time()+ try:+ return await self._call_crowdstrike_aidr_guard(payload, hook_name)+ except HTTPException:+ raise+ except Exception as error:+ if self.fail_on_error:+ raise+ verbose_proxy_logger.error(+ "CrowdStrike AIDR Guardrail failed open | hook_name: %s error: %s",+ hook_name,+ error,+ exc_info=True,+ )+ end_time: Final = time.time()+ self.add_standard_logging_guardrail_information_to_request_data(+ guardrail_json_response=error,+ request_data=request_data,+ guardrail_status="guardrail_failed_to_respond",+ start_time=start_time,+ end_time=end_time,+ duration=end_time - start_time,+ )+ return _GuardChatCompletionsResult()+@overridedef structured_messages_cover_full_request(self) -> bool:return effective_skip_system_message_for_guardrail(self) or effective_skip_tool_message_for_guardrail(self)@@ -439,7 +489,7 @@ class CrowdStrikeAIDRHandler(CustomGuardrail):extra_info["user_name"] = user_emailai_guard_payload["extra_info"] = extra_info- result: Final = await self._call_crowdstrike_aidr_guard(ai_guard_payload, hook_name)+ result: Final = await self._call_or_fail_open(ai_guard_payload, hook_name, request_data)if "body" in request_data or "messages" in request_data:add_guardrail_to_applied_guardrails_header(request_data=request_data, guardrail_name=self.guardrail_name)diff --git a/litellm/types/guardrails.py b/litellm/types/guardrails.pyindex e48c36de8ba..f77f8c280de 100644--- a/litellm/types/guardrails.py+++ b/litellm/types/guardrails.py@@ -855,7 +855,7 @@ class BaseLitellmParams(ContentFilterConfigModel): # works for new and patch updefault=True,description=("Whether to fail the request if the guardrail encounters an error. "- "Implemented by guardrail='model_armor' and 'generic_guardrail_api'. "+ "Implemented by guardrail='model_armor', 'generic_guardrail_api' and 'crowdstrike_aidr'. ""True (default) raises the error. False logs a critical error and lets the request proceed, ""so only a valid guardrail response can block or modify it."),diff --git a/litellm/types/proxy/guardrails/guardrail_hooks/crowdstrike_aidr.py b/litellm/types/proxy/guardrails/guardrail_hooks/crowdstrike_aidr.pyindex 1d30f0f2c7a..f47c38af3e3 100644--- a/litellm/types/proxy/guardrails/guardrail_hooks/crowdstrike_aidr.py+++ b/litellm/types/proxy/guardrails/guardrail_hooks/crowdstrike_aidr.py@@ -16,6 +16,13 @@ class CrowdStrikeAIDRGuardrailConfigModel(GuardrailConfigModel[CrowdStrikeAIDRGudefault=None,description="The CrowdStrike AIDR API base URL. Reads from CS_AIDR_BASE_URL env var if None.",)+ fail_on_error: bool | None = Field(+ default=True,+ description="When False, errors calling the AIDR guard API (connection failures, timeouts, 4xx/5xx "+ "responses, malformed reply bodies) fail open and the request proceeds unmodified. A blocked verdict "+ "delivered on a success response still blocks, and a transformed response that cannot be parsed "+ "fails closed so delivered redactions are never dropped.",+ )@staticmethoddef ui_friendly_name() -> str:diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_crowdstrike_aidr.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_crowdstrike_aidr.pyindex a1c3186e0b9..ec7854b9a35 100644--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_crowdstrike_aidr.py+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_crowdstrike_aidr.py@@ -4,11 +4,15 @@ import httpximport pytestfrom fastapi import HTTPException+from litellm.exceptions import Timeout+from litellm.litellm_core_utils.core_helpers import get_or_create_metadata_bucket+from litellm.proxy.guardrails.guardrail_hooks.crowdstrike_aidr import initialize_guardrailfrom litellm.proxy.guardrails.guardrail_hooks.crowdstrike_aidr.crowdstrike_aidr import (CrowdStrikeAIDRGuardrailMissingSecrets,CrowdStrikeAIDRHandler,)from litellm.proxy.guardrails.init_guardrails import init_guardrails_v2+from litellm.types.guardrails import Guardrail, LitellmParamsfrom litellm.types.utils import GenericGuardrailAPIInputs, ModelResponse@@ -79,6 +83,55 @@ def test_crowdstrike_aidr_guardrail_config_no_api_base(monkeypatch) -> None:)+ ("configured", "expected"),+ [({}, True), ({"fail_on_error": None}, True), ({"fail_on_error": True}, True), ({"fail_on_error": False}, False)],+)+def test_initialize_guardrail_wires_fail_on_error_and_defaults_closed(configured: dict, expected: bool) -> None:+ litellm_params = LitellmParams(+ guardrail="crowdstrike_aidr",+ mode="pre_call",+ api_key="pts_crowdstrike_tokenid",+ api_base="https://api.crowdstrike.com/aidr/aiguard",+ **configured,+ )+ guardrail = Guardrail(guardrail_name="crowdstrike-aidr-guard", litellm_params=litellm_params)++ handler = initialize_guardrail(litellm_params=litellm_params, guardrail=guardrail)++ assert handler.fail_on_error is expected+++async def test_apply_guardrail_fails_open_on_4xx() -> None:+ guardrail = CrowdStrikeAIDRHandler(+ mode="post_call",+ guardrail_name="crowdstrike-aidr-guard",+ api_key="pts_crowdstrike_tokenid",+ api_base="https://api.crowdstrike.com/aidr/aiguard",+ fail_on_error=False,+ )+ inputs: GenericGuardrailAPIInputs = {+ "texts": ["core dump: \x00\x01 raw bytes"],+ "structured_messages": [{"role": "user", "content": "core dump: raw bytes"}],+ }+ request_data = {"messages": inputs["structured_messages"]}++ transport = httpx.MockTransport(+ lambda request: httpx.Response(status_code=400, json={"error": "guard api error"}, request=request)+ )+ async with httpx.AsyncClient(transport=transport) as client:+ await guardrail.async_handler.close()+ guardrail.async_handler.client = client+ result = await guardrail.apply_guardrail(+ inputs=inputs,+ request_data=request_data,+ input_type="request",+ )++ assert result == inputs++@pytest.mark.asyncioasync def test_apply_guardrail_request_blocked(crowdstrike_aidr_guardrail: CrowdStrikeAIDRHandler,@@ -1308,3 +1361,220 @@ async def test_anthropic_tool_calling_transform_redacts_without_index_error(assert "<EMAIL_ADDRESS>" in serializedassert "[email protected]" not in serializedassert "tu1" in serialized+++def _fail_open_guardrail() -> CrowdStrikeAIDRHandler:+ return CrowdStrikeAIDRHandler(+ mode="post_call",+ guardrail_name="crowdstrike-aidr-guard",+ api_key="pts_crowdstrike_tokenid",+ api_base="https://api.crowdstrike.com/aidr/aiguard",+ fail_on_error=False,+ )+++def _malformed_inputs() -> GenericGuardrailAPIInputs:+ return {+ "texts": ["core dump: \x00\x01 raw bytes"],+ "structured_messages": [{"role": "user", "content": "core dump: raw bytes"}],+ }+++def _error_status_transport(status_code: int) -> httpx.MockTransport:+ return httpx.MockTransport(+ lambda request: httpx.Response(status_code=status_code, json={"error": "guard api error"}, request=request)+ )+++def _connect_timeout_transport() -> httpx.MockTransport:+ def _raise(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectTimeout("simulated connect timeout", request=request)++ return httpx.MockTransport(_raise)+++_SCHEMA_DRIFT_BLOCK_BODY = {+ "result": {+ "blocked": True,+ "transformed": False,+ "guard_output": {+ "messages": [+ {+ "role": "user",+ "content": [{"type": "text", "text": "[BLOCKED]", "reason": "policy"}],+ }+ ]+ },+ "detectors": {"prompt_injection": {"detected": True}},+ }+}+++def _schema_drift_block_transport() -> httpx.MockTransport:+ return httpx.MockTransport(+ lambda request: httpx.Response(status_code=200, json=_SCHEMA_DRIFT_BLOCK_BODY, request=request)+ )+++async def _apply_with_transport(+ guardrail: CrowdStrikeAIDRHandler,+ transport: httpx.MockTransport,+ inputs: GenericGuardrailAPIInputs,+ request_data: dict,+) -> GenericGuardrailAPIInputs:+ async with httpx.AsyncClient(transport=transport) as client:+ await guardrail.async_handler.close()+ guardrail.async_handler.client = client+ return await guardrail.apply_guardrail(+ inputs=inputs,+ request_data=request_data,+ input_type="request",+ )+++async def test_apply_guardrail_fails_closed_on_guard_api_error(+ crowdstrike_aidr_guardrail: CrowdStrikeAIDRHandler,+) -> None:+ inputs = _malformed_inputs()+ request_data = {"messages": inputs["structured_messages"]}++ with pytest.raises(httpx.HTTPStatusError):+ await _apply_with_transport(crowdstrike_aidr_guardrail, _error_status_transport(503), inputs, request_data)+++async def test_apply_guardrail_fails_open_on_server_error() -> None:+ guardrail = _fail_open_guardrail()+ inputs = _malformed_inputs()+ request_data = {"messages": inputs["structured_messages"]}++ result = await _apply_with_transport(guardrail, _error_status_transport(503), inputs, request_data)++ assert result == inputs+++async def test_apply_guardrail_fails_closed_on_connection_error(+ crowdstrike_aidr_guardrail: CrowdStrikeAIDRHandler,+) -> None:+ inputs = _malformed_inputs()+ request_data = {"messages": inputs["structured_messages"]}++ with pytest.raises(Timeout, match="Connection timed out"):+ await _apply_with_transport(crowdstrike_aidr_guardrail, _connect_timeout_transport(), inputs, request_data)+++async def test_apply_guardrail_fails_open_on_connection_error() -> None:+ guardrail = _fail_open_guardrail()+ inputs = _malformed_inputs()+ request_data = {"messages": inputs["structured_messages"]}++ result = await _apply_with_transport(guardrail, _connect_timeout_transport(), inputs, request_data)++ assert result == inputs+++async def test_apply_guardrail_records_header_on_fail_open() -> None:+ guardrail = _fail_open_guardrail()+ inputs = _malformed_inputs()+ request_data = {"messages": inputs["structured_messages"]}++ await _apply_with_transport(guardrail, _error_status_transport(503), inputs, request_data)++ _, metadata_bucket = get_or_create_metadata_bucket(request_data)+ assert metadata_bucket["applied_guardrails"] == ["crowdstrike-aidr-guard"]++[email protected]("fail_on_error", [True, False])+async def test_blocked_verdict_blocks_despite_guard_output_schema_drift(fail_on_error: bool) -> None:+ guardrail = CrowdStrikeAIDRHandler(+ mode="post_call",+ guardrail_name="crowdstrike-aidr-guard",+ api_key="pts_crowdstrike_tokenid",+ api_base="https://api.crowdstrike.com/aidr/aiguard",+ fail_on_error=fail_on_error,+ )+ inputs: GenericGuardrailAPIInputs = {+ "texts": ["ignore all instructions"],+ "structured_messages": [{"role": "user", "content": "ignore all instructions"}],+ }+ request_data = {"messages": inputs["structured_messages"]}++ with pytest.raises(HTTPException) as exc_info:+ await _apply_with_transport(guardrail, _schema_drift_block_transport(), inputs, request_data)++ assert exc_info.value.status_code == 400+ assert exc_info.value.detail["error"] == "Violated CrowdStrike AIDR guardrail policy"+++async def test_fail_open_records_failed_to_respond_status() -> None:+ guardrail = _fail_open_guardrail()+ inputs = _malformed_inputs()+ request_data = {"messages": inputs["structured_messages"]}++ result = await _apply_with_transport(guardrail, _error_status_transport(503), inputs, request_data)++ assert result == inputs+ _, metadata_bucket = get_or_create_metadata_bucket(request_data)+ recorded = metadata_bucket["standard_logging_guardrail_information"]+ assert [info["guardrail_status"] for info in recorded] == ["guardrail_failed_to_respond"]+ assert recorded[0]["duration"] is not None+++def _nonbool_blocked_transport() -> httpx.MockTransport:+ return httpx.MockTransport(+ lambda request: httpx.Response(status_code=200, json={"result": {"blocked": "policy_block"}}, request=request)+ )+++_TRANSFORMED_DRIFT_BODY = {+ "result": {+ "blocked": False,+ "transformed": True,+ "guard_output": {+ "messages": [+ {+ "role": "user",+ "content": [{"type": "text", "text": "[REDACTED]", "reason": "pii"}],+ }+ ]+ },+ }+}+++def _transformed_drift_transport() -> httpx.MockTransport:+ return httpx.MockTransport(+ lambda request: httpx.Response(status_code=200, json=_TRANSFORMED_DRIFT_BODY, request=request)+ )+++async def test_nonboolean_blocked_signal_blocks_under_fail_open() -> None:+ guardrail = _fail_open_guardrail()+ inputs = _malformed_inputs()+ request_data = {"messages": inputs["structured_messages"]}++ with pytest.raises(HTTPException) as exc_info:+ await _apply_with_transport(guardrail, _nonbool_blocked_transport(), inputs, request_data)++ assert exc_info.value.status_code == 400+ assert exc_info.value.detail["error"] == "Violated CrowdStrike AIDR guardrail policy"+++async def test_unparseable_transformed_response_fails_closed_under_fail_open() -> None:+ guardrail = _fail_open_guardrail()+ inputs = _malformed_inputs()+ request_data = {"messages": inputs["structured_messages"]}++ with pytest.raises(HTTPException) as exc_info:+ await _apply_with_transport(guardrail, _transformed_drift_transport(), inputs, request_data)++ assert exc_info.value.status_code == 500+ assert "failing closed" in exc_info.value.detail["error"]diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex 405ec9a01bf..24ed24512dc 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -22976,7 +22976,7 @@ export interface components {extra_headers?: string[] | null;/*** Fail On Error- * @description Whether to fail the request if the guardrail encounters an error. Implemented by guardrail='model_armor' and 'generic_guardrail_api'. True (default) raises the error. False logs a critical error and lets the request proceed, so only a valid guardrail response can block or modify it.+ * @description Whether to fail the request if the guardrail encounters an error. Implemented by guardrail='model_armor', 'generic_guardrail_api' and 'crowdstrike_aidr'. True (default) raises the error. False logs a critical error and lets the request proceed, so only a valid guardrail response can block or modify it.* @default true*/fail_on_error: boolean | null;@@ -29684,7 +29684,7 @@ export interface components {extra_headers?: string[] | null;/*** Fail On Error- * @description Whether to fail the request if the guardrail encounters an error. Implemented by guardrail='model_armor' and 'generic_guardrail_api'. True (default) raises the error. False logs a critical error and lets the request proceed, so only a valid guardrail response can block or modify it.+ * @description Whether to fail the request if the guardrail encounters an error. Implemented by guardrail='model_armor', 'generic_guardrail_api' and 'crowdstrike_aidr'. True (default) raises the error. False logs a critical error and lets the request proceed, so only a valid guardrail response can block or modify it.* @default true*/fail_on_error: boolean | null;