diff --git a/litellm/proxy/guardrails/guardrail_hooks/ovalix/__init__.py b/litellm/proxy/guardrails/guardrail_hooks/ovalix/__init__.py new file mode 100644 index 000000000000..b73572e4ed5a --- /dev/null +++ b/litellm/proxy/guardrails/guardrail_hooks/ovalix/__init__.py @@ -0,0 +1,46 @@ +"""Ovalix guardrail hook: registration and initialization for the proxy.""" + +from typing import TYPE_CHECKING + +from litellm.types.guardrails import SupportedGuardrailIntegrations + +from .ovalix import OvalixGuardrail + +if TYPE_CHECKING: + from litellm.types.guardrails import Guardrail, LitellmParams + + +def initialize_guardrail(litellm_params: "LitellmParams", guardrail: "Guardrail"): + """Create and register an Ovalix guardrail callback from proxy config.""" + import litellm + + tracker_api_base = getattr(litellm_params, "tracker_api_base", None) + tracker_api_key = getattr(litellm_params, "tracker_api_key", None) + application_id = getattr(litellm_params, "application_id", None) + pre_checkpoint_id = getattr(litellm_params, "pre_checkpoint_id", None) + post_checkpoint_id = getattr(litellm_params, "post_checkpoint_id", None) + + _ovalix_callback = OvalixGuardrail( + guardrail_name=guardrail.get("guardrail_name", ""), + tracker_api_base=tracker_api_base, + tracker_api_key=tracker_api_key, + application_id=application_id, + pre_checkpoint_id=pre_checkpoint_id, + post_checkpoint_id=post_checkpoint_id, + event_hook=litellm_params.mode, + default_on=litellm_params.default_on, + ) + litellm.logging_callback_manager.add_litellm_callback(_ovalix_callback) + + return _ovalix_callback + + +# Registry of guardrail name -> initializer for proxy config loading. +guardrail_initializer_registry = { + SupportedGuardrailIntegrations.OVALIX.value: initialize_guardrail, +} + +# Registry of guardrail name -> guardrail class (e.g. for apply_guardrail API). +guardrail_class_registry = { + SupportedGuardrailIntegrations.OVALIX.value: OvalixGuardrail, +} diff --git a/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py b/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py new file mode 100644 index 000000000000..bad132092dc3 --- /dev/null +++ b/litellm/proxy/guardrails/guardrail_hooks/ovalix/ovalix.py @@ -0,0 +1,330 @@ +"""Ovalix guardrail integration: pre- and post-call checks via the Tracker service. + +Use Ovalix Guardrails for your LLM calls. Supports pre_call (user input) and +post_call (model output) checkpoints with optional correction/blocking. +""" + +import datetime +import hashlib +import os +from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Type + +import httpx + +from litellm._logging import verbose_proxy_logger +from litellm.exceptions import GuardrailRaisedException +from litellm.integrations.custom_guardrail import ( + CustomGuardrail, + log_guardrail_information, +) +from litellm.llms.custom_httpx.http_handler import ( + get_async_httpx_client, + httpxSpecialProvider, +) +from litellm.types.guardrails import GuardrailEventHooks +from litellm.types.utils import GenericGuardrailAPIInputs + +if TYPE_CHECKING: + from litellm.types.proxy.guardrails.guardrail_hooks.base import GuardrailConfigModel + + +BLOCKED_BY_OVALIX_FALLBACK_MESSAGE = "This message was blocked by Ovalix" +BLOCKED_ACTION_TYPE = "block" + + +class OvalixGuardrailMissingSecrets(Exception): + """Raised when required Ovalix config (API base, key, application/checkpoint IDs) is missing.""" + + pass + + +class OvalixGuardrailBlockedException(GuardrailRaisedException): + """ + Raised when Ovalix blocks a message. Sets status_code=400 so the proxy + returns 400 and HTTP clients do not retry (they retry on 5xx). + """ + + status_code = 400 + + def __init__( + self, + guardrail_name: Optional[str] = None, + message: str = "", + should_wrap_with_default_message: bool = True, + ): + super().__init__( + guardrail_name=guardrail_name, + message=message, + should_wrap_with_default_message=should_wrap_with_default_message, + ) + + +class OvalixGuardrail(CustomGuardrail): + """ + Ovalix guardrail: pre-prompt (pre_call) and post-prompt (post_call) checks + via the Tracker service, with application and checkpoint resolution from the + Monolith backend. + """ + + def __init__( + self, + tracker_api_base: Optional[str] = None, + tracker_api_key: Optional[str] = None, + application_id: Optional[str] = None, + pre_checkpoint_id: Optional[str] = None, + post_checkpoint_id: Optional[str] = None, + **kwargs: Any, + ): + self._tracker_api_base = tracker_api_base or os.environ.get( + "OVALIX_TRACKER_API_BASE" + ) + self._tracker_api_key = tracker_api_key or os.environ.get( + "OVALIX_TRACKER_API_KEY" + ) + self._application_id = application_id or os.environ.get("OVALIX_APPLICATION_ID") + self._pre_checkpoint_id = pre_checkpoint_id or os.environ.get( + "OVALIX_PRE_CHECKPOINT_ID" + ) + self._post_checkpoint_id = post_checkpoint_id or os.environ.get( + "OVALIX_POST_CHECKPOINT_ID" + ) + + if "supported_event_hooks" not in kwargs: + kwargs["supported_event_hooks"] = [] + + self._validate_config(kwargs["supported_event_hooks"]) + + self._tracker_headers = httpx.Headers( + { + "Authorization": f"Bearer {self._tracker_api_key}", + "Content-Type": "application/json", + }, + encoding="utf-8", + ) + + self._async_handler = get_async_httpx_client( + llm_provider=httpxSpecialProvider.GuardrailCallback + ) + + super().__init__(**kwargs) + verbose_proxy_logger.debug( + "Ovalix Guardrail initialized: tracker=%s, application_id=%s, pre_checkpoint_id=%s, post_checkpoint_id=%s", + self._tracker_api_base, + self._application_id, + self._pre_checkpoint_id, + self._post_checkpoint_id, + ) + + def _validate_config( + self, supported_event_hooks: List[GuardrailEventHooks] + ) -> None: + """Ensure required secrets and checkpoint IDs are set; auto-add hooks when IDs are present.""" + errors: List[str] = [] + + if not self._tracker_api_base: + errors.append( + "Tracker API base, set OVALIX_TRACKER_API_BASE or pass tracker_api_base" + ) + if not self._tracker_api_key: + errors.append( + "Tracker API key, set OVALIX_TRACKER_API_KEY or pass tracker_api_key" + ) + if not self._application_id: + errors.append( + "Application ID, set OVALIX_APPLICATION_ID or pass application_id" + ) + if ( + not self._pre_checkpoint_id + and GuardrailEventHooks.pre_call in supported_event_hooks + ): + errors.append( + "Pre-checkpoint ID, set OVALIX_PRE_CHECKPOINT_ID or pass pre_checkpoint_id" + ) + if ( + not self._post_checkpoint_id + and GuardrailEventHooks.post_call in supported_event_hooks + ): + errors.append( + "Post-checkpoint ID, set OVALIX_POST_CHECKPOINT_ID or pass post_checkpoint_id" + ) + if not self._pre_checkpoint_id and not self._post_checkpoint_id: + errors.append( + "Pre-checkpoint ID or Post-checkpoint ID, set OVALIX_PRE_CHECKPOINT_ID or OVALIX_POST_CHECKPOINT_ID or pass pre_checkpoint_id or post_checkpoint_id" + ) + + if errors: + raise OvalixGuardrailMissingSecrets( + "Missing Ovalix guardrail configuration errors: " + ". ".join(errors) + ) + + # auto-add hooks when checkpoint IDs are present + if ( + self._pre_checkpoint_id + and GuardrailEventHooks.pre_call not in supported_event_hooks + ): + supported_event_hooks.append(GuardrailEventHooks.pre_call) + if ( + self._post_checkpoint_id + and GuardrailEventHooks.post_call not in supported_event_hooks + ): + supported_event_hooks.append(GuardrailEventHooks.post_call) + + def _get_actor(self, data: dict) -> str: + """Return a stable actor identifier from request metadata (e.g. user email or id).""" + metadata = data.get("metadata") or data.get("litellm_metadata") or {} + if metadata.get("user_api_key_user_email"): + return metadata["user_api_key_user_email"] + if metadata.get("user_api_key_user_id"): + return metadata["user_api_key_user_id"] + return "unknown" + + def _get_tracker_actor_id(self, data: dict) -> str: + """Normalize the actor string into a short, stable id for Tracker API payloads.""" + # NOTE: this hash is purely for normalization — it collapses an arbitrary actor + # string (email, user id, or "unknown") into a compact, fixed-length, consistent + # key. It is not a privacy/security measure and the actor value is not sensitive, + # so a plain SHA-256 (truncated) is sufficient; no salting/KDF is needed here. + actor_id = self._get_actor(data).encode() + normalized_actor_id = hashlib.sha256(actor_id).hexdigest()[:8] + return normalized_actor_id + + def _get_session_id(self, data: dict) -> str: + """Return a unique identifier for the chat/session (actor + date + application_id).""" + actor_hash = self._get_tracker_actor_id(data) + today = datetime.datetime.now().strftime("%Y-%m-%d") + return f"{actor_hash}_{today}_{self._application_id}" + + async def _call_checkpoint( + self, + content: str, + checkpoint_id: str, + actor: str, + session_id: str, + ) -> Dict[str, Any]: + """Call the Ovalix Tracker checkpoint API and return the JSON response.""" + application_id = self._application_id + if not application_id or not checkpoint_id: + raise ValueError("Ovalix: application_id or checkpoint_id not resolved") + + url = f"{self._tracker_api_base}/tracking/custom_application/checkpoint" + headers = dict(self._tracker_headers) + payload = { + "application_id": application_id, + "checkpoint_id": checkpoint_id, + "actor": actor, + "session_id": session_id, + "data_type": "TEXT", + "data": {"content": content}, + } + response = await self._async_handler.post(url, headers=headers, json=payload) + response.raise_for_status() + return response.json() + + @log_guardrail_information + async def apply_guardrail( + self, + inputs: GenericGuardrailAPIInputs, + request_data: dict, + input_type: Literal["request", "response"], + logging_obj: Optional[Any] = None, + ) -> GenericGuardrailAPIInputs: + """ + Apply Ovalix guardrail to the given inputs (request or response text). + + Used by the unified guardrail flow and the /apply_guardrail API. + For "request", uses the pre-checkpoint; for "response", uses the post-checkpoint. + + Args: + inputs: Guardrail API inputs (e.g. texts to check). + request_data: Full request payload (messages, metadata, response). + input_type: "request" (pre_call) or "response" (post_call). + logging_obj: Optional logging context. + + Returns: + Updated inputs (e.g. with replaced/corrected texts, or unchanged). + """ + if not self._pre_checkpoint_id and not self._post_checkpoint_id: + return inputs + + tracker_actor_id = self._get_tracker_actor_id(request_data) + session_id = self._get_session_id(request_data) + texts = inputs.get("texts") or [] + if not texts or not isinstance(texts, list): + return inputs + + if input_type == "response": + if not self._post_checkpoint_id: + return inputs + corrected_llm_responses = await self._generate_post_guardrail_llm_texts( + texts, tracker_actor_id, session_id, self._post_checkpoint_id + ) + return {**inputs, "texts": corrected_llm_responses} + + if self._pre_checkpoint_id: + post_guardrail_texts = await self._generate_post_guardrail_llm_texts( + texts, tracker_actor_id, session_id, self._pre_checkpoint_id + ) + return {**inputs, "texts": post_guardrail_texts} + return inputs + + async def _generate_post_guardrail_llm_texts( + self, texts: List[str], actor: str, session_id: str, checkpoint_id: str + ) -> List[str]: + """Generate post-guardrail LLM responses for the given LLM responses.""" + post_guardrail_texts: List[str] = [] + + is_first_response = True + for llm_response in reversed(texts): + try: + resp = await self._call_checkpoint( + llm_response, checkpoint_id, actor, session_id + ) + except Exception as e: + verbose_proxy_logger.exception( + "Ovalix apply_guardrail checkpoint call failed: %s", e + ) + raise GuardrailRaisedException( + guardrail_name=self.guardrail_name, + message=f"Ovalix guardrail error: {e!s}", + should_wrap_with_default_message=False, + ) from e + + action_type = (resp.get("action_type") or "").lower() + blocking_message = ( + self._get_trackers_corrected_message(resp) + or BLOCKED_BY_OVALIX_FALLBACK_MESSAGE + ) + if action_type == BLOCKED_ACTION_TYPE and is_first_response: + self._block_current_message(blocking_message) + elif action_type == BLOCKED_ACTION_TYPE: + post_guardrail_texts.insert(0, blocking_message) + else: + corrected_text = ( + self._get_trackers_corrected_message(resp) or llm_response + ) + post_guardrail_texts.insert(0, corrected_text) + is_first_response = False + return post_guardrail_texts + + def _block_current_message(self, blocking_message: str) -> None: + """Raise OvalixGuardrailBlockedException with the given message (no default wrapper).""" + raise OvalixGuardrailBlockedException( + guardrail_name=self.guardrail_name, + message=blocking_message, + should_wrap_with_default_message=False, + ) + + def _get_trackers_corrected_message(self, resp: dict) -> Optional[str]: + """Extract corrected/blocking message content from Tracker checkpoint response.""" + modified = resp.get("modified_data") + if isinstance(modified, dict) and "content" in modified: + return modified["content"] + return None + + @staticmethod + def get_config_model() -> Optional[Type["GuardrailConfigModel"]]: + from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( + OvalixGuardrailConfigModel, + ) + + return OvalixGuardrailConfigModel diff --git a/litellm/types/guardrails.py b/litellm/types/guardrails.py index 0430c570e14d..4fea1d944344 100644 --- a/litellm/types/guardrails.py +++ b/litellm/types/guardrails.py @@ -23,6 +23,9 @@ from litellm.types.proxy.guardrails.guardrail_hooks.litellm_content_filter import ( ContentFilterCategoryConfig, ) +from litellm.types.proxy.guardrails.guardrail_hooks.ovalix import ( + OvalixGuardrailConfigModel, +) from litellm.types.proxy.guardrails.guardrail_hooks.promptguard import ( PromptGuardConfigModel, ) @@ -93,6 +96,7 @@ class SupportedGuardrailIntegrations(Enum): GENERIC_GUARDRAIL_API = "generic_guardrail_api" QUALIFIRE = "qualifire" CUSTOM_CODE = "custom_code" + OVALIX = "ovalix" MICROSOFT_PURVIEW = "microsoft_purview" SEMANTIC_GUARD = "semantic_guard" MCP_END_USER_PERMISSION = "mcp_end_user_permission" @@ -786,6 +790,7 @@ class LitellmParams( BaseLitellmParams, EnkryptAIGuardrailConfigs, IBMGuardrailsBaseConfigModel, + OvalixGuardrailConfigModel, QualifireGuardrailConfigModel, BlockCodeExecutionGuardrailConfigModel, HiddenlayerGuardrailConfigModel, diff --git a/litellm/types/proxy/guardrails/guardrail_hooks/ovalix.py b/litellm/types/proxy/guardrails/guardrail_hooks/ovalix.py new file mode 100644 index 000000000000..7417d1a00c98 --- /dev/null +++ b/litellm/types/proxy/guardrails/guardrail_hooks/ovalix.py @@ -0,0 +1,37 @@ +"""Pydantic config model for the Ovalix guardrail (Tracker API, application and checkpoint IDs).""" + +from typing import Optional + +from pydantic import Field + +from .base import GuardrailConfigModel + + +class OvalixGuardrailConfigModel(GuardrailConfigModel): + """Configuration parameters for the Ovalix guardrail (pre/post call checkpoints).""" + + tracker_api_base: Optional[str] = Field( + default=None, + description="Base URL for the Ovalix Tracker service.", + ) + tracker_api_key: Optional[str] = Field( + default=None, + description="API key for the Ovalix Tracker service.", + ) + application_id: Optional[str] = Field( + default=None, + description="Application ID for the Ovalix Tracker service.", + ) + pre_checkpoint_id: Optional[str] = Field( + default=None, + description="Pre-checkpoint ID for the Ovalix Tracker service.", + ) + post_checkpoint_id: Optional[str] = Field( + default=None, + description="Post-checkpoint ID for the Ovalix Tracker service.", + ) + + @staticmethod + def ui_friendly_name() -> str: + """Display name for this guardrail in the proxy UI.""" + return "Ovalix Guardrail" diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_ovalix.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_ovalix.py new file mode 100644 index 000000000000..4160a835ca43 --- /dev/null +++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_ovalix.py @@ -0,0 +1,653 @@ +""" +Unit tests for Ovalix guardrail: config resolution and apply_guardrail behavior +with mocked Tracker service responses (allow, anonymize, block). +""" + +import os +from typing import Any, List +from unittest.mock import AsyncMock, MagicMock, patch + +import httpx +import pytest + +from litellm.exceptions import GuardrailRaisedException +from litellm.proxy.guardrails.guardrail_hooks.ovalix.ovalix import ( + OvalixGuardrail, + OvalixGuardrailBlockedException, + OvalixGuardrailMissingSecrets, +) +from litellm.types.utils import GenericGuardrailAPIInputs + +# Example Tracker responses (as returned by the checkpoint API) +TRACKER_RESPONSE_ALLOW = { + "action_type": "allow", + "data_type": "TEXT", + "original_data": {"content": "how are you?"}, + "modified_data": {"content": "how are you?"}, + "alerts": [], +} + +TRACKER_RESPONSE_ANONYMIZE = { + "action_type": "anonymize", + "data_type": "TEXT", + "original_data": {"content": "Hello, my name is David."}, + "modified_data": {"content": "Hello, my name is {Name}. How are you?"}, + "alerts": [ + { + "title": "Sensitive Data Alert", + "subtitle": "We've identified that you were trying to share sensitive information", + "alerts": ["Name:\tDavid\nRedacted to:\t{Name}"], + } + ], +} + +TRACKER_RESPONSE_BLOCK = { + "action_type": "block", + "data_type": "TEXT", + "original_data": {"content": "I am 15 YO"}, + "modified_data": {"content": "This message was blocked by Ovalix"}, + "alerts": [ + { + "title": "Sensitive Data Alert", + "subtitle": "We've identified that you were trying to share sensitive information", + "alerts": ["Age:\t15\nBlocked"], + } + ], +} + + +def _ovalix_env(): + return { + "OVALIX_TRACKER_API_BASE": "https://tracker.test", + "OVALIX_TRACKER_API_KEY": "key", + "OVALIX_APPLICATION_ID": "app-1", + "OVALIX_PRE_CHECKPOINT_ID": "pre-1", + "OVALIX_POST_CHECKPOINT_ID": "post-1", + } + + +def _guardrail_kwargs(): + return { + "guardrail_name": "ovalix-test", + "event_hook": "pre_call", + "default_on": True, + } + + +class TestOvalixGuardrailConfigModel: + """Minimal config model tests: wiring only.""" + + def test_get_config_model_returns_ovalix_config_model(self): + """get_config_model returns OvalixGuardrailConfigModel for proxy/config wiring.""" + config_model = OvalixGuardrail.get_config_model() + assert config_model is not None + assert config_model.__name__ == "OvalixGuardrailConfigModel" + assert config_model.ui_friendly_name() == "Ovalix Guardrail" + + +class TestOvalixGuardrail: + """Behavioral tests with mocked Tracker checkpoint API.""" + + def setup_method(self): + for key in list(os.environ.keys()): + if key.startswith("OVALIX_"): + del os.environ[key] + + def teardown_method(self): + for key in list(os.environ.keys()): + if key.startswith("OVALIX_"): + del os.environ[key] + + @pytest.fixture + def guardrail_with_env(self): + """Guardrail with OVALIX_* env set; cleans up in teardown.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + yield OvalixGuardrail(**_guardrail_kwargs()) + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + def test_initialization_requires_secrets(self): + """Initialization raises when required Tracker/application/checkpoint config is missing.""" + with pytest.raises(OvalixGuardrailMissingSecrets): + OvalixGuardrail( + guardrail_name="ovalix-test", + event_hook="pre_call", + default_on=True, + ) + + def test_initialization_with_explicit_params(self): + """Guardrail initializes with explicit tracker base, key, app and checkpoint IDs.""" + guardrail = OvalixGuardrail( + tracker_api_base="https://tracker.example", + tracker_api_key="secret", + application_id="app-x", + pre_checkpoint_id="pre-x", + post_checkpoint_id="post-x", + **_guardrail_kwargs(), + ) + assert guardrail._tracker_api_base == "https://tracker.example" + assert guardrail._application_id == "app-x" + assert guardrail._pre_checkpoint_id == "pre-x" + assert guardrail._post_checkpoint_id == "post-x" + + def test_initialization_with_env_vars(self): + """Guardrail picks up OVALIX_* env vars when params not passed.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + assert guardrail._tracker_api_base == "https://tracker.test" + assert guardrail._tracker_api_key == "key" + assert guardrail._application_id == "app-1" + assert guardrail._pre_checkpoint_id == "pre-1" + assert guardrail._post_checkpoint_id == "post-1" + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + @pytest.mark.asyncio + async def test_call_checkpoint_sends_correct_payload_and_returns_json(self): + """_call_checkpoint POSTs to tracker with application_id, checkpoint_id, actor, session_id, data.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + mock_response = MagicMock() + mock_response.json.return_value = TRACKER_RESPONSE_ALLOW + mock_response.raise_for_status = MagicMock() + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + mock_post.return_value = mock_response + result = await guardrail._call_checkpoint( + content="hello", + checkpoint_id="pre-1", + actor="a1b2c3d4", + session_id="session-1", + ) + + assert result == TRACKER_RESPONSE_ALLOW + mock_post.assert_called_once() + call_args = mock_post.call_args + assert call_args.args[0] == ( + "https://tracker.test/tracking/custom_application/checkpoint" + ) + body = call_args.kwargs["json"] + assert body["application_id"] == "app-1" + assert body["checkpoint_id"] == "pre-1" + assert body["actor"] == "a1b2c3d4" + assert body["session_id"] == "session-1" + assert body["data_type"] == "TEXT" + assert body["data"] == {"content": "hello"} + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + @pytest.mark.asyncio + async def test_apply_guardrail_request_allow_passes_through(self): + """When Tracker returns allow, apply_guardrail returns inputs with texts set to modified_data content.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + inputs = GenericGuardrailAPIInputs( + structured_messages=[{"role": "user", "content": "how are you?"}], + texts=["how are you?"], + ) + request_data = {} + + mock_response = MagicMock() + mock_response.json.return_value = TRACKER_RESPONSE_ALLOW + mock_response.raise_for_status = MagicMock() + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + mock_post.return_value = mock_response + result = await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="request", + logging_obj=None, + ) + + assert result.get("texts") == ["how are you?"] + assert mock_post.call_count == 1 + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + @pytest.mark.asyncio + async def test_apply_guardrail_request_anonymize_returns_modified_text(self): + """When Tracker returns anonymize, apply_guardrail returns texts with modified_data content.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + inputs = GenericGuardrailAPIInputs( + structured_messages=[ + {"role": "user", "content": "Hello, my name is David."} + ], + texts=["Hello, my name is David."], + ) + request_data = {} + + mock_response = MagicMock() + mock_response.json.return_value = TRACKER_RESPONSE_ANONYMIZE + mock_response.raise_for_status = MagicMock() + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + mock_post.return_value = mock_response + result = await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="request", + logging_obj=None, + ) + + assert result.get("texts") == ["Hello, my name is {Name}. How are you?"] + assert mock_post.call_count == 1 + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + @pytest.mark.asyncio + async def test_apply_guardrail_request_block_raises_with_tracker_message(self): + """When Tracker returns block on the (chronologically) last user message, OvalixGuardrailBlockedException is raised.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + inputs = GenericGuardrailAPIInputs( + structured_messages=[{"role": "user", "content": "I am 15 YO"}], + texts=["I am 15 YO"], + ) + request_data = {} + + mock_response = MagicMock() + mock_response.json.return_value = TRACKER_RESPONSE_BLOCK + mock_response.raise_for_status = MagicMock() + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + mock_post.return_value = mock_response + with pytest.raises(OvalixGuardrailBlockedException) as exc_info: + await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="request", + logging_obj=None, + ) + + assert "This message was blocked by Ovalix" in str(exc_info.value.message) + assert exc_info.value.status_code == 400 + assert mock_post.call_count == 1 + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + @pytest.mark.asyncio + async def test_apply_guardrail_request_block_non_last_replaced_in_texts(self): + """When Tracker returns block on a non-last user message, that message is replaced in texts and no exception is raised.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + inputs = GenericGuardrailAPIInputs( + structured_messages=[ + {"role": "user", "content": "I am 15 YO"}, + {"role": "user", "content": "how are you?"}, + ], + texts=["I am 15 YO", "how are you?"], + ) + request_data = {} + + def side_effect(*args, **kwargs): + body = kwargs.get("json", {}) + content = (body.get("data") or {}).get("content", "") + resp = MagicMock() + if "15" in content: + resp.json.return_value = TRACKER_RESPONSE_BLOCK + else: + resp.json.return_value = TRACKER_RESPONSE_ALLOW + resp.raise_for_status = MagicMock() + return resp + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + mock_post.side_effect = side_effect + result = await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="request", + logging_obj=None, + ) + + assert result.get("texts") == [ + "This message was blocked by Ovalix", + "how are you?", + ] + assert mock_post.call_count == 2 + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + @pytest.mark.asyncio + async def test_apply_guardrail_response_allow_returns_inputs(self): + """When input_type is response and Tracker allows, apply_guardrail returns inputs with texts updated from Tracker.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + inputs = GenericGuardrailAPIInputs( + structured_messages=[ + {"role": "assistant", "content": "Safe assistant reply"} + ], + texts=["Safe assistant reply"], + ) + request_data = {} + + mock_response = MagicMock() + mock_response.json.return_value = TRACKER_RESPONSE_ALLOW + mock_response.raise_for_status = MagicMock() + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + mock_post.return_value = mock_response + result = await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="response", + logging_obj=None, + ) + + assert result.get("texts") == ["how are you?"] + assert mock_post.call_count == 1 + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + @pytest.mark.asyncio + async def test_apply_guardrail_response_block_raises(self, guardrail_with_env): + """When Tracker blocks on response, apply_guardrail raises OvalixGuardrailBlockedException.""" + guardrail = guardrail_with_env + inputs = GenericGuardrailAPIInputs( + structured_messages=[{"role": "user", "content": "I am 15 YO"}], + texts=["I am 15 YO"], + ) + request_data = {} + + mock_response = MagicMock() + mock_response.json.return_value = TRACKER_RESPONSE_BLOCK + mock_response.raise_for_status = MagicMock() + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + mock_post.return_value = mock_response + with pytest.raises(OvalixGuardrailBlockedException) as exc_info: + await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="response", + logging_obj=None, + ) + + assert "This message was blocked by Ovalix" in str(exc_info.value.message) + assert exc_info.value.status_code == 400 + assert mock_post.call_count == 1 + + @pytest.mark.asyncio + async def test_apply_guardrail_request_missing_modified_data_uses_original_content( + self, guardrail_with_env + ): + """When Tracker response has no modified_data.content, original content is used.""" + guardrail = guardrail_with_env + inputs = GenericGuardrailAPIInputs( + structured_messages=[{"role": "user", "content": "original text"}], + texts=["original text"], + ) + request_data = {} + + mock_response = MagicMock() + mock_response.json.return_value = { + "action_type": "allow", + "data_type": "TEXT", + "original_data": {"content": "original text"}, + "modified_data": {}, + "alerts": [], + } + mock_response.raise_for_status = MagicMock() + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + mock_post.return_value = mock_response + result = await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="request", + logging_obj=None, + ) + + assert result.get("texts") == ["original text"] + assert mock_post.call_count == 1 + + @pytest.mark.asyncio + async def test_apply_guardrail_tracker_http_error_raises_guardrail_exception( + self, guardrail_with_env + ): + """When Tracker returns HTTP error (e.g. 400), GuardrailRaisedException is raised.""" + guardrail = guardrail_with_env + inputs = GenericGuardrailAPIInputs( + structured_messages=[{"role": "user", "content": "hello"}], + texts=["hello"], + ) + request_data = {} + + mock_response = MagicMock() + mock_response.raise_for_status.side_effect = httpx.HTTPStatusError( + "Bad Request", + request=MagicMock(), + response=MagicMock(status_code=400), + ) + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + mock_post.return_value = mock_response + with pytest.raises(GuardrailRaisedException): + await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="request", + logging_obj=None, + ) + + assert mock_post.call_count == 1 + + @pytest.mark.asyncio + async def test_apply_guardrail_checkpoint_error_raises_guardrail_exception(self): + """When Tracker checkpoint call fails, GuardrailRaisedException is raised.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + inputs = GenericGuardrailAPIInputs( + structured_messages=[{"role": "user", "content": "hello"}], + texts=["hello"], + ) + request_data = {} + + with patch.object( + guardrail._async_handler, + "post", + new_callable=AsyncMock, + side_effect=httpx.ConnectError("Connection refused"), + ): + with pytest.raises(GuardrailRaisedException): + await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="request", + logging_obj=None, + ) + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + @pytest.mark.asyncio + async def test_apply_guardrail_request_empty_messages_returns_inputs(self): + """When request has no messages, apply_guardrail returns inputs without calling Tracker.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + inputs = GenericGuardrailAPIInputs(structured_messages=[], texts=[]) + request_data = {} + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + result = await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="request", + logging_obj=None, + ) + + assert result == inputs + mock_post.assert_not_called() + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + def test_get_actor_from_metadata(self): + """Actor is taken from metadata.user_api_key_user_email or user_api_key_user_id.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + assert ( + guardrail._get_actor( + {"metadata": {"user_api_key_user_email": "a@b.com"}} + ) + == "a@b.com" + ) + assert ( + guardrail._get_actor({"metadata": {"user_api_key_user_id": "uid-1"}}) + == "uid-1" + ) + assert ( + guardrail._get_actor( + {"litellm_metadata": {"user_api_key_user_id": "uid-2"}} + ) + == "uid-2" + ) + assert guardrail._get_actor({}) == "unknown" + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k] + + def test_get_actor_prefers_email_over_id(self, guardrail_with_env): + """When both user_api_key_user_email and user_api_key_user_id exist, email is used.""" + guardrail = guardrail_with_env + data = { + "metadata": { + "user_api_key_user_email": "primary@test.com", + "user_api_key_user_id": "uid-99", + } + } + assert guardrail._get_actor(data) == "primary@test.com" + + def test_get_tracker_actor_id_is_hash_not_raw_pii(self, guardrail_with_env): + """Tracker API actor field uses a short hash of _get_actor, not email/user id.""" + guardrail = guardrail_with_env + data = {"metadata": {"user_api_key_user_email": "user@example.com"}} + raw = guardrail._get_actor(data) + hashed = guardrail._get_tracker_actor_id(data) + assert raw == "user@example.com" + assert hashed != raw + assert len(hashed) == 8 + assert all(c in "0123456789abcdef" for c in hashed) + + def test_get_session_id_deterministic_and_includes_app_id(self, guardrail_with_env): + """Session ID is stable for same actor/day and includes application_id.""" + guardrail = guardrail_with_env + data = {"metadata": {"user_api_key_user_id": "user-1"}} + session_id_1 = guardrail._get_session_id(data) + session_id_2 = guardrail._get_session_id(data) + assert session_id_1 == session_id_2 + assert "app-1" in session_id_1 + + def test_block_current_message_raises_ovalix_blocked_exception( + self, guardrail_with_env + ): + """_block_current_message raises OvalixGuardrailBlockedException with status_code 400.""" + guardrail = guardrail_with_env + with pytest.raises(OvalixGuardrailBlockedException) as exc_info: + guardrail._block_current_message("Custom block reason") + assert "Custom block reason" in str(exc_info.value.message) + assert exc_info.value.status_code == 400 + + def test_get_trackers_corrected_message(self, guardrail_with_env): + """_get_trackers_corrected_message returns modified_data.content or None.""" + guardrail = guardrail_with_env + assert ( + guardrail._get_trackers_corrected_message( + {"modified_data": {"content": "corrected text"}} + ) + == "corrected text" + ) + assert guardrail._get_trackers_corrected_message({"modified_data": {}}) is None + assert ( + guardrail._get_trackers_corrected_message({"modified_data": "not-a-dict"}) + is None + ) + + @pytest.mark.asyncio + async def test_apply_guardrail_response_no_texts_returns_unchanged(self): + """When input_type is response and inputs have no texts, apply_guardrail returns inputs without calling Tracker.""" + for k, v in _ovalix_env().items(): + os.environ[k] = v + try: + guardrail = OvalixGuardrail(**_guardrail_kwargs()) + inputs = GenericGuardrailAPIInputs() + request_data = {} + + with patch.object( + guardrail._async_handler, "post", new_callable=AsyncMock + ) as mock_post: + result = await guardrail.apply_guardrail( + inputs=inputs, + request_data=request_data, + input_type="response", + logging_obj=None, + ) + + assert result == inputs + mock_post.assert_not_called() + finally: + for k in _ovalix_env(): + if k in os.environ: + del os.environ[k]