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/rubrik): attribute blocked requests to the caller that made them (#35734)
yucheng-berri2d1f650e9a5a
diff --git a/basedpyright-code-budget.json b/basedpyright-code-budget.jsonindex f6dd90077b1..90e0a283c63 100644--- a/basedpyright-code-budget.json+++ b/basedpyright-code-budget.json@@ -1,6 +1,6 @@{"reportAny": {- "limit": 29813+ "limit": 29811},"reportArgumentType": {"limit": 2645@@ -24,7 +24,7 @@"limit": 42},"reportExplicitAny": {- "limit": 9473+ "limit": 9471},"reportFunctionMemberAccess": {"limit": 11diff --git a/litellm/integrations/rubrik.py b/litellm/integrations/rubrik.pyindex 4bcbe8bae37..9942776bc00 100644--- a/litellm/integrations/rubrik.py+++ b/litellm/integrations/rubrik.py@@ -34,12 +34,14 @@ from litellm.types.utils import (Function,GenericGuardrailAPIInputs,StandardLoggingPayload,+ StandardLoggingUserAPIKeyMetadata,)if TYPE_CHECKING:from litellm.litellm_core_utils.litellm_logging import (Logging as LiteLLMLoggingObj,)+ from litellm.proxy._types import UserAPIKeyAuth_WEBHOOK_PATH_RESPONSE_MODERATION = "/v1/after_completion/openai/v1"_WEBHOOK_PATH_PROMPT_MODERATION = "/v1/before_prompt/openai/v1"@@ -725,7 +727,7 @@ class RubrikLogger(CustomGuardrail, CustomBatchLogger):self,request_data: dict,original_exception: Exception,- user_api_key_dict: Any,+ user_api_key_dict: "UserAPIKeyAuth",traceback_str: str | None = None,) -> None:"""Log blocked requests signalled via ``ModifyResponseException``@@ -755,20 +757,21 @@ class RubrikLogger(CustomGuardrail, CustomBatchLogger):"Rubrik: block exception without stashed logging_obj. "f"litellm_call_id={request_data.get('litellm_call_id')}, "f"model={request_data.get('model')}, "- f"user_id={getattr(user_api_key_dict, 'user_id', None)}, "+ f"user_id={user_api_key_dict.user_id}, "f"raising_guardrail="f"{getattr(original_exception, 'guardrail_name', None)}")returncall_id: str | None = None- await self._build_and_enqueue_block_event(logging_obj, original_exception, call_id)+ await self._build_and_enqueue_block_event(logging_obj, original_exception, call_id, user_api_key_dict)async def _build_and_enqueue_block_event(self,logging_obj: "LiteLLMLoggingObj",exception: "ModifyResponseException",call_id: str | None,+ user_api_key_dict: "UserAPIKeyAuth",) -> None:try:call_details = logging_obj.model_call_details@@ -780,8 +783,8 @@ class RubrikLogger(CustomGuardrail, CustomBatchLogger):# prevent. The flag dies with model_call_details when the request# completes; there's nothing to clean up.call_id = call_details.get("litellm_call_id")- payload = self._prepare_block_failure_payload(logging_obj, exception)- except (AttributeError, KeyError, TypeError) as e:+ payload = self._prepare_block_failure_payload(logging_obj, exception, user_api_key_dict)+ except (AttributeError, ImportError, KeyError, TypeError) as e:verbose_logger.error(f"Rubrik: failed to build blocked-tool payload for "f"litellm_call_id={call_id}: {e}. Event will NOT be logged.",@@ -801,17 +804,20 @@ class RubrikLogger(CustomGuardrail, CustomBatchLogger):self,logging_obj: "LiteLLMLoggingObj",exception: "ModifyResponseException",+ user_api_key_dict: "UserAPIKeyAuth",) -> StandardLoggingPayload:"""Build a failure-style payload using the exception text as response.Blocked-tool events are security-relevant and **bypass sampling**:every block is logged.- The deferred success-handler runs as a separately-scheduled task and- races with this hook, so ``standard_logging_object`` on- ``model_call_details`` may not yet be populated. If present we reuse- it; otherwise we fall back to a best-effort payload built from the- fields available at block time.+ A non-streaming block always takes the fallback, and not because of a+ race: registering a post_call guardrail sets ``_defer_async_logging``,+ which parks the success handler that would have written+ ``standard_logging_object``, and ``_flush_deferred_async_logging``+ returns early once an exception was raised. Streaming requests never set+ that flag, so a streamed block can arrive with the object already+ populated; the branch below covers it and wins over the fallback.For prompt blocks the LLM is never called, so ``standard_logging_object``is never populated. The fallback therefore must carry enough fields to@@ -830,9 +836,11 @@ class RubrikLogger(CustomGuardrail, CustomBatchLogger):``acompletion()``, which hasn't run yet for a prompt block.- ``model_id``: not available before the LLM returns hidden_params;defaults to empty string.- - ``user_api_key_hash``: ``call_details["metadata"]["user_api_key"]`` --- the hashed token written by ``add_user_information_to_request_data``- before ``pre_call_hook`` fires.+ - caller identity: ``_caller_metadata`` off the ``user_api_key_dict``+ the failure hook is handed. The enriched litellm metadata lives under+ ``call_details["litellm_params"]["metadata"]``, never at the top+ level, so the previous top-level read resolved to an empty string for+ every block.- time fields: ``call_details["start_time"]`` reused for all three;end/completion times are meaningless for a prompt block."""@@ -848,7 +856,7 @@ class RubrikLogger(CustomGuardrail, CustomBatchLogger):f"for litellm_call_id={call_details.get('litellm_call_id')}; ""using best-effort fallback payload.")- payload = self._build_fallback_payload(call_details)+ payload = self._build_fallback_payload(call_details, user_api_key_dict)payload["response"] = exception_text@@ -863,8 +871,30 @@ class RubrikLogger(CustomGuardrail, CustomBatchLogger):return payload # type: ignore[return-value]@staticmethod- def _build_fallback_payload(call_details: Mapping[str, Any]) -> dict[str, Any]:- _metadata: Mapping[str, Any] = call_details.get("metadata") or _EMPTY_MAPPING+ def _caller_metadata(user_api_key_dict: "UserAPIKeyAuth") -> StandardLoggingUserAPIKeyMetadata:+ """Identify the caller whose request was blocked.++ Uses the same mapper the success path and the proxy spend logger use, so+ a block log and a success log agree on the caller key set.++ The import is deferred because ``litellm/integrations/`` is SDK-side+ while the mapper lives under ``proxy/``: ``rubrik.py`` is imported during+ guardrail discovery and must not pull proxy-only dependencies into its+ import chain. It is unguarded because the only dispatcher of this hook,+ ``ProxyLogging.post_call_failure_hook``, already imports fastapi at+ module scope, so there is no path where this hook runs and the mapper is+ missing.+ """+ from litellm.proxy.litellm_pre_call_utils import LiteLLMProxyRequestSetup++ return LiteLLMProxyRequestSetup.get_sanitized_user_information_from_key(user_api_key_dict)++ @classmethod+ def _build_fallback_payload(+ cls,+ call_details: Mapping[str, Any],+ user_api_key_dict: "UserAPIKeyAuth",+ ) -> dict[str, Any]:# Convert datetime to a Unix float so json.dumps can serialize it.# httpx's json= parameter uses stdlib json.dumps with no custom encoder._raw_start = call_details.get("start_time")@@ -884,11 +914,7 @@ class RubrikLogger(CustomGuardrail, CustomBatchLogger):"endTime": _start,"completionStartTime": _start,"messages": call_details.get("messages") or (),- "metadata": {- # "user_api_key" is the hashed token written by- # add_user_information_to_request_data before guardrails fire.- "user_api_key_hash": _metadata.get("user_api_key_hash") or _metadata.get("user_api_key") or "",- },+ "metadata": cls._caller_metadata(user_api_key_dict),"status": "failure",}diff --git a/ruff-strict-budget.json b/ruff-strict-budget.jsonindex d3ef01940bb..003e09de0c2 100644--- a/ruff-strict-budget.json+++ b/ruff-strict-budget.json@@ -24,7 +24,7 @@"limit": 130},"ANN401": {- "limit": 1851+ "limit": 1850},"ASYNC230": {"limit": 14diff --git a/tests/test_litellm/integrations/test_rubrik.py b/tests/test_litellm/integrations/test_rubrik.pyindex 7f589dc15bf..4a2ee487c65 100644--- a/tests/test_litellm/integrations/test_rubrik.py+++ b/tests/test_litellm/integrations/test_rubrik.py@@ -17,6 +17,7 @@ from litellm.integrations.rubrik import (RubrikLogger,_MalformedToolBlockingResponseError,)+from litellm.proxy._types import UserAPIKeyAuthfrom tests.test_litellm.integrations.rubrik_test_helpers import (make_inputs_with_tools,@@ -44,6 +45,18 @@ def handler(mock_env):return RubrikLogger()+def user_api_key_dict():+ """The authenticated caller the proxy hands to async_post_call_failure_hook."""+ return UserAPIKeyAuth(+ api_key="sk-block-attribution-test",+ key_alias="rubrik-probe-key",+ user_id="probe-user-1",+ team_id="probe-team-1",+ org_id="probe-org-1",+ )++# -- Initialization -----------------------------------------------------------@@ -1544,17 +1557,17 @@ class TestSuccessEventBlockedSkip:@pytest.mark.asyncioclass TestPostCallFailureHook:- async def test_non_modify_exception_returns_immediately(self, handler):+ async def test_non_modify_exception_returns_immediately(self, handler, user_api_key_dict):"""Non-ModifyResponseException causes a no-op."""await handler.async_post_call_failure_hook(request_data={"litellm_call_id": "test"},original_exception=ValueError("unrelated error"),- user_api_key_dict=None,+ user_api_key_dict=user_api_key_dict,)assert len(handler.log_queue) == 0async def test_modify_exception_without_stashed_logging_obj_emits_warning(- self, handler+ self, handler, user_api_key_dict):"""ModifyResponseException with no _rubrik_logging_obj → warning, no enqueue."""request_data = {"litellm_call_id": "test-123", "model": "gpt-4"}@@ -1568,12 +1581,12 @@ class TestPostCallFailureHook:await handler.async_post_call_failure_hook(request_data=request_data,original_exception=exc,- user_api_key_dict=None,+ user_api_key_dict=user_api_key_dict,)assert len(handler.log_queue) == 0async def test_modify_exception_with_valid_logging_obj_enqueues_payload(- self, handler+ self, handler, user_api_key_dict):"""ModifyResponseException + stashed logging_obj → builds and enqueues."""logging_obj = Mock()@@ -1602,12 +1615,12 @@ class TestPostCallFailureHook:await handler.async_post_call_failure_hook(request_data=request_data,original_exception=exc,- user_api_key_dict=None,+ user_api_key_dict=user_api_key_dict,)assert len(handler.log_queue) == 1assert "ModifyResponseException" in handler.log_queue[0]["response"]- async def test_logging_obj_popped_from_request_data(self, handler):+ async def test_logging_obj_popped_from_request_data(self, handler, user_api_key_dict):"""_rubrik_logging_obj must be popped from request_data so it is notforwarded downstream."""logging_obj = Mock()@@ -1636,12 +1649,12 @@ class TestPostCallFailureHook:await handler.async_post_call_failure_hook(request_data=request_data,original_exception=exc,- user_api_key_dict=None,+ user_api_key_dict=user_api_key_dict,)assert "_rubrik_logging_obj" not in request_dataasync def test_build_and_enqueue_swallows_attribute_error_from_prepare_payload(- self, handler+ self, handler, user_api_key_dict):"""When _prepare_block_failure_payload raises AttributeError/KeyError/TypeError,the error is logged and the event is silently dropped (lines 806-812)."""@@ -1657,10 +1670,10 @@ class TestPostCallFailureHook:)# Must not raise- await handler._build_and_enqueue_block_event(logging_obj, exc, None)+ await handler._build_and_enqueue_block_event(logging_obj, exc, None, user_api_key_dict)assert len(handler.log_queue) == 0- async def test_build_and_enqueue_swallows_flush_exception(self, handler):+ async def test_build_and_enqueue_swallows_flush_exception(self, handler, user_api_key_dict):"""When _append_and_maybe_flush raises, the error is logged (lines 816-817)."""logging_obj = Mock()logging_obj.model_call_details = {@@ -1688,14 +1701,14 @@ class TestPostCallFailureHook:)# Must not raise- await handler._build_and_enqueue_block_event(logging_obj, exc, None)+ await handler._build_and_enqueue_block_event(logging_obj, exc, None, user_api_key_dict)# -- _prepare_block_failure_payload and _build_fallback_payload ---------------class TestPrepareBlockFailurePayload:- def test_uses_standard_logging_object_when_present(self, handler):+ def test_uses_standard_logging_object_when_present(self, handler, user_api_key_dict):"""When standard_logging_object is on model_call_details, it is used as base."""logging_obj = Mock()logging_obj.model_call_details = {@@ -1716,12 +1729,37 @@ class TestPrepareBlockFailurePayload:guardrail_name="rubrik",)- payload = handler._prepare_block_failure_payload(logging_obj, exc)+ payload = handler._prepare_block_failure_payload(logging_obj, exc, user_api_key_dict)assert "ModifyResponseException: blocked" in payload["response"]assert payload["id"] == "call-slo"- def test_uses_fallback_when_standard_logging_object_absent(self, handler):+ def test_standard_logging_object_identity_is_not_overwritten(self, handler, user_api_key_dict):+ """A streamed block can arrive with the object populated; it keeps its own identity."""+ logging_obj = Mock()+ logging_obj.model_call_details = {+ "litellm_call_id": "call-slo-identity",+ "model": "gpt-4",+ "standard_logging_object": {+ "id": "chatcmpl-original",+ "model": "gpt-4",+ "response": "original response",+ "messages": [],+ "metadata": {"user_api_key_hash": "hash-from-standard-logging-object"},+ },+ }+ exc = ModifyResponseException(+ message="blocked",+ model="gpt-4",+ request_data={},+ guardrail_name="rubrik",+ )++ payload = handler._prepare_block_failure_payload(logging_obj, exc, user_api_key_dict)++ assert payload["metadata"]["user_api_key_hash"] == "hash-from-standard-logging-object"++ def test_uses_fallback_when_standard_logging_object_absent(self, handler, user_api_key_dict):"""When standard_logging_object is absent, _build_fallback_payload is used."""from datetime import datetime@@ -1731,7 +1769,7 @@ class TestPrepareBlockFailurePayload:"model": "claude-3","messages": [{"role": "user", "content": "question"}],"optional_params": {"temperature": 0.5},- "metadata": {"user_api_key_hash": "hash-abc"},+ "metadata": {"headers": {"host": "127.0.0.1:4000", "user-agent": "curl/8.7.1"}},"start_time": datetime(2024, 6, 1),}exc = ModifyResponseException(@@ -1741,16 +1779,15 @@ class TestPrepareBlockFailurePayload:guardrail_name="rubrik",)- payload = handler._prepare_block_failure_payload(logging_obj, exc)+ payload = handler._prepare_block_failure_payload(logging_obj, exc, user_api_key_dict)assert payload["id"] == "call-fallback"assert payload["model"] == "claude-3"assert payload["model_group"] == "claude-3"assert "ModifyResponseException: prompt blocked" in payload["response"]- assert payload["metadata"]["user_api_key_hash"] == "hash-abc"assert payload["status"] == "failure"- def test_fallback_payload_without_start_time(self, handler):+ def test_fallback_payload_without_start_time(self, handler, user_api_key_dict):"""_build_fallback_payload handles missing start_time gracefully."""logging_obj = Mock()logging_obj.model_call_details = {@@ -1767,10 +1804,90 @@ class TestPrepareBlockFailurePayload:guardrail_name="rubrik",)- payload = handler._prepare_block_failure_payload(logging_obj, exc)+ payload = handler._prepare_block_failure_payload(logging_obj, exc, user_api_key_dict)assert payload["startTime"] is None+class TestBlockPayloadCallerAttribution:+ """A block log must identify the caller that triggered it.++ The enriched litellm metadata lives under+ ``model_call_details["litellm_params"]["metadata"]``, never at the top+ level, so sourcing identity from ``call_details["metadata"]`` yielded an+ empty string for every block. Identity comes from the authenticated+ ``user_api_key_dict`` the failure hook is handed.+ """++ def _blocked_call_details(self):+ return {+ "litellm_call_id": "call-attr",+ "model": "claude-3",+ "messages": [{"role": "user", "content": "question"}],+ "optional_params": {},+ "metadata": {"headers": {"host": "127.0.0.1:4000", "user-agent": "curl/8.7.1"}},+ }++ def test_fallback_payload_identifies_the_caller(self, handler, user_api_key_dict):+ payload = handler._build_fallback_payload(self._blocked_call_details(), user_api_key_dict)++ metadata = payload["metadata"]+ assert metadata["user_api_key_hash"] == user_api_key_dict.api_key+ assert metadata["user_api_key_alias"] == "rubrik-probe-key"+ assert metadata["user_api_key_user_id"] == "probe-user-1"+ assert metadata["user_api_key_team_id"] == "probe-team-1"+ assert metadata["user_api_key_org_id"] == "probe-org-1"++ def test_metadata_covers_the_full_caller_key_set(self, handler, user_api_key_dict):+ """A block log and a success log agree on the caller key set."""+ from litellm.types.utils import StandardLoggingUserAPIKeyMetadata++ payload = handler._build_fallback_payload(self._blocked_call_details(), user_api_key_dict)++ expected = StandardLoggingUserAPIKeyMetadata.__required_keys__ | StandardLoggingUserAPIKeyMetadata.__optional_keys__+ assert set(payload["metadata"]) == set(expected)++ def test_virtual_key_is_logged_hashed(self, handler):+ """A virtual key reaches the webhook as its hash, never as the raw token."""+ raw = "sk-block-attribution-test"+ payload = handler._build_fallback_payload(+ self._blocked_call_details(), UserAPIKeyAuth(api_key=raw)+ )++ assert payload["metadata"]["user_api_key_hash"] not in (raw, "")++ def test_request_header_metadata_is_not_used_as_identity(self, handler, user_api_key_dict):+ """The pre-fix source is present and misleading; it must not win."""+ call_details = self._blocked_call_details()+ call_details["metadata"]["user_api_key_hash"] = "stale-hash-from-request-metadata"++ payload = handler._build_fallback_payload(call_details, user_api_key_dict)++ assert payload["metadata"]["user_api_key_hash"] == user_api_key_dict.api_key++ async def test_enqueued_block_event_carries_attribution(self, handler, user_api_key_dict):+ """End of the real hook chain: what actually lands on the Rubrik queue."""+ logging_obj = Mock()+ logging_obj.model_call_details = self._blocked_call_details()+ request_data = {"litellm_call_id": "call-attr", "_rubrik_logging_obj": logging_obj}+ exc = ModifyResponseException(+ message="prompt blocked",+ model="claude-3",+ request_data=request_data,+ guardrail_name="rubrik",+ )++ await handler.async_post_call_failure_hook(+ request_data=request_data,+ original_exception=exc,+ user_api_key_dict=user_api_key_dict,+ )++ assert len(handler.log_queue) == 1+ metadata = handler.log_queue[0]["metadata"]+ assert metadata["user_api_key_hash"] == user_api_key_dict.api_key+ assert metadata["user_api_key_user_id"] == "probe-user-1"++# -- async_send_batch empty queue and flush_queue edge cases ------------------diff --git a/type-discipline-budget.json b/type-discipline-budget.jsonindex f071c381916..bf0b30967e7 100644--- a/type-discipline-budget.json+++ b/type-discipline-budget.json@@ -3,7 +3,7 @@"limit": 23350},"LIT002": {- "limit": 27256+ "limit": 27255},"LIT003": {"limit": 292