From c7572132fad0a0ef33b50f8d9b9dda8a8ca1d581 Mon Sep 17 00:00:00 2001 From: CASE-Drakon <268336291+CASE-Drakon@users.noreply.github.com> Date: Fri, 16 Oct 2026 12:30:42 +0100 Subject: [PATCH] fix(langchain): stop the run on BLOCK and scan bare LLM and chat prompts --- .github/workflows/test.yml | 2 +- CHANGELOG.md | 12 + README.md | 33 ++- examples/langchain_callback.py | 50 ++-- src/shieldcortex/integrations/langchain.py | 270 ++++++++++++++------- tests/integrations/test_langchain.py | 176 ++++++++++++++ 6 files changed, 423 insertions(+), 120 deletions(-) create mode 100644 tests/integrations/test_langchain.py diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 3ddda90..f623005 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -18,7 +18,7 @@ jobs: with: python-version: ${{ matrix.python-version }} - name: Install dependencies - run: pip install -e ".[dev]" + run: pip install -e ".[dev,langchain]" - name: Lint run: ruff check src/ - name: Type check diff --git a/CHANGELOG.md b/CHANGELOG.md index e849cca..ed76b7d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## [Unreleased] + +### Fixed + +- LangChain async blocks now propagate when `raise_on_block=True`. +- Bare LLM and chat model inputs are scanned by their start callbacks. + +### Added + +- `ShieldCortexSyncCallbackHandler` for synchronous LangChain calls and + `ContentBlockedError` for catching blocked content with its scan result. + ## 0.2.0 — 2026-08-11 SDK lockstep release: the Python SDK now covers the full customer surface diff --git a/README.md b/README.md index 8109bb2..80fa2e9 100644 --- a/README.md +++ b/README.md @@ -100,19 +100,38 @@ except MemoryBlockedError as e: ## LangChain Integration -Automatically scan all LLM inputs and outputs as they flow through your chain — no changes to your existing code: +The callbacks scan chain inputs, LLM prompts, text in chat messages, tool inputs, +LLM outputs, and string tool outputs. Use the async handler for `ainvoke` and +`astream`, or the sync handler for `invoke`: ```python -from shieldcortex import AsyncShieldCortex -from shieldcortex.integrations.langchain import ShieldCortexCallbackHandler +from langchain_openai import ChatOpenAI # or any LangChain chat model / LLM +from shieldcortex import AsyncShieldCortex, ShieldCortex +from shieldcortex.integrations.langchain import ( + ContentBlockedError, + ShieldCortexCallbackHandler, + ShieldCortexSyncCallbackHandler, +) -client = AsyncShieldCortex(api_key="sc_live_...") -handler = ShieldCortexCallbackHandler(client, raise_on_block=True) +model = ChatOpenAI() -# Scans inputs on chain start, outputs on LLM end, and tool I/O -llm = ChatOpenAI(callbacks=[handler]) +async with AsyncShieldCortex(api_key="sc_live_...") as client: + handler = ShieldCortexCallbackHandler(client, raise_on_block=True) + try: + reply = await model.ainvoke("Hello", config={"callbacks": [handler]}) + except ContentBlockedError as error: # also a ValueError + print(error.result.firewall.reason, error.source_identifier) + +with ShieldCortex(api_key="sc_live_...") as client: + handler = ShieldCortexSyncCallbackHandler(client, raise_on_block=True) + reply = model.invoke("Hello", config={"callbacks": [handler]}) ``` +Only `BLOCK` verdicts act today. With `raise_on_block=True`, a block stops the +run with `ContentBlockedError`; otherwise it logs a warning. Scan API errors +are logged and the run continues. Use the matching handler for the call mode: +LangChain cannot propagate an async handler's block from `invoke`. + ## Audit Logs Every scan is logged. Query your history, export for compliance, or auto-paginate through all entries: diff --git a/examples/langchain_callback.py b/examples/langchain_callback.py index d3669e6..68f3b40 100644 --- a/examples/langchain_callback.py +++ b/examples/langchain_callback.py @@ -1,33 +1,41 @@ -"""LangChain callback handler example. +"""Scan LangChain inputs and outputs with the matching callback handler. -Scans LLM inputs and outputs through ShieldCortex. - - pip install shieldcortex[langchain] +Install with ``pip install shieldcortex[langchain]``. The handlers scan chain +inputs, LLM prompts, text in chat messages, tool inputs, LLM outputs, and +string tool outputs. Only BLOCK verdicts act; scan API errors are logged and +the run continues. """ import asyncio -from shieldcortex import AsyncShieldCortex -from shieldcortex.integrations.langchain import ShieldCortexCallbackHandler +from langchain_core.language_models.fake_chat_models import FakeListChatModel + +from shieldcortex import AsyncShieldCortex, ShieldCortex +from shieldcortex.integrations.langchain import ( + ContentBlockedError, + ShieldCortexCallbackHandler, + ShieldCortexSyncCallbackHandler, +) async def main() -> None: + model = FakeListChatModel(responses=["Hello!"]) + async with AsyncShieldCortex(api_key="sc_live_YOUR_KEY_HERE") as client: - handler = ShieldCortexCallbackHandler( - client, - mode="balanced", - scan_inputs=True, - scan_outputs=True, - raise_on_block=False, # Log warnings instead of raising - ) - - # Use with any LangChain component: - # - # from langchain_openai import ChatOpenAI - # llm = ChatOpenAI(callbacks=[handler]) - # response = await llm.ainvoke("Hello!") - - print(f"Handler ready. Audit IDs so far: {handler.audit_ids}") + handler = ShieldCortexCallbackHandler(client, raise_on_block=True) + try: + print(await model.ainvoke("Hello", config={"callbacks": [handler]})) + except ContentBlockedError as error: # also a ValueError + print(f"Blocked {error.source_identifier}: {error.result.firewall.reason}") + + # For invoke(), use the sync client and handler. The async handler's block + # cannot propagate from a sync call. + with ShieldCortex(api_key="sc_live_YOUR_KEY_HERE") as client: + handler = ShieldCortexSyncCallbackHandler(client, raise_on_block=True) + try: + print(model.invoke("Hello", config={"callbacks": [handler]})) + except ContentBlockedError as error: + print(f"Blocked {error.source_identifier}: {error.result.firewall.reason}") if __name__ == "__main__": diff --git a/src/shieldcortex/integrations/langchain.py b/src/shieldcortex/integrations/langchain.py index 2390282..2275f49 100644 --- a/src/shieldcortex/integrations/langchain.py +++ b/src/shieldcortex/integrations/langchain.py @@ -1,22 +1,12 @@ -"""LangChain integration for ShieldCortex memory security scanning. +"""LangChain callbacks for ShieldCortex scanning. -Provides a callback handler that scans LLM inputs and outputs through -the ShieldCortex defence pipeline. +The async handler is for ``ainvoke``/``astream``; the sync handler is for +``invoke``. They scan chain inputs, LLM prompts, chat message text, tool inputs, +LLM outputs, and string tool outputs. Only ``BLOCK`` verdicts act today. +With ``raise_on_block=True``, a block raises :class:`ContentBlockedError`. +Scan API errors are logged and the run continues. -Install with:: - - pip install shieldcortex[langchain] - -Usage:: - - from shieldcortex import AsyncShieldCortex - from shieldcortex.integrations.langchain import ShieldCortexCallbackHandler - - client = AsyncShieldCortex(api_key="sc_live_...") - handler = ShieldCortexCallbackHandler(client) - - # Pass to any LangChain component - llm = ChatOpenAI(callbacks=[handler]) +Install with ``pip install shieldcortex[langchain]``. """ from __future__ import annotations @@ -24,118 +14,216 @@ import logging from typing import Any, Literal +from shieldcortex.async_client import AsyncShieldCortex +from shieldcortex.client import ShieldCortex from shieldcortex.errors import ShieldCortexError -from shieldcortex.types import ScanConfig, ScanSource +from shieldcortex.types import ScanConfig, ScanResult, ScanSource try: - from langchain_core.callbacks import AsyncCallbackHandler + from langchain_core.callbacks import AsyncCallbackHandler, BaseCallbackHandler + from langchain_core.messages import BaseMessage from langchain_core.outputs import LLMResult except ImportError: raise ImportError( "LangChain is not installed. Install with: pip install shieldcortex[langchain]" ) -from shieldcortex.async_client import AsyncShieldCortex - logger = logging.getLogger("shieldcortex.langchain") +Mode = Literal["strict", "balanced", "permissive"] + +class ContentBlockedError(ValueError): + """A ``BLOCK`` verdict, with the scan result and source identifier.""" -class ShieldCortexCallbackHandler(AsyncCallbackHandler): # type: ignore[misc] - """LangChain async callback handler that scans content through ShieldCortex. + def __init__(self, result: ScanResult, source_identifier: str) -> None: + self.result = result + self.source_identifier = f"langchain:{source_identifier}" + super().__init__(f"ShieldCortex blocked {source_identifier}: {result.firewall.reason}") - Scans user inputs (chain start) and LLM outputs (LLM end) through - the defence pipeline. Optionally raises on blocked content. - Args: - client: An :class:`~shieldcortex.AsyncShieldCortex` instance. - mode: Defence mode — ``"strict"``, ``"balanced"``, or ``"permissive"``. - scan_inputs: Scan user inputs at chain start. - scan_outputs: Scan LLM outputs. - raise_on_block: Raise ``ValueError`` when content is blocked - (default: log a warning). +def _chat_texts(messages: list[list[BaseMessage]]) -> list[str]: + texts: list[str] = [] + for batch in messages: + for message in batch: + content = message.content + if isinstance(content, str): + texts.append(content) + elif isinstance(content, list): + for block in content: + if isinstance(block, str): + texts.append(block) + elif isinstance(block, dict) and block.get("type") == "text": + value = block.get("text") + if isinstance(value, str): + texts.append(value) + return texts + + +def _output_texts(response: LLMResult) -> list[str]: + return [ + generation.text for group in response.generations for generation in group if generation.text + ] + + +class _ScanLogic: + """Shared source construction and verdict handling for both callback types.""" + + mode: Mode + scan_inputs: bool + scan_outputs: bool + raise_on_block: bool + audit_ids: list[int] + + def _configure( + self, mode: Mode, scan_inputs: bool, scan_outputs: bool, raise_on_block: bool + ) -> None: + self.mode = mode + self.scan_inputs = scan_inputs + self.scan_outputs = scan_outputs + self.raise_on_block = raise_on_block + self.audit_ids = [] + + def _scan_options(self, source_identifier: str) -> dict[str, Any]: + return { + "source": ScanSource(type="agent", identifier=f"langchain:{source_identifier}"), + "config": ScanConfig(mode=self.mode), + } + + def _handle_result(self, result: ScanResult, source_identifier: str) -> None: + self.audit_ids.append(result.audit_id) + if result.firewall.result == "BLOCK": + error = ContentBlockedError(result, source_identifier) + if self.raise_on_block: + raise error + logger.warning("%s", error) + + +class ShieldCortexCallbackHandler(_ScanLogic, AsyncCallbackHandler): + """Async LangChain handler for ``ainvoke`` and ``astream``. + + Scans chain inputs, LLM prompts, chat message text, tool inputs, LLM + outputs, and string tool outputs. ``raise_on_block=True`` propagates + :class:`ContentBlockedError` (a ``ValueError``). Only ``BLOCK`` acts; + scan API errors are logged and the run continues. """ def __init__( self, client: AsyncShieldCortex, *, - mode: Literal["strict", "balanced", "permissive"] = "balanced", + mode: Mode = "balanced", scan_inputs: bool = True, scan_outputs: bool = True, raise_on_block: bool = False, ) -> None: self.client = client - self.mode = mode - self.scan_inputs = scan_inputs - self.scan_outputs = scan_outputs - self.raise_on_block = raise_on_block - self.audit_ids: list[int] = [] + self._configure(mode, scan_inputs, scan_outputs, raise_on_block) + self.raise_error = raise_on_block async def on_chain_start( - self, - serialized: dict[str, Any], - inputs: dict[str, Any], - **kwargs: Any, + self, serialized: dict[str, Any], inputs: dict[str, Any], **kwargs: Any ) -> None: - """Scan user inputs at chain start.""" - if not self.scan_inputs: - return - input_text = str(inputs) - await self._scan(input_text, "chain_input") + if self.scan_inputs: + await self._scan(str(inputs), "chain_input") - async def on_llm_end( - self, - response: LLMResult, - **kwargs: Any, + async def on_llm_start( + self, serialized: dict[str, Any], prompts: list[str], **kwargs: Any ) -> None: - """Scan LLM outputs.""" - if not self.scan_outputs: - return - for generation_list in response.generations: - for generation in generation_list: - if hasattr(generation, "text") and generation.text: - await self._scan(generation.text, "llm_output") + if self.scan_inputs: + for prompt in dict.fromkeys(prompts): + await self._scan(prompt, "llm_input") + + async def on_chat_model_start( + self, serialized: dict[str, Any], messages: list[list[BaseMessage]], **kwargs: Any + ) -> None: + if self.scan_inputs: + for content in dict.fromkeys(_chat_texts(messages)): + await self._scan(content, "chat_input") + + async def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: + if self.scan_outputs: + for content in _output_texts(response): + await self._scan(content, "llm_output") async def on_tool_start( - self, - serialized: dict[str, Any], - input_str: str, - **kwargs: Any, + self, serialized: dict[str, Any], input_str: str, **kwargs: Any ) -> None: - """Scan tool inputs.""" if self.scan_inputs: await self._scan(input_str, "tool_input") - async def on_tool_end( - self, - output: Any, - **kwargs: Any, - ) -> None: - """Scan tool outputs.""" + async def on_tool_end(self, output: Any, **kwargs: Any) -> None: if self.scan_outputs and isinstance(output, str): await self._scan(output, "tool_output") async def _scan(self, content: str, source_identifier: str) -> None: - """Internal: scan content and handle the result.""" + if not content: + return + try: + result = await self.client.scan(content, **self._scan_options(source_identifier)) + except ShieldCortexError as exc: + logger.warning("ShieldCortex scan error: %s", exc) + return + self._handle_result(result, source_identifier) + + +class ShieldCortexSyncCallbackHandler(_ScanLogic, BaseCallbackHandler): + """Sync LangChain handler for ``invoke`` with the same scanning options. + + ``raise_on_block=True`` propagates :class:`ContentBlockedError` (a + ``ValueError``). Only ``BLOCK`` acts; scan API errors are logged and the + run continues. + """ + + def __init__( + self, + client: ShieldCortex, + *, + mode: Mode = "balanced", + scan_inputs: bool = True, + scan_outputs: bool = True, + raise_on_block: bool = False, + ) -> None: + self.client = client + self._configure(mode, scan_inputs, scan_outputs, raise_on_block) + self.raise_error = raise_on_block + + def on_chain_start( + self, serialized: dict[str, Any], inputs: dict[str, Any], **kwargs: Any + ) -> None: + if self.scan_inputs: + self._scan(str(inputs), "chain_input") + + def on_llm_start(self, serialized: dict[str, Any], prompts: list[str], **kwargs: Any) -> None: + if self.scan_inputs: + for prompt in dict.fromkeys(prompts): + self._scan(prompt, "llm_input") + + def on_chat_model_start( + self, serialized: dict[str, Any], messages: list[list[BaseMessage]], **kwargs: Any + ) -> None: + if self.scan_inputs: + for content in dict.fromkeys(_chat_texts(messages)): + self._scan(content, "chat_input") + + def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: + if self.scan_outputs: + for content in _output_texts(response): + self._scan(content, "llm_output") + + def on_tool_start(self, serialized: dict[str, Any], input_str: str, **kwargs: Any) -> None: + if self.scan_inputs: + self._scan(input_str, "tool_input") + + def on_tool_end(self, output: Any, **kwargs: Any) -> None: + if self.scan_outputs and isinstance(output, str): + self._scan(output, "tool_output") + + def _scan(self, content: str, source_identifier: str) -> None: + if not content: + return try: - result = await self.client.scan( - content, - source=ScanSource( - type="agent", identifier=f"langchain:{source_identifier}" - ), - config=ScanConfig(mode=self.mode), - ) - self.audit_ids.append(result.audit_id) - - if result.firewall.result == "BLOCK": - msg = ( - f"ShieldCortex blocked {source_identifier}: " - f"{result.firewall.reason}" - ) - if self.raise_on_block: - raise ValueError(msg) - logger.warning(msg) - - except ShieldCortexError as e: - # Don't break the LangChain pipeline on scanning errors - logger.warning("ShieldCortex scan error: %s", e) + result = self.client.scan(content, **self._scan_options(source_identifier)) + except ShieldCortexError as exc: + logger.warning("ShieldCortex scan error: %s", exc) + return + self._handle_result(result, source_identifier) diff --git a/tests/integrations/test_langchain.py b/tests/integrations/test_langchain.py new file mode 100644 index 0000000..9b7b91d --- /dev/null +++ b/tests/integrations/test_langchain.py @@ -0,0 +1,176 @@ +"""Regression tests using real LangChain runnables and mocked scan HTTP calls.""" + +from __future__ import annotations + +import json +import logging + +import httpx +import pytest +import respx +from langchain_core.language_models.fake import FakeListLLM +from langchain_core.language_models.fake_chat_models import FakeListChatModel +from langchain_core.messages import HumanMessage +from langchain_core.runnables import RunnableLambda + +from shieldcortex import AsyncShieldCortex, ShieldCortex +from shieldcortex.integrations import langchain as integration + +ShieldCortexCallbackHandler = integration.ShieldCortexCallbackHandler + + +BASE = "https://api.shieldcortex.ai" +ALLOWED_RESPONSE = { + "allowed": True, + "firewall": { + "result": "ALLOW", + "reason": "OK", + "threatIndicators": [], + "anomalyScore": 0.01, + "blockedPatterns": [], + }, + "sensitivity": {"level": "PUBLIC", "redactionRequired": False}, + "trust": {"score": 0.95}, + "auditId": 1, +} +BLOCKED_RESPONSE = { + "allowed": False, + "firewall": { + "result": "BLOCK", + "reason": "Credential leak detected", + "threatIndicators": ["credential_leak"], + "anomalyScore": 0.95, + "blockedPatterns": ["AWS_KEY"], + }, + "sensitivity": {"level": "RESTRICTED", "redactionRequired": True}, + "trust": {"score": 0.1}, + "auditId": 2, +} + + +def scan_requests(route: respx.Route) -> list[dict[str, object]]: + return [json.loads(call.request.read()) for call in route.calls] + + +@pytest.mark.asyncio +@respx.mock +async def test_async_block_stops_chat_model() -> None: + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=BLOCKED_RESPONSE) + ) + async with AsyncShieldCortex(api_key="sc_test_abc") as client: + handler = ShieldCortexCallbackHandler(client, raise_on_block=True) + with pytest.raises(integration.ContentBlockedError) as exc_info: + await FakeListChatModel(responses=["hi"]).ainvoke( + "prompt", config={"callbacks": [handler]} + ) + assert isinstance(exc_info.value, ValueError) + assert exc_info.value.result.firewall.result == "BLOCK" + assert exc_info.value.source_identifier == "langchain:chat_input" + assert len(route.calls) == 1 + + +@pytest.mark.asyncio +@respx.mock +async def test_async_block_warns_and_returns(caplog: pytest.LogCaptureFixture) -> None: + respx.post(f"{BASE}/v1/scan").mock(return_value=httpx.Response(200, json=BLOCKED_RESPONSE)) + async with AsyncShieldCortex(api_key="sc_test_abc") as client: + handler = ShieldCortexCallbackHandler(client, raise_on_block=False) + with caplog.at_level(logging.WARNING, logger="shieldcortex.langchain"): + result = await FakeListChatModel(responses=["hi"]).ainvoke( + "prompt", config={"callbacks": [handler]} + ) + assert result.content == "hi" + assert "ShieldCortex blocked chat_input" in caplog.text + + +@pytest.mark.asyncio +@respx.mock +async def test_bare_chat_scans_prompt_once() -> None: + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=ALLOWED_RESPONSE) + ) + async with AsyncShieldCortex(api_key="sc_test_abc") as client: + handler = ShieldCortexCallbackHandler(client, scan_outputs=False) + await FakeListChatModel(responses=["hi"]).ainvoke( + "prompt", config={"callbacks": [handler]} + ) + assert [(item["content"], item["source"]["identifier"]) for item in scan_requests(route)] == [ + ("prompt", "langchain:chat_input") + ] + + +@pytest.mark.asyncio +@respx.mock +async def test_bare_llm_scans_prompt() -> None: + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=ALLOWED_RESPONSE) + ) + async with AsyncShieldCortex(api_key="sc_test_abc") as client: + handler = ShieldCortexCallbackHandler(client, scan_outputs=False) + await FakeListLLM(responses=["hi"]).ainvoke("prompt", config={"callbacks": [handler]}) + assert [(item["content"], item["source"]["identifier"]) for item in scan_requests(route)] == [ + ("prompt", "langchain:llm_input") + ] + + +@pytest.mark.asyncio +@respx.mock +async def test_chat_content_blocks_scan_text_only() -> None: + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=ALLOWED_RESPONSE) + ) + async with AsyncShieldCortex(api_key="sc_test_abc") as client: + handler = ShieldCortexCallbackHandler(client, scan_outputs=False) + await FakeListChatModel(responses=["hi"]).ainvoke( + [ + HumanMessage( + content=[ + {"type": "text", "text": "visible"}, + {"type": "image_url", "image_url": "hidden"}, + "plain", + "", + ] + ) + ], + config={"callbacks": [handler]}, + ) + assert [item["content"] for item in scan_requests(route)] == ["visible", "plain"] + + +@pytest.mark.asyncio +@respx.mock +async def test_scan_inputs_false() -> None: + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=ALLOWED_RESPONSE) + ) + async with AsyncShieldCortex(api_key="sc_test_abc") as client: + handler = ShieldCortexCallbackHandler(client, scan_inputs=False) + await FakeListChatModel(responses=["hi"]).ainvoke( + "prompt", config={"callbacks": [handler]} + ) + assert [item["source"]["identifier"] for item in scan_requests(route)] == [ + "langchain:llm_output" + ] + + +@respx.mock +def test_sync_block_stops_model() -> None: + respx.post(f"{BASE}/v1/scan").mock(return_value=httpx.Response(200, json=BLOCKED_RESPONSE)) + with ShieldCortex(api_key="sc_test_abc") as client: + handler = integration.ShieldCortexSyncCallbackHandler(client, raise_on_block=True) + with pytest.raises(integration.ContentBlockedError): + FakeListChatModel(responses=["hi"]).invoke("prompt", config={"callbacks": [handler]}) + + +@pytest.mark.asyncio +@respx.mock +async def test_chain_start_blocks() -> None: + respx.post(f"{BASE}/v1/scan").mock(return_value=httpx.Response(200, json=BLOCKED_RESPONSE)) + async with AsyncShieldCortex(api_key="sc_test_abc") as client: + handler = ShieldCortexCallbackHandler(client, raise_on_block=True) + with pytest.raises(integration.ContentBlockedError) as exc_info: + await RunnableLambda(lambda value: value).ainvoke( + "prompt", config={"callbacks": [handler]} + ) + assert exc_info.value.source_identifier == "langchain:chain_input"