From 1f81ac671298356bb91d6af9ab9a29da702d5275 Mon Sep 17 00:00:00 2001 From: Srikanth Date: Tue, 13 Oct 2026 12:40:01 +0530 Subject: [PATCH] fix: missing response verdicts fail closed; mark fail-open classify/pii results as degraded --- CHANGELOG.md | 16 ++++ docs/sdk/types.md | 2 + guardex/_engine/runner.py | 10 +-- guardex/_stream_base.py | 2 +- guardex/_types.py | 4 + guardex/async_client.py | 4 +- guardex/classifier.py | 9 ++- guardex/client.py | 4 +- guardex/guard.py | 43 ++++++---- guardex/stream.py | 4 +- pyproject.toml | 2 +- tests/test_missing_verdicts.py | 141 +++++++++++++++++++++++++++++++++ 12 files changed, 209 insertions(+), 32 deletions(-) create mode 100644 tests/test_missing_verdicts.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f072cde..00120e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,22 @@ project tries to follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [0.2.1] - 2026-10-13 + +### Security + +- A response with no verdict field is no longer read as a pass: a missing + `safe`, `allowed` or `grounded` reads as false, and a missing `has_pii` or + `has_contradiction` as true. +- `ClassifyResult` and `PIIResult` gain `degraded`, set when `classify()`, + `pii_scan()` or `LlamaGuardClassifier` return through a fail-open path, and + on `screen()`'s classify and PII results. `screen()` now also sets + `ScreenResult.degraded` in local mode when a model did not load. +- `screen()` blocks when PII is reported but no masked text came back, and + `pii_mask()` raises instead of returning the unmasked text. `pii_mask()` + on text without PII now returns the text (it returned `None` in local and + server mode). + ## [0.2.0] - 2026-07-11 ### Added diff --git a/docs/sdk/types.md b/docs/sdk/types.md index 0bbb2ae..0c33996 100644 --- a/docs/sdk/types.md +++ b/docs/sdk/types.md @@ -94,6 +94,7 @@ class ClassifyResult: categories: list[str] = field(default_factory=list) # All detected categories confidence: float = 1.0 # Classification confidence description: Optional[str] = None # Human-readable category label + degraded: bool = False # True when returned via a fail-open path ``` **Example:** @@ -120,6 +121,7 @@ class PIIResult: has_pii: bool # Whether PII was detected entities: list[PIIEntity] = field(default_factory=list) # Detected entities masked_text: Optional[str] = None # Text with PII replaced (if masked) + degraded: bool = False # True when returned via a fail-open path ``` **Example:** diff --git a/guardex/_engine/runner.py b/guardex/_engine/runner.py index 3f77f88..b31aa97 100644 --- a/guardex/_engine/runner.py +++ b/guardex/_engine/runner.py @@ -114,7 +114,7 @@ def _classify_raw( "GuardEx classifier provider not registered - " "fail_open=True, returning safe=True (content NOT screened)" ) - return {"safe": True, "category": None, "categories": [], "confidence": 1.0} + return {"safe": True, "category": None, "categories": [], "confidence": 1.0, "_fail_open": True} raise RuntimeError( "GuardEx classifier not loaded. " "pip install 'guardex-ai[local]' - or pass api_key=/base_url= for server mode." @@ -122,7 +122,7 @@ def _classify_raw( raw = _run_async(provider.classify(text, stage=stage, categories=categories, cascade_mode=cascade_mode)) return { - "safe": raw.get("safe", True), + "safe": raw.get("safe", False), "category": raw.get("category"), "categories": raw.get("categories", []), "confidence": raw.get("confidence", 1.0), @@ -151,7 +151,7 @@ def _pii_raw( "GuardEx PII provider not registered - " "fail_open=True, returning has_pii=False (PII NOT scanned)" ) - return {"has_pii": False, "entities": [], "masked_text": text if mask else None} + return {"has_pii": False, "entities": [], "masked_text": text if mask else None, "_fail_open": True} raise RuntimeError( "GuardEx PII detector not loaded. " "pip install 'guardex-ai[local]' - or pass api_key=/base_url= for server mode." @@ -219,7 +219,7 @@ def _scope_raw( ) raw = _run_async(provider.check_scope(text, profile, alpha=alpha)) return { - "allowed": raw.get("allowed", True), + "allowed": raw.get("allowed", False), "distance": raw.get("distance", 0.0), "matched_topic": raw.get("matched_topic"), "confidence": raw.get("confidence", 1.0), @@ -451,7 +451,7 @@ def pii_scan( """Scan text for PII. Returns raw pii dict (no masked_text).""" _ensure_providers() raw = self._pii_raw(text, entities=entities, threshold=threshold, mask=False) - return {"has_pii": raw["has_pii"], "entities": raw["entities"]} + return {k: raw[k] for k in ("has_pii", "entities", "_fail_open") if k in raw} def pii_mask( self, diff --git a/guardex/_stream_base.py b/guardex/_stream_base.py index b6ad073..a1f208a 100644 --- a/guardex/_stream_base.py +++ b/guardex/_stream_base.py @@ -98,7 +98,7 @@ def classify_should_block(classify: dict, min_confidence: float) -> bool: ``classify_min_confidence`` is treated as safe so streaming and ``Guard.screen()`` agree. """ - if classify.get("safe", True): + if classify.get("safe", False): return False if min_confidence > 0.0 and classify.get("confidence", 1.0) < min_confidence: return False diff --git a/guardex/_types.py b/guardex/_types.py index 928e2ed..413ecf0 100644 --- a/guardex/_types.py +++ b/guardex/_types.py @@ -72,6 +72,8 @@ class ClassifyResult: categories: list[str] = field(default_factory=list) confidence: float = 1.0 description: Optional[str] = None + degraded: bool = False + """True when no classification ran (fail-open); ``safe`` is then not a real verdict.""" @dataclass(frozen=True, slots=True) @@ -80,6 +82,8 @@ class PIIResult: has_pii: bool entities: list[PIIEntity] = field(default_factory=list) masked_text: Optional[str] = None + degraded: bool = False + """True when no PII scan ran (fail-open); ``has_pii`` is then not a real verdict.""" @dataclass(frozen=True, slots=True) diff --git a/guardex/async_client.py b/guardex/async_client.py index e2b5e58..775e249 100644 --- a/guardex/async_client.py +++ b/guardex/async_client.py @@ -403,7 +403,7 @@ async def classify( body, request_id = await self._request("POST", "/v1/classify", json=payload, extra_headers=extra_headers) if body.get("_fail_open"): - return {"safe": True, "category": None, "categories": [], "_request_id": None} + return {"safe": True, "category": None, "categories": [], "_request_id": None, "_fail_open": True} if request_id: body["_request_id"] = request_id return body @@ -426,7 +426,7 @@ async def pii_scan( body, _ = await self._request("POST", "/v1/pii/scan", json=payload, extra_headers=extra_headers) if body.get("_fail_open"): - return {"has_pii": False, "entities": []} + return {"has_pii": False, "entities": [], "_fail_open": True} return body async def pii_mask( diff --git a/guardex/classifier.py b/guardex/classifier.py index 060b767..6c93c3c 100644 --- a/guardex/classifier.py +++ b/guardex/classifier.py @@ -73,11 +73,12 @@ def classify( categories=self._policy.blocked_categories, ) cr = ClassifyResult( - safe=result.get("safe", True), + safe=result.get("safe", False), category=result.get("category"), categories=result.get("categories", []), confidence=result.get("confidence", 1.0), description=result.get("description"), + degraded=bool(result.get("_fail_open")), ) except Exception as e: logger.warning( @@ -86,9 +87,9 @@ def classify( ) if not self._policy.fail_open: raise - cr = ClassifyResult(safe=True) + cr = ClassifyResult(safe=True, degraded=True) - # Worst-severity wins: any unsafe result trumps a safe one. - if not cr.safe and worst.safe: + # Worst-severity wins: an unsafe or unscreened result replaces a safe one. + if worst.safe and (not cr.safe or cr.degraded): worst = cr return worst diff --git a/guardex/client.py b/guardex/client.py index 5d381da..f0b7f81 100644 --- a/guardex/client.py +++ b/guardex/client.py @@ -258,7 +258,7 @@ def classify( body, request_id = self._request("POST", "/v1/classify", json=payload, extra_headers=extra_headers) if body.get("_fail_open"): - return {"safe": True, "category": None, "categories": [], "_request_id": None} + return {"safe": True, "category": None, "categories": [], "_request_id": None, "_fail_open": True} if request_id: body["_request_id"] = request_id return body @@ -281,7 +281,7 @@ def pii_scan( body, _ = self._request("POST", "/v1/pii/scan", json=payload, extra_headers=extra_headers) if body.get("_fail_open"): - return {"has_pii": False, "entities": []} + return {"has_pii": False, "entities": [], "_fail_open": True} return body def pii_mask( diff --git a/guardex/guard.py b/guardex/guard.py index e36ce91..65b3758 100644 --- a/guardex/guard.py +++ b/guardex/guard.py @@ -60,7 +60,7 @@ Gate, ScreenResult, ClassifyResult, PIIResult, PIIEntity, ScopeResult, Action, GateTrace, gate_to_stage, output_gate_for, ) -from .exceptions import GuardExViolation +from .exceptions import GuardExAPIError, GuardExViolation if TYPE_CHECKING: from ._types import GroundingResult @@ -118,7 +118,7 @@ def _parse_grounding_result( details = [ SentenceGroundingResult( sentence=s.get("sentence", ""), - grounded=s.get("grounded", True), + grounded=s.get("grounded", False), score=s.get("entailment", s.get("score", 1.0)), matched_chunk=s.get("matched_chunk"), verdict=s.get("verdict", "grounded"), @@ -129,9 +129,9 @@ def _parse_grounding_result( ] return GroundingResult( - grounded=raw.get("grounded", True), + grounded=raw.get("grounded", False), faithfulness_score=raw.get("faithfulness_score", 1.0), - has_contradiction=raw.get("has_contradiction", False), + has_contradiction=raw.get("has_contradiction", True), sentence_count=raw.get("sentence_count", 0), grounded_count=raw.get("grounded_count", 0), contradicted_count=raw.get("contradicted_count", 0), @@ -178,8 +178,8 @@ def _parse_screen_result( return ScreenResult( gate=gate, action="pass", - classify=ClassifyResult(safe=True), - pii=PIIResult(has_pii=False), + classify=ClassifyResult(safe=True, degraded=True), + pii=PIIResult(has_pii=False, degraded=True), text=original_text, request_id=request_id, gates_run=gates_run_t, @@ -190,11 +190,12 @@ def _parse_screen_result( # Parse classification clf_data = raw.get("classify", {}) classify = ClassifyResult( - safe=clf_data.get("safe", True), + safe=clf_data.get("safe", False), category=clf_data.get("category"), categories=clf_data.get("categories", []), confidence=clf_data.get("confidence", 1.0), description=clf_data.get("description"), + degraded=bool(clf_data.get("_fail_open")), ) # Parse PII @@ -210,9 +211,10 @@ def _parse_screen_result( for e in pii_data.get("entities", []) ] pii = PIIResult( - has_pii=pii_data.get("has_pii", False), + has_pii=pii_data.get("has_pii", True), entities=pii_entities, masked_text=pii_data.get("masked_text"), + degraded=bool(pii_data.get("_fail_open")), ) # Parse scope @@ -220,7 +222,7 @@ def _parse_screen_result( scope_data = raw.get("scope") if scope_data is not None: scope = ScopeResult( - allowed=scope_data.get("allowed", True), + allowed=scope_data.get("allowed", False), distance=scope_data.get("distance", 0.0), matched_topic=scope_data.get("matched_topic"), confidence=scope_data.get("confidence", 1.0), @@ -249,7 +251,7 @@ def _parse_screen_result( action: Action = "block" elif not classify.safe: action = "block" - elif pii.has_pii and pii_action == "block": + elif pii.has_pii and (pii_action == "block" or not pii.masked_text or "text" not in raw): action = "block" elif pii.has_pii and pii.masked_text: action = "mask" @@ -266,6 +268,7 @@ def _parse_screen_result( request_id=request_id, gates_run=gates_run_t, diagnostics=diagnostics_t, + degraded=classify.degraded or pii.degraded, ) @@ -738,9 +741,9 @@ def classify( **classify_kwargs, ) if raw.get("_fail_open"): - return ClassifyResult(safe=True) + return ClassifyResult(safe=True, degraded=True) return ClassifyResult( - safe=raw.get("safe", True), + safe=raw.get("safe", False), category=raw.get("category"), categories=raw.get("categories", []), confidence=raw.get("confidence", 1.0), @@ -760,7 +763,7 @@ def pii_scan( threshold=policy.pii_threshold, ) if raw.get("_fail_open"): - return PIIResult(has_pii=False) + return PIIResult(has_pii=False, degraded=True) entities = [ PIIEntity( text=e.get("text", ""), @@ -771,7 +774,7 @@ def pii_scan( ) for e in raw.get("entities", []) ] - return PIIResult(has_pii=raw.get("has_pii", False), entities=entities) + return PIIResult(has_pii=raw.get("has_pii", True), entities=entities) def pii_mask( self, @@ -785,7 +788,17 @@ def pii_mask( entities=policy.pii_entities, threshold=policy.pii_threshold, ) - return raw.get("masked_text", text) + masked = raw.get("masked_text") + if masked is not None: + return masked + if raw.get("has_pii") is False: + return text + raise GuardExAPIError( + status_code=502, + error_type="invalid_response", + message="Response has no masked_text. Run a guardex-server that matches this SDK version.", + code="missing_masked_text", + ) def screen_batch( self, diff --git a/guardex/stream.py b/guardex/stream.py index 96e6dc5..2b0286d 100644 --- a/guardex/stream.py +++ b/guardex/stream.py @@ -162,7 +162,7 @@ def _flush(self) -> Iterator[str]: # Topic scope is reported in a separate `scope` object, not in # `classify.safe`; enforce it here to match Guard.screen(). scope = result.get("scope") - if scope is not None and not scope.get("allowed", True): + if scope is not None and not scope.get("allowed", False): logger.warning( "StreamGuard blocked at gate=%s: out of topic scope after %d chars", self._gate, self._total_screened, @@ -289,7 +289,7 @@ async def _aflush(self) -> AsyncIterator[str]: # Topic scope is reported in a separate `scope` object, not in # `classify.safe`; enforce it here to match Guard.screen(). scope = result.get("scope") - if scope is not None and not scope.get("allowed", True): + if scope is not None and not scope.get("allowed", False): logger.warning( "AsyncStreamGuard blocked at gate=%s: out of topic scope after %d chars", self._gate, self._total_screened, diff --git a/pyproject.toml b/pyproject.toml index 19688a5..03c479c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "guardex-ai" -version = "0.2.0" +version = "0.2.1" description = "Open-source AI guardrails: safety classification, PII detection, prompt injection defense for any LLM" readme = "README.md" license = { text = "Apache-2.0" } diff --git a/tests/test_missing_verdicts.py b/tests/test_missing_verdicts.py new file mode 100644 index 0000000..2a4220c --- /dev/null +++ b/tests/test_missing_verdicts.py @@ -0,0 +1,141 @@ +"""A response without a verdict, or a fail-open result, must not read as a clean pass.""" + +from __future__ import annotations + +from unittest.mock import MagicMock + +import httpx +import pytest +import respx + +from guardex.classifier import LlamaGuardClassifier +from guardex.exceptions import GuardExAPIError, GuardExViolation +from guardex.guard import Guard, _parse_grounding_result, _parse_screen_result +from guardex.policy import GuardExPolicy +from guardex.stream import StreamGuard + +BASE = "http://localhost:8001" + + +class TestMissingVerdictFailsClosed: + def test_screen_without_safe_blocks(self) -> None: + r = _parse_screen_result({"pii": {"has_pii": False}}, "input", "hi") + assert r.classify.safe is False + assert r.action == "block" + + def test_screen_without_has_pii_reports_pii(self) -> None: + r = _parse_screen_result({"classify": {"safe": True}}, "input", "hi", pii_action="block") + assert r.pii.has_pii is True + assert r.action == "block" + + def test_scope_without_allowed_blocks(self) -> None: + raw = {"classify": {"safe": True}, "pii": {"has_pii": False}, "scope": {}} + r = _parse_screen_result(raw, "input", "hi") + assert r.scope is not None and r.scope.allowed is False + assert r.action == "block" + + def test_grounding_without_verdict_is_not_grounded(self) -> None: + r = _parse_grounding_result({"details": [{"sentence": "a"}]}) + assert r.grounded is False + assert r.has_contradiction is True + assert r.details[0].grounded is False + + @respx.mock(base_url=BASE) + def test_classify_without_safe_is_unsafe(self, respx_mock: respx.MockRouter, guard: Guard) -> None: + respx_mock.post("/v1/classify").respond(json={"category": None}) + assert guard.classify("hi").safe is False + + @respx.mock(base_url=BASE) + def test_pii_scan_without_has_pii_reports_pii(self, respx_mock: respx.MockRouter, guard: Guard) -> None: + respx_mock.post("/v1/pii/scan").respond(json={"entities": []}) + assert guard.pii_scan("hi").has_pii is True + + @pytest.mark.parametrize("response", [ + {"pii": {"has_pii": False}, "text": "hi"}, + {"classify": {"safe": True}, "pii": {"has_pii": False}, "scope": {}, "text": "hi"}, + ]) + def test_stream_raises(self, response: dict) -> None: + client = MagicMock() + client.screen = MagicMock(return_value=(response, None)) + sg = StreamGuard(client, GuardExPolicy(api_key="gx_test_x", base_url=BASE), gate="output") + with pytest.raises(GuardExViolation): + list(sg.run(iter(["hi"]))) + + def test_classifier_without_safe_is_unsafe(self) -> None: + with respx.mock(base_url=BASE) as mock: + mock.post("/v1/classify").respond(json={"category": None}) + assert LlamaGuardClassifier(GuardExPolicy(base_url=BASE)).classify(["hi"]).safe is False + + +class TestFailOpenIsMarked: + def test_screen_nested_results(self) -> None: + r = _parse_screen_result({"_fail_open": True}, "input", "hi") + assert r.degraded and r.classify.degraded and r.pii.degraded + + @respx.mock(base_url=BASE) + def test_classify(self, respx_mock: respx.MockRouter, guard_fail_open: Guard) -> None: + respx_mock.post("/v1/classify").mock(side_effect=httpx.ConnectError("refused")) + r = guard_fail_open.classify("hi") + assert r.safe is True and r.degraded is True + + @respx.mock(base_url=BASE) + def test_pii_scan(self, respx_mock: respx.MockRouter, guard_fail_open: Guard) -> None: + respx_mock.post("/v1/pii/scan").mock(side_effect=httpx.ConnectError("refused")) + r = guard_fail_open.pii_scan("hi") + assert r.has_pii is False and r.degraded is True + + @respx.mock(base_url=BASE) + def test_real_verdicts_are_not_degraded(self, respx_mock: respx.MockRouter, guard: Guard) -> None: + respx_mock.post("/v1/classify").respond(json={"safe": True}) + respx_mock.post("/v1/pii/scan").respond(json={"has_pii": False, "entities": []}) + assert guard.classify("hi").degraded is False + assert guard.pii_scan("hi").degraded is False + + def test_classifier_keeps_the_mark(self) -> None: + with respx.mock(base_url=BASE) as mock: + mock.post("/v1/classify").mock(side_effect=httpx.ConnectError("refused")) + r = LlamaGuardClassifier(GuardExPolicy(base_url=BASE, fail_open=True)).classify(["a", "b"]) + assert r.safe is True and r.degraded is True + + +class TestLocalFailOpenIsMarked: + def test_classifier_not_loaded(self) -> None: + from unittest.mock import patch + + from guardex._engine.runner import LocalRunner + + with patch("guardex._engine.providers.registry.get_classifier_provider", return_value=None): + raw = LocalRunner(fail_open=True)._classify_raw("hi") + r = _parse_screen_result({"classify": raw, "pii": {"has_pii": False}}, "input", "hi") + assert r.classify.safe is True and r.classify.degraded is True and r.degraded is True + + def test_pii_detector_not_loaded(self) -> None: + from unittest.mock import patch + + from guardex._engine.runner import LocalRunner + + with patch("guardex._engine.providers.registry.get_pii_provider", return_value=None), \ + patch("guardex._engine.runner._ensure_providers"): + raw = LocalRunner(fail_open=True).pii_scan("hi") + assert raw["_fail_open"] is True + + +class TestPiiWithoutMaskedText: + def test_screen_mask_without_masked_text_blocks(self) -> None: + raw = {"classify": {"safe": True}, "pii": {"has_pii": True, "entities": []}, "text": "my ssn"} + assert _parse_screen_result(raw, "input", "my ssn", pii_action="mask").action == "block" + + def test_screen_mask_without_text_blocks(self) -> None: + raw = {"classify": {"safe": True}, "pii": {"has_pii": True, "entities": [], "masked_text": "my "}} + assert _parse_screen_result(raw, "input", "my ssn 123", pii_action="mask").action == "block" + + @respx.mock(base_url=BASE) + def test_pii_mask_without_masked_text_raises(self, respx_mock: respx.MockRouter, guard: Guard) -> None: + respx_mock.post("/v1/pii/mask").respond(json={"has_pii": True, "entities": []}) + with pytest.raises(GuardExAPIError): + guard.pii_mask("my ssn") + + @respx.mock(base_url=BASE) + def test_pii_mask_without_pii_returns_text(self, respx_mock: respx.MockRouter, guard: Guard) -> None: + respx_mock.post("/v1/pii/mask").respond(json={"has_pii": False, "entities": [], "masked_text": None}) + assert guard.pii_mask("hello") == "hello"