From a7721acd26fa0fe2c2d3fe2605351038502196ef Mon Sep 17 00:00:00 2001 From: TARS Date: Sat, 17 Oct 2026 00:42:36 +0000 Subject: [PATCH 1/2] fix(langchain): opt-in fail-closed and quarantine blocking; scan structured tool outputs (#7) - fail_closed (default False) on both handlers: with raise_on_block=True a ShieldCortexError from a scan raises ContentBlockedError (result=None, original error chained as __cause__). fail_closed=True without raise_on_block=True raises ValueError at construction. - block_on_quarantine (default False): QUARANTINE is handled exactly like BLOCK. - on_tool_end reduces non-string outputs to text via one shared helper (.content string, joined text parts of a content-block list, JSON with str() fallback) and scans them; None and empty reductions are skipped. - Docstrings, README and CHANGELOG updated; defaults unchanged for API errors and QUARANTINE. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 24 +++ README.md | 35 +++- src/shieldcortex/integrations/langchain.py | 143 ++++++++++--- tests/integrations/test_langchain.py | 229 ++++++++++++++++++++- 4 files changed, 395 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5fc3c3a..3557a6f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,30 @@ ## [Unreleased] +Defaults are unchanged for API errors and QUARANTINE: a `ShieldCortexError` +from a scan is still logged and skipped, and QUARANTINE still does not act, +unless you opt in with the new options below. + +### Added + +- LangChain handlers: `fail_closed` (default `False`). With + `raise_on_block=True`, a `ShieldCortexError` from a scan (401, 429, 5xx, + timeout, and every other API error) raises `ContentBlockedError` with + `result=None` and the original error as `__cause__`, so the run stops. + `fail_closed=True` without `raise_on_block=True` raises `ValueError` at + construction. `ContentBlockedError.result` is now typed `ScanResult | None`. +- LangChain handlers: `block_on_quarantine` (default `False`). When `True`, + a QUARANTINE verdict is treated exactly like BLOCK. + +### Fixed + +- LangChain `on_tool_end` now scans structured tool outputs (ToolMessage + content, content blocks, dicts) instead of skipping them. Non-string + outputs are reduced to text (`.content` string, joined text parts of a + content-block list, or JSON with a `str()` fallback); `None` and outputs + that reduce to empty text are not scanned. String outputs are scanned as + before. + ## 0.4.0 — 2026-10-16 Minor release: the LangChain integration now stops the run on BLOCK, scans diff --git a/README.md b/README.md index d76b550..75e8b13 100644 --- a/README.md +++ b/README.md @@ -114,7 +114,7 @@ except MemoryBlockedError as e: ## LangChain Integration 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 +LLM outputs, and tool outputs. Use the async handler for `ainvoke` and `astream`, or the sync handler for `invoke`: ```python @@ -140,8 +140,8 @@ with ShieldCortex(api_key="sc_live_...") as client: 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. Use the matching +By default only `BLOCK` verdicts act. With `raise_on_block=True`, a block stops +the run with `ContentBlockedError`; otherwise it logs a warning. Use the matching handler for the call mode: LangChain cannot propagate an async handler's block from `invoke`. @@ -153,10 +153,31 @@ from `invoke`. output block stops the run after delivery and cannot prevent exposure. Buffer the stream yourself if blocked output must never be shown. Input scans still run before the model starts. -- **Scan errors:** a `ShieldCortexError` from the scan call (HTTP error, - timeout) is logged and that scan is skipped. Other exceptions, such as - connection errors, are not caught: with `raise_on_block=True` they stop the - run, otherwise LangChain logs them. +- **Tool outputs** are reduced to text before scanning: strings as is; objects + with string `.content` (such as `ToolMessage`) by that content; a list + `.content` by its string items and the string `text` of its dict items, + joined by newlines; anything else as JSON (`default=str`), falling back to + `str()`. `None` and non-string outputs that reduce to empty text are not + scanned. With the async handler, give tools a coroutine: for sync-only tools + under `ainvoke`, LangChain logs and swallows the async handler's block. +- **Scan errors:** by default a `ShieldCortexError` from the scan call (any + HTTP error such as 401, 429 or 5xx, or a timeout) is logged and that scan is + skipped, so the content passes. Other exceptions, such as connection errors, + are not caught: with `raise_on_block=True` they stop the run, otherwise + LangChain logs them. + +Two opt-in options, available on both handlers: + +| Option | Default | Effect | +|---|---|---| +| `fail_closed` | `False` | With `raise_on_block=True`, a `ShieldCortexError` from a scan raises `ContentBlockedError` instead of being logged and skipped. `error.result` is `None` and `error.__cause__` is the original error. Requires `raise_on_block=True`; otherwise the constructor raises `ValueError`. | +| `block_on_quarantine` | `False` | Treat `QUARANTINE` verdicts exactly like `BLOCK` (warn, or raise with `raise_on_block=True`). | + +```python +handler = ShieldCortexSyncCallbackHandler( + client, raise_on_block=True, fail_closed=True, block_on_quarantine=True +) +``` ## Audit Logs diff --git a/src/shieldcortex/integrations/langchain.py b/src/shieldcortex/integrations/langchain.py index d71eb79..e67c839 100644 --- a/src/shieldcortex/integrations/langchain.py +++ b/src/shieldcortex/integrations/langchain.py @@ -2,25 +2,42 @@ 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. Chat message text means string content, -string blocks, and dict blocks whose ``text`` is a string and whose ``type`` is -``"text"`` or absent. Only ``BLOCK`` verdicts act today. With -``raise_on_block=True``, a block raises :class:`ContentBlockedError`. +LLM outputs, and tool outputs. Chat message text means string content, string +blocks, and dict blocks whose ``text`` is a string and whose ``type`` is +``"text"`` or absent. + +Tool outputs are reduced to text before scanning: a string is scanned as is; +an object with string ``.content`` (such as a ``ToolMessage``) is scanned by +that content; a list ``.content`` is scanned as its string items and the +string ``text`` of its dict items, joined by newlines; anything else is +JSON-encoded (``default=str``), falling back to ``str()``. ``None``, and +non-string outputs that reduce to empty text, are not scanned. + +By default only ``BLOCK`` verdicts act. ``block_on_quarantine=True`` treats +``QUARANTINE`` the same way. With ``raise_on_block=True``, a block raises +:class:`ContentBlockedError`; otherwise it is logged as a warning. LLM output is scanned in ``on_llm_end``, after the model finishes. With ``stream``/``astream`` every chunk has already reached the caller by then, so an output block stops the run after delivery and cannot prevent exposure. -A :class:`~shieldcortex.errors.ShieldCortexError` from the scan call (HTTP -error, timeout) is logged and that scan is skipped. Other exceptions, such as -connection errors, are not caught: with ``raise_on_block=True`` they stop the -run, otherwise LangChain logs them. +By default a :class:`~shieldcortex.errors.ShieldCortexError` from the scan +call (any HTTP error such as 401, 429 or 5xx, or a timeout) is logged and that +scan is skipped, so the content passes (fail open). With ``fail_closed=True`` +and ``raise_on_block=True``, such an error instead raises +:class:`ContentBlockedError` with ``result=None`` and the original error as +``__cause__``, stopping the run. ``fail_closed=True`` without +``raise_on_block=True`` raises ``ValueError`` at construction, because there +would be nothing to stop the run with. Other exceptions, such as connection +errors, are not caught: with ``raise_on_block=True`` they stop the run, +otherwise LangChain logs them. Install with ``pip install shieldcortex[langchain]``. """ from __future__ import annotations +import json import logging from typing import Any, Literal @@ -43,12 +60,22 @@ class ContentBlockedError(ValueError): - """A ``BLOCK`` verdict, with the scan result and source identifier.""" + """Blocked content, with the scan result and source identifier. + + Raised for a ``BLOCK`` verdict (or ``QUARANTINE`` with + ``block_on_quarantine=True``). With ``fail_closed=True`` it is also raised + when the scan itself fails: then ``result`` is ``None`` and the + :class:`~shieldcortex.errors.ShieldCortexError` is the ``__cause__``. + """ - def __init__(self, result: ScanResult, source_identifier: str) -> None: + def __init__( + self, result: ScanResult | None, source_identifier: str, reason: str | None = None + ) -> None: self.result = result self.source_identifier = f"langchain:{source_identifier}" - super().__init__(f"ShieldCortex blocked {source_identifier}: {result.firewall.reason}") + if reason is None: + reason = result.firewall.reason if result is not None else "scan failed" + super().__init__(f"ShieldCortex blocked {source_identifier}: {reason}") def _chat_texts(messages: list[list[BaseMessage]]) -> list[str]: @@ -72,6 +99,31 @@ def _chat_texts(messages: list[list[BaseMessage]]) -> list[str]: return texts +def _tool_output_text(output: Any) -> str | None: + """Reduce a tool output to the text to scan, or ``None`` to skip it.""" + if output is None: + return None + if isinstance(output, str): + return output + content = getattr(output, "content", None) + if isinstance(content, str): + text = content + elif isinstance(content, list): + parts: list[str] = [] + for block in content: + if isinstance(block, str): + parts.append(block) + elif isinstance(block, dict) and isinstance(block.get("text"), str): + parts.append(block["text"]) + text = "\n".join(part for part in parts if part) + else: + try: + text = json.dumps(output, default=str) + except (TypeError, ValueError): + text = str(output) + return text or None + + def _output_texts(response: LLMResult) -> list[str]: return [ generation.text for group in response.generations for generation in group if generation.text @@ -85,15 +137,27 @@ class _ScanLogic: scan_inputs: bool scan_outputs: bool raise_on_block: bool + fail_closed: bool + block_on_quarantine: bool audit_ids: list[int] def _configure( - self, mode: Mode, scan_inputs: bool, scan_outputs: bool, raise_on_block: bool + self, + mode: Mode, + scan_inputs: bool, + scan_outputs: bool, + raise_on_block: bool, + fail_closed: bool = False, + block_on_quarantine: bool = False, ) -> None: + if fail_closed and not raise_on_block: + raise ValueError("fail_closed=True requires raise_on_block=True") self.mode = mode self.scan_inputs = scan_inputs self.scan_outputs = scan_outputs self.raise_on_block = raise_on_block + self.fail_closed = fail_closed + self.block_on_quarantine = block_on_quarantine self.audit_ids = [] def _scan_options(self, source_identifier: str) -> dict[str, Any]: @@ -102,9 +166,15 @@ def _scan_options(self, source_identifier: str) -> dict[str, Any]: "config": ScanConfig(mode=self.mode), } + def _handle_error(self, exc: ShieldCortexError, source_identifier: str) -> None: + if self.fail_closed: + raise ContentBlockedError(None, source_identifier, f"scan failed: {exc}") from exc + logger.warning("ShieldCortex scan error: %s", exc) + def _handle_result(self, result: ScanResult, source_identifier: str) -> None: self.audit_ids.append(result.audit_id) - if result.firewall.result == "BLOCK": + verdict = result.firewall.result + if verdict == "BLOCK" or (verdict == "QUARANTINE" and self.block_on_quarantine): error = ContentBlockedError(result, source_identifier) if self.raise_on_block: raise error @@ -115,10 +185,13 @@ 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. - Streamed output is scanned after delivery; see the module docstring for - that and for which scan errors are logged. + outputs, and tool outputs (structured outputs are reduced to text). + ``raise_on_block=True`` propagates :class:`ContentBlockedError` (a + ``ValueError``). ``BLOCK`` acts; ``block_on_quarantine=True`` (default + ``False``) makes ``QUARANTINE`` act too. ``fail_closed=True`` (default + ``False``, requires ``raise_on_block=True``) raises on scan errors instead + of logging and skipping them. Streamed output is scanned after delivery; + see the module docstring for that and for the reduction rules. """ def __init__( @@ -129,9 +202,13 @@ def __init__( scan_inputs: bool = True, scan_outputs: bool = True, raise_on_block: bool = False, + fail_closed: bool = False, + block_on_quarantine: bool = False, ) -> None: self.client = client - self._configure(mode, scan_inputs, scan_outputs, raise_on_block) + self._configure( + mode, scan_inputs, scan_outputs, raise_on_block, fail_closed, block_on_quarantine + ) self.raise_error = raise_on_block async def on_chain_start( @@ -166,14 +243,16 @@ async def on_tool_start( await self._scan(input_str, "tool_input") 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") + if self.scan_outputs: + text = _tool_output_text(output) + if text is not None: + await self._scan(text, "tool_output") async def _scan(self, content: str, source_identifier: str) -> None: try: result = await self.client.scan(content, **self._scan_options(source_identifier)) except ShieldCortexError as exc: - logger.warning("ShieldCortex scan error: %s", exc) + self._handle_error(exc, source_identifier) return self._handle_result(result, source_identifier) @@ -182,9 +261,11 @@ 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. Streamed output is scanned after - delivery; see the module docstring for that and for which scan errors - are logged. + ``ValueError``). ``BLOCK`` acts; ``block_on_quarantine=True`` (default + ``False``) makes ``QUARANTINE`` act too. ``fail_closed=True`` (default + ``False``, requires ``raise_on_block=True``) raises on scan errors instead + of logging and skipping them. Streamed output is scanned after delivery; + see the module docstring for that and for the reduction rules. """ def __init__( @@ -195,9 +276,13 @@ def __init__( scan_inputs: bool = True, scan_outputs: bool = True, raise_on_block: bool = False, + fail_closed: bool = False, + block_on_quarantine: bool = False, ) -> None: self.client = client - self._configure(mode, scan_inputs, scan_outputs, raise_on_block) + self._configure( + mode, scan_inputs, scan_outputs, raise_on_block, fail_closed, block_on_quarantine + ) self.raise_error = raise_on_block def on_chain_start( @@ -228,13 +313,15 @@ def on_tool_start(self, serialized: dict[str, Any], input_str: str, **kwargs: An 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") + if self.scan_outputs: + text = _tool_output_text(output) + if text is not None: + self._scan(text, "tool_output") def _scan(self, content: str, source_identifier: str) -> None: try: result = self.client.scan(content, **self._scan_options(source_identifier)) except ShieldCortexError as exc: - logger.warning("ShieldCortex scan error: %s", exc) + self._handle_error(exc, source_identifier) return self._handle_result(result, source_identifier) diff --git a/tests/integrations/test_langchain.py b/tests/integrations/test_langchain.py index 9a79708..c2259d6 100644 --- a/tests/integrations/test_langchain.py +++ b/tests/integrations/test_langchain.py @@ -4,16 +4,19 @@ import json import logging +from typing import Any 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.messages import HumanMessage, ToolMessage from langchain_core.runnables import RunnableLambda +from langchain_core.tools import StructuredTool from shieldcortex import AsyncShieldCortex, ShieldCortex +from shieldcortex.errors import AuthError, ShieldCortexError from shieldcortex.integrations import langchain as integration ShieldCortexCallbackHandler = integration.ShieldCortexCallbackHandler @@ -238,3 +241,227 @@ async def test_empty_llm_prompt_is_skipped() -> None: handler = ShieldCortexCallbackHandler(client, scan_outputs=False) await FakeListLLM(responses=["hi"]).ainvoke("", config={"callbacks": [handler]}) assert scan_requests(route) == [] + + +# --- fail_closed, block_on_quarantine and structured tool outputs (#7) --- + +QUARANTINE_RESPONSE = { + **BLOCKED_RESPONSE, + "firewall": {**BLOCKED_RESPONSE["firewall"], "result": "QUARANTINE"}, # type: ignore[dict-item] + "auditId": 3, +} +SCAN_FAILURES = { + "401": httpx.Response(401, json={"error": "bad key"}), + "503": httpx.Response(503, text="unavailable"), + "timeout": httpx.ReadTimeout("timed out"), +} + + +async def invoke(is_sync: bool, runnable: Any, value: Any, **options: Any) -> Any: + """Invoke ``runnable`` with the sync or async handler built from ``options``.""" + if is_sync: + with ShieldCortex(api_key="sc_test_abc") as client: + handler = integration.ShieldCortexSyncCallbackHandler(client, **options) + return runnable.invoke(value, config={"callbacks": [handler]}) + async with AsyncShieldCortex(api_key="sc_test_abc") as aclient: + ahandler = ShieldCortexCallbackHandler(aclient, **options) + return await runnable.ainvoke(value, config={"callbacks": [ahandler]}) + + +def mock_failure(name: str) -> respx.Route: + failure = SCAN_FAILURES[name] + route = respx.post(f"{BASE}/v1/scan") + if isinstance(failure, Exception): + return route.mock(side_effect=failure) + return route.mock(return_value=failure) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_sync", [False, True], ids=["async", "sync"]) +@pytest.mark.parametrize("failure", list(SCAN_FAILURES)) +@respx.mock +async def test_fail_closed_raises_on_scan_error(is_sync: bool, failure: str) -> None: + route = mock_failure(failure) + with pytest.raises(integration.ContentBlockedError) as exc_info: + await invoke( + is_sync, + FakeListChatModel(responses=["hi"]), + "prompt", + raise_on_block=True, + fail_closed=True, + ) + error = exc_info.value + assert isinstance(error.__cause__, ShieldCortexError) + assert error.result is None + assert error.source_identifier == "langchain:chat_input" + assert "scan failed" in str(error) + if failure == "401": + assert isinstance(error.__cause__, AuthError) + elif failure == "503": + assert error.__cause__.status_code == 503 + assert len(route.calls) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_sync", [False, True], ids=["async", "sync"]) +@pytest.mark.parametrize("failure", list(SCAN_FAILURES)) +@respx.mock +async def test_scan_error_fails_open_by_default( + is_sync: bool, failure: str, caplog: pytest.LogCaptureFixture +) -> None: + route = mock_failure(failure) + with caplog.at_level(logging.WARNING, logger="shieldcortex.langchain"): + result = await invoke( + is_sync, FakeListChatModel(responses=["hi"]), "prompt", raise_on_block=True + ) + assert result.content == "hi" + assert "ShieldCortex scan error" in caplog.text + assert [item["source"]["identifier"] for item in scan_requests(route)] == [ + "langchain:chat_input", + "langchain:llm_output", + ] + + +@pytest.mark.parametrize( + "handler_class", + [ShieldCortexCallbackHandler, integration.ShieldCortexSyncCallbackHandler], + ids=["async", "sync"], +) +def test_fail_closed_requires_raise_on_block(handler_class: Any) -> None: + with pytest.raises(ValueError, match="fail_closed=True requires raise_on_block=True"): + handler_class(object(), fail_closed=True) + with pytest.raises(ValueError): + handler_class(object(), fail_closed=True, raise_on_block=False) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_sync", [False, True], ids=["async", "sync"]) +@respx.mock +async def test_block_on_quarantine_raises(is_sync: bool) -> None: + respx.post(f"{BASE}/v1/scan").mock(return_value=httpx.Response(200, json=QUARANTINE_RESPONSE)) + with pytest.raises(integration.ContentBlockedError) as exc_info: + await invoke( + is_sync, + FakeListChatModel(responses=["hi"]), + "prompt", + raise_on_block=True, + block_on_quarantine=True, + ) + assert exc_info.value.result is not None + assert exc_info.value.result.firewall.result == "QUARANTINE" + assert exc_info.value.__cause__ is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_sync", [False, True], ids=["async", "sync"]) +@respx.mock +async def test_quarantine_does_not_raise_by_default(is_sync: bool) -> None: + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=QUARANTINE_RESPONSE) + ) + result = await invoke( + is_sync, FakeListChatModel(responses=["hi"]), "prompt", raise_on_block=True + ) + assert result.content == "hi" + assert len(route.calls) == 2 + + +def make_tool(output: Any) -> StructuredTool: + # A coroutine is needed for ``ainvoke`` to fire async callbacks on the event + # loop. For sync-only tools LangChain runs async handlers through a helper + # that logs and swallows their exceptions. + def lookup(query: str) -> Any: + return output + + async def alookup(query: str) -> Any: + return output + + return StructuredTool.from_function( + lookup, coroutine=alookup, name="lookup", description="lookup" + ) + + +TOOL_CALL = {"name": "lookup", "args": {"query": "q"}, "id": "call-1", "type": "tool_call"} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_sync", [False, True], ids=["async", "sync"]) +@respx.mock +async def test_tool_message_output_is_scanned_and_blocks(is_sync: bool) -> None: + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=BLOCKED_RESPONSE) + ) + with pytest.raises(integration.ContentBlockedError) as exc_info: + await invoke( + is_sync, + make_tool("AKIA-secret"), + TOOL_CALL, + raise_on_block=True, + scan_inputs=False, + ) + assert exc_info.value.source_identifier == "langchain:tool_output" + assert [item["content"] for item in scan_requests(route)] == ["AKIA-secret"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_sync", [False, True], ids=["async", "sync"]) +@respx.mock +async def test_tool_message_content_blocks_are_joined(is_sync: bool) -> None: + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=ALLOWED_RESPONSE) + ) + blocks = [{"type": "text", "text": "first"}, "second", {"type": "image", "url": "x"}] + result = await invoke(is_sync, make_tool(blocks), TOOL_CALL, scan_inputs=False) + assert isinstance(result, ToolMessage) + assert [item["content"] for item in scan_requests(route)] == ["first\nsecond"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_sync", [False, True], ids=["async", "sync"]) +@respx.mock +async def test_dict_tool_output_is_scanned_as_json(is_sync: bool) -> None: + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=BLOCKED_RESPONSE) + ) + with pytest.raises(integration.ContentBlockedError): + await invoke( + is_sync, + make_tool({"key": "AKIA-secret", "n": 1}), + {"query": "q"}, + raise_on_block=True, + scan_inputs=False, + ) + assert [item["content"] for item in scan_requests(route)] == [ + json.dumps({"key": "AKIA-secret", "n": 1}) + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_sync", [False, True], ids=["async", "sync"]) +@respx.mock +async def test_none_tool_output_is_not_scanned(is_sync: bool) -> None: + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=BLOCKED_RESPONSE) + ) + await invoke( + is_sync, make_tool(None), {"query": "q"}, raise_on_block=True, scan_inputs=False + ) + assert len(route.calls) == 0 + + +def test_tool_output_text_reduction() -> None: + reduce = integration._tool_output_text + + class Unencodable: + def __str__(self) -> str: + return "unencodable" + + circular: list[Any] = [] + circular.append(circular) + assert reduce(None) is None + assert reduce("") == "" + assert reduce("plain") == "plain" + assert reduce(ToolMessage(content="", tool_call_id="c")) is None + assert reduce(ToolMessage(content=[{"type": "image", "url": "x"}], tool_call_id="c")) is None + assert reduce({"a": Unencodable()}) == '{"a": "unencodable"}' + assert reduce(circular) == str(circular) From 3a22734c74eb9826d401521854305af0f136c3a9 Mon Sep 17 00:00:00 2001 From: TARS Date: Sat, 17 Oct 2026 01:25:09 +0000 Subject: [PATCH 2/2] docs(langchain): narrow fail-closed contract for sync-only tools under ainvoke; add regression matrix B1: with the async handler, LangChain runs a sync-only tool's ainvoke through invoke in a worker thread and logs and swallows every exception the async handler raises (callbacks/manager.py _run_coros ignores raise_error). Neither BLOCK nor fail_closed scan-error raises stop that tool. Enforcing this from the handler would mean patching LangChain, so the contract is narrowed in the module docstring, README and CHANGELOG (new "Known limitation"), with the workarounds: give the tool a coroutine, or pass the sync handler with a sync client, whose exceptions propagate on that route. Tests: - Real sync-only StructuredTool (no coroutine) under ainvoke: the async handler with fail_closed lets the tool run and return on BLOCK and 503, for tool_input and tool_output (characterises LangChain's behaviour so a change is noticed); the sync handler raises, and on tool_input the tool never runs. - N2: ToolMessage list content with a non-text dict block is dropped, not JSON-encoded; a bare list return is stringified by LangChain and scanned. - N3: fail_closed matrix over chain, LLM, chat and tool input/output hooks x 401/429/503/timeout/base ShieldCortexError in sync and async handlers, plus raw httpx.ConnectError propagating unwrapped. N1: README and CHANGELOG migration note for ContentBlockedError.result being typed ScanResult | None (never None without fail_closed, but type checkers ask callers to narrow). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 24 ++- README.md | 29 +++- src/shieldcortex/integrations/langchain.py | 19 ++- tests/integrations/test_langchain.py | 163 ++++++++++++++++++++- 4 files changed, 221 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e2cb326..11268b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,9 +11,15 @@ unless you opt in with the new options below. - LangChain handlers: `fail_closed` (default `False`). With `raise_on_block=True`, a `ShieldCortexError` from a scan (401, 429, 5xx, timeout, and every other API error) raises `ContentBlockedError` with - `result=None` and the original error as `__cause__`, so the run stops. - `fail_closed=True` without `raise_on_block=True` raises `ValueError` at - construction. `ContentBlockedError.result` is now typed `ScanResult | None`. + `result=None` and the original error as `__cause__`, so the run stops + (except for sync-only tools under `ainvoke` with the async handler; see + Known limitation). `fail_closed=True` without `raise_on_block=True` raises `ValueError` at + construction. +- `ContentBlockedError.result` is now typed `ScanResult | None`. It is only + `None` with `fail_closed=True`, so default-option callers never see `None` + at runtime, but type checkers will ask them to narrow before reading + `error.result.firewall`: + `if error.result is not None: print(error.result.firewall.reason)`. - LangChain handlers: `block_on_quarantine` (default `False`). When `True`, a QUARANTINE verdict is treated exactly like BLOCK. @@ -22,7 +28,8 @@ unless you opt in with the new options below. - LangChain `on_tool_end` now scans structured tool outputs (ToolMessage content, content blocks, dicts) instead of skipping them. Non-string outputs are reduced to text (`.content` string, joined text parts of a - content-block list, or JSON with a `str()` fallback); `None` and outputs + content-block list, or JSON with a `str()` fallback); non-text blocks in a + content list are dropped, not JSON-encoded; `None` and outputs that reduce to empty text are not scanned. String outputs are scanned as before. - Path parameters (ids, device UUIDs, export manifest ids) are now @@ -30,6 +37,15 @@ unless you opt in with the new options below. non-ASCII characters can no longer change the route. Empty, `.` and `..` values raise `ValueError` before any request is sent. +### Known limitation + +- With the async handler, a sync-only tool (no coroutine) called through + `ainvoke` runs in a worker thread where LangChain logs and swallows every + exception the handler raises. Neither BLOCK verdicts nor `fail_closed` + scan-error raises stop that tool: it runs and `ainvoke` returns its output. + Give the tool an async implementation, or pass the sync handler (with a + sync client) for those calls; its exceptions propagate on that route. + ## 0.4.0 — 2026-10-16 Minor release: the LangChain integration now stops the run on BLOCK, scans diff --git a/README.md b/README.md index 75e8b13..4d65fe8 100644 --- a/README.md +++ b/README.md @@ -157,9 +157,18 @@ from `invoke`. with string `.content` (such as `ToolMessage`) by that content; a list `.content` by its string items and the string `text` of its dict items, joined by newlines; anything else as JSON (`default=str`), falling back to - `str()`. `None` and non-string outputs that reduce to empty text are not - scanned. With the async handler, give tools a coroutine: for sync-only tools - under `ainvoke`, LangChain logs and swallows the async handler's block. + `str()`. Other blocks in a list `.content`, such as images or dicts without + a string `text` (for example `{"payload": "..."}`), are dropped rather than + JSON-encoded, so their contents are not scanned. `None` and non-string outputs that reduce + to empty text are not scanned. +- **Sync-only tools under `ainvoke`:** LangChain runs a tool that has no + coroutine in a worker thread and logs and swallows every exception the + async handler raises there. Neither a `BLOCK` verdict nor a `fail_closed` + scan error stops that tool: it runs and `ainvoke` returns its output. Give + the tool an async implementation (`coroutine=` on `StructuredTool`, or + `_arun`), or pass the sync handler with a sync client for those calls, + e.g. `await tool.ainvoke(args, config={"callbacks": [sync_handler]})`; its + exceptions do propagate on that route. - **Scan errors:** by default a `ShieldCortexError` from the scan call (any HTTP error such as 401, 429 or 5xx, or a timeout) is logged and that scan is skipped, so the content passes. Other exceptions, such as connection errors, @@ -170,7 +179,7 @@ Two opt-in options, available on both handlers: | Option | Default | Effect | |---|---|---| -| `fail_closed` | `False` | With `raise_on_block=True`, a `ShieldCortexError` from a scan raises `ContentBlockedError` instead of being logged and skipped. `error.result` is `None` and `error.__cause__` is the original error. Requires `raise_on_block=True`; otherwise the constructor raises `ValueError`. | +| `fail_closed` | `False` | With `raise_on_block=True`, a `ShieldCortexError` from a scan raises `ContentBlockedError` instead of being logged and skipped (except for sync-only tools under `ainvoke` with the async handler, see above). `error.result` is `None` and `error.__cause__` is the original error. Requires `raise_on_block=True`; otherwise the constructor raises `ValueError`. | | `block_on_quarantine` | `False` | Treat `QUARANTINE` verdicts exactly like `BLOCK` (warn, or raise with `raise_on_block=True`). | ```python @@ -179,6 +188,18 @@ handler = ShieldCortexSyncCallbackHandler( ) ``` +`ContentBlockedError.result` is typed `ScanResult | None`. Without +`fail_closed` it is never `None` at runtime, but type checkers will still ask +you to narrow it before reading `error.result.firewall`: + +```python +except ContentBlockedError as error: + if error.result is None: # fail_closed: the scan itself failed + print("scan failed:", error.__cause__) + else: + print(error.result.firewall.reason) +``` + ## Audit Logs Every scan is logged. Query your history, export for compliance, or auto-paginate through all entries: diff --git a/src/shieldcortex/integrations/langchain.py b/src/shieldcortex/integrations/langchain.py index e67c839..64ebbc6 100644 --- a/src/shieldcortex/integrations/langchain.py +++ b/src/shieldcortex/integrations/langchain.py @@ -9,9 +9,10 @@ Tool outputs are reduced to text before scanning: a string is scanned as is; an object with string ``.content`` (such as a ``ToolMessage``) is scanned by that content; a list ``.content`` is scanned as its string items and the -string ``text`` of its dict items, joined by newlines; anything else is -JSON-encoded (``default=str``), falling back to ``str()``. ``None``, and -non-string outputs that reduce to empty text, are not scanned. +string ``text`` of its dict items, joined by newlines (other blocks, such as +images or dicts without a string ``text``, are dropped, not JSON-encoded); +anything else is JSON-encoded (``default=str``), falling back to ``str()``. +``None``, and non-string outputs that reduce to empty text, are not scanned. By default only ``BLOCK`` verdicts act. ``block_on_quarantine=True`` treats ``QUARANTINE`` the same way. With ``raise_on_block=True``, a block raises @@ -32,6 +33,13 @@ errors, are not caught: with ``raise_on_block=True`` they stop the run, otherwise LangChain logs them. +Exception: with the async handler, a tool without a coroutine (a sync-only +tool) called through ``ainvoke`` runs in a worker thread, and LangChain logs +and swallows every exception the async handler raises there. Neither a block +nor a ``fail_closed`` scan error stops that tool: it runs and its output is +returned. Give such tools a coroutine, or attach the sync handler (with a +sync client) to those calls; its exceptions do propagate on that route. + Install with ``pip install shieldcortex[langchain]``. """ @@ -190,8 +198,9 @@ class ShieldCortexCallbackHandler(_ScanLogic, AsyncCallbackHandler): ``ValueError``). ``BLOCK`` acts; ``block_on_quarantine=True`` (default ``False``) makes ``QUARANTINE`` act too. ``fail_closed=True`` (default ``False``, requires ``raise_on_block=True``) raises on scan errors instead - of logging and skipping them. Streamed output is scanned after delivery; - see the module docstring for that and for the reduction rules. + of logging and skipping them. Streamed output is scanned after delivery, + and nothing this handler raises stops a sync-only tool under ``ainvoke``; + see the module docstring for both and for the reduction rules. """ def __init__( diff --git a/tests/integrations/test_langchain.py b/tests/integrations/test_langchain.py index c2259d6..c18ec06 100644 --- a/tests/integrations/test_langchain.py +++ b/tests/integrations/test_langchain.py @@ -369,7 +369,7 @@ async def test_quarantine_does_not_raise_by_default(is_sync: bool) -> None: def make_tool(output: Any) -> StructuredTool: # A coroutine is needed for ``ainvoke`` to fire async callbacks on the event # loop. For sync-only tools LangChain runs async handlers through a helper - # that logs and swallows their exceptions. + # that logs and swallows their exceptions; see the sync-only tests below. def lookup(query: str) -> Any: return output @@ -465,3 +465,164 @@ def __str__(self) -> str: assert reduce(ToolMessage(content=[{"type": "image", "url": "x"}], tool_call_id="c")) is None assert reduce({"a": Unencodable()}) == '{"a": "unencodable"}' assert reduce(circular) == str(circular) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_sync", [False, True], ids=["async", "sync"]) +@respx.mock +async def test_tool_message_non_text_dict_block_is_dropped(is_sync: bool) -> None: + # In a ToolMessage's list content only string blocks and string ``text`` + # fields are scanned; other dict blocks are dropped, not JSON-encoded. + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=BLOCKED_RESPONSE) + ) + message = ToolMessage(content=[{"payload": "AKIA-secret"}], tool_call_id="call-1") + result = await invoke( + is_sync, make_tool(message), TOOL_CALL, raise_on_block=True, scan_inputs=False + ) + assert result.content == [{"payload": "AKIA-secret"}] + assert len(route.calls) == 0 + route.mock(return_value=httpx.Response(200, json=ALLOWED_RESPONSE)) + mixed = ToolMessage( + content=[{"payload": "AKIA-secret"}, {"type": "text", "text": "visible"}], + tool_call_id="call-1", + ) + await invoke(is_sync, make_tool(mixed), TOOL_CALL, scan_inputs=False) + # A bare list return is not a ToolMessage yet: LangChain stringifies a + # list holding non-content blocks, so that string is scanned. + await invoke(is_sync, make_tool([{"payload": "AKIA-secret"}]), TOOL_CALL, scan_inputs=False) + assert [item["content"] for item in scan_requests(route)] == [ + "visible", + '[{"payload": "AKIA-secret"}]', + ] + + +# --- Sync-only tools under ``ainvoke`` (documented limitation) --- + +SYNC_ONLY_SCAN_RESPONSES = { + "block": httpx.Response(200, json=BLOCKED_RESPONSE), + "fail_closed_503": httpx.Response(503, text="unavailable"), +} + + +def make_sync_only_tool(calls: list[str]) -> StructuredTool: + def lookup(query: str) -> str: + calls.append(query) + return "tool output" + + return StructuredTool.from_function(lookup, name="lookup", description="lookup") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("hook", ["tool_input", "tool_output"]) +@pytest.mark.parametrize("response", list(SYNC_ONLY_SCAN_RESPONSES)) +@respx.mock +async def test_async_handler_cannot_stop_sync_only_tool_under_ainvoke( + hook: str, response: str, caplog: pytest.LogCaptureFixture +) -> None: + # LangChain runs a sync-only tool's ``ainvoke`` through ``invoke`` in a + # worker thread and logs and swallows the async handler's exceptions. If + # this starts failing, LangChain now propagates them: update the docs. + route = respx.post(f"{BASE}/v1/scan").mock(return_value=SYNC_ONLY_SCAN_RESPONSES[response]) + calls: list[str] = [] + with caplog.at_level(logging.WARNING): + result = await invoke( + False, + make_sync_only_tool(calls), + {"query": "q"}, + raise_on_block=True, + fail_closed=True, + scan_inputs=hook == "tool_input", + scan_outputs=hook == "tool_output", + ) + assert result == "tool output" + assert calls == ["q"] + assert len(route.calls) == 1 + assert f"ContentBlockedError('ShieldCortex blocked {hook}" in caplog.text + + +@pytest.mark.asyncio +@pytest.mark.parametrize("hook", ["tool_input", "tool_output"]) +@pytest.mark.parametrize("response", list(SYNC_ONLY_SCAN_RESPONSES)) +@respx.mock +async def test_sync_handler_stops_sync_only_tool_under_ainvoke(hook: str, response: str) -> None: + # The documented workaround: the sync handler's exceptions propagate. + route = respx.post(f"{BASE}/v1/scan").mock(return_value=SYNC_ONLY_SCAN_RESPONSES[response]) + calls: list[str] = [] + tool = make_sync_only_tool(calls) + with ShieldCortex(api_key="sc_test_abc") as client: + handler = integration.ShieldCortexSyncCallbackHandler( + client, + raise_on_block=True, + fail_closed=True, + scan_inputs=hook == "tool_input", + scan_outputs=hook == "tool_output", + ) + with pytest.raises(integration.ContentBlockedError) as exc_info: + await tool.ainvoke({"query": "q"}, config={"callbacks": [handler]}) + assert exc_info.value.source_identifier == f"langchain:{hook}" + assert (exc_info.value.result is None) == (response == "fail_closed_503") + assert calls == ([] if hook == "tool_input" else ["q"]) + assert len(route.calls) == 1 + + +# --- fail_closed across every scanned hook --- + +MATRIX_FAILURES: dict[str, Any] = { + **SCAN_FAILURES, + "429": httpx.Response(429, json={"error": "slow down"}), + "base": ShieldCortexError("boom", 0, ""), +} +HOOKS: dict[str, Any] = { + "chain_input": (lambda: RunnableLambda(lambda value: value), "x", {"scan_outputs": False}), + "llm_input": (lambda: FakeListLLM(responses=["hi"]), "prompt", {"scan_outputs": False}), + "llm_output": (lambda: FakeListLLM(responses=["hi"]), "prompt", {"scan_inputs": False}), + "chat_input": ( + lambda: FakeListChatModel(responses=["hi"]), + "prompt", + {"scan_outputs": False}, + ), + "tool_input": (lambda: make_tool("out"), {"query": "q"}, {"scan_outputs": False}), + "tool_output": (lambda: make_tool("out"), {"query": "q"}, {"scan_inputs": False}), +} + + +def mock_matrix_failure(name: str) -> respx.Route: + failure = MATRIX_FAILURES[name] + route = respx.post(f"{BASE}/v1/scan") + if isinstance(failure, Exception): + return route.mock(side_effect=failure) + return route.mock(return_value=failure) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_sync", [False, True], ids=["async", "sync"]) +@pytest.mark.parametrize("failure", list(MATRIX_FAILURES)) +@pytest.mark.parametrize("hook", list(HOOKS)) +@respx.mock +async def test_fail_closed_matrix(is_sync: bool, failure: str, hook: str) -> None: + make_runnable, value, options = HOOKS[hook] + route = mock_matrix_failure(failure) + with pytest.raises(integration.ContentBlockedError) as exc_info: + await invoke( + is_sync, make_runnable(), value, raise_on_block=True, fail_closed=True, **options + ) + error = exc_info.value + assert error.result is None + assert isinstance(error.__cause__, ShieldCortexError) + assert error.source_identifier == f"langchain:{hook}" + assert len(route.calls) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_sync", [False, True], ids=["async", "sync"]) +@pytest.mark.parametrize("hook", list(HOOKS)) +@respx.mock +async def test_connection_error_propagates_unwrapped(is_sync: bool, hook: str) -> None: + make_runnable, value, options = HOOKS[hook] + route = respx.post(f"{BASE}/v1/scan").mock(side_effect=httpx.ConnectError("refused")) + with pytest.raises(httpx.ConnectError): + await invoke( + is_sync, make_runnable(), value, raise_on_block=True, fail_closed=True, **options + ) + assert len(route.calls) == 1