curbi-langchain 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Curbi, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.4
2
+ Name: curbi-langchain
3
+ Version: 0.1.0
4
+ Summary: Fail-closed remote Curbi configured-rule checking for LangChain text runnables
5
+ Author: Curbi, Inc.
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://curbi.io
8
+ Project-URL: Repository, https://github.com/Curbi-Inc/curbi-check
9
+ Project-URL: Documentation, https://curbi.io/connect/
10
+ Project-URL: Issues, https://github.com/Curbi-Inc/curbi-check/issues
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: langchain-core<2,>=1.0
17
+ Requires-Dist: httpx<1,>=0.28
18
+ Dynamic: license-file
19
+
20
+ # curbi-langchain
21
+
22
+ A real LangChain LCEL Runnable that checks completed **text** against your configured Curbi policy. A passing reply returns unchanged; findings raise `CurbiBlocked` with structured `.findings`. Invalid responses, timeouts and HTTP errors raise `CurbiUnavailable`, so unchecked text is not returned.
23
+
24
+ Install after the reviewed package is published: `pip install curbi-langchain==0.1.0`. For local evaluation before publication, build and install its wheel.
25
+
26
+ ```python
27
+ from curbi_langchain import curbi_guard
28
+ guard = curbi_guard(policy={"prices": [{"item": "Pro", "amount": 49}]})
29
+ guard.invoke("Pro is $99.") # CurbiBlocked: configured price mismatch
30
+ ```
31
+
32
+ In an existing LangChain application, place the guard **after** `StrOutputParser()`:
33
+
34
+ ```python
35
+ from langchain_core.output_parsers import StrOutputParser
36
+ from curbi_langchain import curbi_guard
37
+ # model is your existing LangChain chat model; no model is selected or funded here.
38
+ checked_chain = model | StrOutputParser() | curbi_guard(policy=your_policy)
39
+ reply = checked_chain.invoke("Explain our Pro plan")
40
+ # Also supported: await checked_chain.ainvoke(...), batch(...) and abatch(...).
41
+ ```
42
+
43
+ `policy` must be a JSON dictionary with a non-empty `prices`, `forbid` or `actions` rule collection; empty/no-rule configurations are rejected before networking. Optional `api_key` goes in the Authorization header; keep it in your own secret store. `timeout` defaults to 10 seconds (accepted range 0.1–30), used as an absolute response-acceptance deadline, checked after headers, between body chunks and before accepting a result. HTTPX also applies per-phase timeouts. An already-blocked network read may finish later at its phase timeout; this is not a hard wall-clock cancellation guarantee. No automatic retries occur. Each check uses a fresh idempotency key. Managed API usage may be billable under your account's terms.
44
+
45
+ **Data and limits:** this is remote HTTP checking, not an embedded local checker. Your complete policy and reply are sent to the fixed `https://api.curbi.io/v1/check` endpoint. Redirects are refused; text/request/response sizes and verdict/finding spans are validated. Inputs support up to 4,000 UTF-16 code units and 64 KiB JSON; responses up to 256 KiB. Async checking runs the bounded synchronous client in a worker thread. Cancellation does not guarantee that an already-sent HTTP request is cancelled.
46
+
47
+ This checks completed text, not tokens as they stream; it does not prevent tools/actions already executed by the model. A pass means no configured rule fired. It grants no permission and proves no provider outcome or general truth. The adapter makes no model calls and prints no inputs, keys or provider payloads. LangChain's separately configured tracing may still record your application data.
48
+
49
+ MIT. Source and issue tracker: https://github.com/Curbi-Inc/curbi-check. Package version 0.1.0 is preparation for registry publication, not evidence it is already listed.
50
+
51
+ Validated framework version: langchain-core 1.7.4; httpx 0.28.1, Python 3.11. Tests use real framework classes and mocked HTTP, with no paid model or API calls.
52
+
53
+ The response must explicitly report `proof.authorizationGranted: false`; missing or contradictory authority metadata is rejected. A passing check never grants execution authority.
@@ -0,0 +1,34 @@
1
+ # curbi-langchain
2
+
3
+ A real LangChain LCEL Runnable that checks completed **text** against your configured Curbi policy. A passing reply returns unchanged; findings raise `CurbiBlocked` with structured `.findings`. Invalid responses, timeouts and HTTP errors raise `CurbiUnavailable`, so unchecked text is not returned.
4
+
5
+ Install after the reviewed package is published: `pip install curbi-langchain==0.1.0`. For local evaluation before publication, build and install its wheel.
6
+
7
+ ```python
8
+ from curbi_langchain import curbi_guard
9
+ guard = curbi_guard(policy={"prices": [{"item": "Pro", "amount": 49}]})
10
+ guard.invoke("Pro is $99.") # CurbiBlocked: configured price mismatch
11
+ ```
12
+
13
+ In an existing LangChain application, place the guard **after** `StrOutputParser()`:
14
+
15
+ ```python
16
+ from langchain_core.output_parsers import StrOutputParser
17
+ from curbi_langchain import curbi_guard
18
+ # model is your existing LangChain chat model; no model is selected or funded here.
19
+ checked_chain = model | StrOutputParser() | curbi_guard(policy=your_policy)
20
+ reply = checked_chain.invoke("Explain our Pro plan")
21
+ # Also supported: await checked_chain.ainvoke(...), batch(...) and abatch(...).
22
+ ```
23
+
24
+ `policy` must be a JSON dictionary with a non-empty `prices`, `forbid` or `actions` rule collection; empty/no-rule configurations are rejected before networking. Optional `api_key` goes in the Authorization header; keep it in your own secret store. `timeout` defaults to 10 seconds (accepted range 0.1–30), used as an absolute response-acceptance deadline, checked after headers, between body chunks and before accepting a result. HTTPX also applies per-phase timeouts. An already-blocked network read may finish later at its phase timeout; this is not a hard wall-clock cancellation guarantee. No automatic retries occur. Each check uses a fresh idempotency key. Managed API usage may be billable under your account's terms.
25
+
26
+ **Data and limits:** this is remote HTTP checking, not an embedded local checker. Your complete policy and reply are sent to the fixed `https://api.curbi.io/v1/check` endpoint. Redirects are refused; text/request/response sizes and verdict/finding spans are validated. Inputs support up to 4,000 UTF-16 code units and 64 KiB JSON; responses up to 256 KiB. Async checking runs the bounded synchronous client in a worker thread. Cancellation does not guarantee that an already-sent HTTP request is cancelled.
27
+
28
+ This checks completed text, not tokens as they stream; it does not prevent tools/actions already executed by the model. A pass means no configured rule fired. It grants no permission and proves no provider outcome or general truth. The adapter makes no model calls and prints no inputs, keys or provider payloads. LangChain's separately configured tracing may still record your application data.
29
+
30
+ MIT. Source and issue tracker: https://github.com/Curbi-Inc/curbi-check. Package version 0.1.0 is preparation for registry publication, not evidence it is already listed.
31
+
32
+ Validated framework version: langchain-core 1.7.4; httpx 0.28.1, Python 3.11. Tests use real framework classes and mocked HTTP, with no paid model or API calls.
33
+
34
+ The response must explicitly report `proof.authorizationGranted: false`; missing or contradictory authority metadata is rejected. A passing check never grants execution authority.
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "curbi-langchain"
7
+ version = "0.1.0"
8
+ description = "Fail-closed remote Curbi configured-rule checking for LangChain text runnables"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{name = "Curbi, Inc."}]
14
+ dependencies = ["langchain-core>=1.0,<2", "httpx>=0.28,<1"]
15
+ classifiers = ["Programming Language :: Python :: 3", "Operating System :: OS Independent"]
16
+
17
+ [project.urls]
18
+ Homepage = "https://curbi.io"
19
+ Repository = "https://github.com/Curbi-Inc/curbi-check"
20
+ Documentation = "https://curbi.io/connect/"
21
+ Issues = "https://github.com/Curbi-Inc/curbi-check/issues"
22
+
23
+ [tool.setuptools.packages.find]
24
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,20 @@
1
+ """Curbi remote configured-rule checking for LangChain LCEL."""
2
+ import asyncio
3
+ from langchain_core.runnables import RunnableLambda
4
+ from ._check import Checker, CurbiError, CurbiUnavailable, CurbiBlocked
5
+
6
+ __all__ = ["curbi_guard", "CurbiError", "CurbiUnavailable", "CurbiBlocked"]
7
+
8
+
9
+ def curbi_guard(policy, *, api_key=None, timeout=10.0):
10
+ """Pipe after generated text. Returns the exact text or raises a CurbiError.
11
+
12
+ Remote checks send the policy and reply to Curbi. This is not a streaming
13
+ interceptor, execution authorization, or provider confirmation.
14
+ """
15
+ checker = Checker(policy, api_key, timeout)
16
+
17
+ async def check_async(reply):
18
+ return await asyncio.to_thread(checker.check, reply)
19
+
20
+ return RunnableLambda(checker.check, afunc=check_async, name="curbi_guard")
@@ -0,0 +1,105 @@
1
+ """Bounded remote rule checks. Never permission or provider-outcome proof."""
2
+ import copy
3
+ import json
4
+ import math
5
+ import uuid
6
+ import time
7
+ import httpx
8
+
9
+ ENDPOINT = "https://api.curbi.io/v1/check"
10
+
11
+
12
+ class CurbiError(RuntimeError):
13
+ """No unchecked result is returned when checking fails."""
14
+
15
+
16
+ class CurbiUnavailable(CurbiError):
17
+ """The check did not yield a valid verdict."""
18
+
19
+
20
+ class CurbiBlocked(CurbiError):
21
+ def __init__(self, findings):
22
+ super().__init__("Curbi found a configured-rule violation")
23
+ self.findings = tuple(copy.deepcopy(findings))
24
+
25
+
26
+ class Checker:
27
+ def __init__(self, policy, api_key=None, timeout=10.0):
28
+ if not isinstance(policy, dict) or not policy:
29
+ raise ValueError("A non-empty policy is required")
30
+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not math.isfinite(timeout) or not 0.1 <= timeout <= 30:
31
+ raise ValueError("timeout must be between 0.1 and 30 seconds")
32
+ if api_key is not None and (not isinstance(api_key, str) or not 1 <= len(api_key) <= 512 or any(ord(c) < 33 or ord(c) > 126 for c in api_key)):
33
+ raise ValueError("Invalid API key")
34
+ try:
35
+ self._policy = json.loads(json.dumps(policy, allow_nan=False))
36
+ except (ValueError, TypeError, RecursionError):
37
+ raise ValueError("Policy must contain JSON values") from None
38
+ rules = self._policy
39
+ if not (isinstance(rules.get("prices"), list) and rules["prices"] or isinstance(rules.get("forbid"), list) and rules["forbid"] or isinstance(rules.get("actions"), dict) and rules["actions"]):
40
+ raise ValueError("Policy has no_rules: configure prices, forbid or actions")
41
+ self._key, self._timeout = api_key, float(timeout)
42
+
43
+ def check(self, reply):
44
+ if not isinstance(reply, str) or not reply.strip():
45
+ raise CurbiUnavailable("Non-empty text is required")
46
+ try:
47
+ utf16 = reply.encode("utf-16-le")
48
+ body = json.dumps({"policy": self._policy, "reply": reply}, ensure_ascii=False, allow_nan=False).encode("utf-8")
49
+ except (UnicodeError, ValueError, TypeError, RecursionError):
50
+ raise CurbiUnavailable("Input is not valid bounded JSON text") from None
51
+ if len(utf16) // 2 > 4000 or len(body) > 65536:
52
+ raise CurbiUnavailable("Check input exceeds the supported limit")
53
+ headers = {"Content-Type": "application/json", "Accept": "application/json", "User-Agent": "CurbiPython/0.1.0", "Idempotency-Key": uuid.uuid4().hex}
54
+ if self._key:
55
+ headers["Authorization"] = "Bearer " + self._key
56
+ deadline = time.monotonic() + self._timeout
57
+
58
+ def within_deadline():
59
+ if time.monotonic() >= deadline:
60
+ raise CurbiUnavailable("Check network deadline exceeded")
61
+
62
+ try:
63
+ with httpx.Client(timeout=self._timeout, follow_redirects=False, trust_env=False) as client:
64
+ within_deadline()
65
+ with client.stream("POST", ENDPOINT, headers=headers, content=body) as response:
66
+ within_deadline()
67
+ if response.status_code != 200:
68
+ raise CurbiUnavailable("Check service did not return success")
69
+ if response.headers.get("content-type", "").split(";", 1)[0].strip().lower() != "application/json":
70
+ raise CurbiUnavailable("Check service returned an invalid content type")
71
+ chunks, size = [], 0
72
+ for chunk in response.iter_bytes():
73
+ within_deadline()
74
+ size += len(chunk)
75
+ if size > 262144:
76
+ raise CurbiUnavailable("Check response exceeds the supported limit")
77
+ chunks.append(chunk)
78
+ within_deadline()
79
+ verdict = json.loads(b"".join(chunks))
80
+ except (httpx.RequestError, UnicodeError, ValueError, RecursionError):
81
+ raise CurbiUnavailable("Check service unavailable or response invalid") from None
82
+ if not isinstance(verdict, dict) or verdict.get("object") != "check" or verdict.get("version") != "2026-11-01" or type(verdict.get("pass")) is not bool:
83
+ raise CurbiUnavailable("Invalid check verdict")
84
+ proof = verdict.get("proof")
85
+ if not isinstance(proof, dict) or proof.get("authorizationGranted") is not False:
86
+ raise CurbiUnavailable("Invalid check authority boundary")
87
+ findings = verdict.get("findings")
88
+ if not isinstance(findings, list) or len(findings) > 100 or verdict["pass"] != (len(findings) == 0):
89
+ raise CurbiUnavailable("Inconsistent check verdict")
90
+ for finding in findings:
91
+ if not isinstance(finding, dict) or not isinstance(finding.get("rule"), str) or not 1 <= len(finding["rule"]) <= 100 or not isinstance(finding.get("why"), str) or not isinstance(finding.get("text"), str):
92
+ raise CurbiUnavailable("Invalid finding")
93
+ span = finding.get("span")
94
+ if not isinstance(span, list) or len(span) != 2 or any(type(n) is not int for n in span) or not 0 <= span[0] <= span[1] <= len(utf16) // 2:
95
+ raise CurbiUnavailable("Invalid finding span")
96
+ try:
97
+ original = utf16[span[0] * 2:span[1] * 2].decode("utf-16-le")
98
+ except UnicodeError:
99
+ raise CurbiUnavailable("Invalid finding span") from None
100
+ if finding["text"] != original:
101
+ raise CurbiUnavailable("Finding does not match original text")
102
+ within_deadline()
103
+ if findings:
104
+ raise CurbiBlocked(findings)
105
+ return reply
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.4
2
+ Name: curbi-langchain
3
+ Version: 0.1.0
4
+ Summary: Fail-closed remote Curbi configured-rule checking for LangChain text runnables
5
+ Author: Curbi, Inc.
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://curbi.io
8
+ Project-URL: Repository, https://github.com/Curbi-Inc/curbi-check
9
+ Project-URL: Documentation, https://curbi.io/connect/
10
+ Project-URL: Issues, https://github.com/Curbi-Inc/curbi-check/issues
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: langchain-core<2,>=1.0
17
+ Requires-Dist: httpx<1,>=0.28
18
+ Dynamic: license-file
19
+
20
+ # curbi-langchain
21
+
22
+ A real LangChain LCEL Runnable that checks completed **text** against your configured Curbi policy. A passing reply returns unchanged; findings raise `CurbiBlocked` with structured `.findings`. Invalid responses, timeouts and HTTP errors raise `CurbiUnavailable`, so unchecked text is not returned.
23
+
24
+ Install after the reviewed package is published: `pip install curbi-langchain==0.1.0`. For local evaluation before publication, build and install its wheel.
25
+
26
+ ```python
27
+ from curbi_langchain import curbi_guard
28
+ guard = curbi_guard(policy={"prices": [{"item": "Pro", "amount": 49}]})
29
+ guard.invoke("Pro is $99.") # CurbiBlocked: configured price mismatch
30
+ ```
31
+
32
+ In an existing LangChain application, place the guard **after** `StrOutputParser()`:
33
+
34
+ ```python
35
+ from langchain_core.output_parsers import StrOutputParser
36
+ from curbi_langchain import curbi_guard
37
+ # model is your existing LangChain chat model; no model is selected or funded here.
38
+ checked_chain = model | StrOutputParser() | curbi_guard(policy=your_policy)
39
+ reply = checked_chain.invoke("Explain our Pro plan")
40
+ # Also supported: await checked_chain.ainvoke(...), batch(...) and abatch(...).
41
+ ```
42
+
43
+ `policy` must be a JSON dictionary with a non-empty `prices`, `forbid` or `actions` rule collection; empty/no-rule configurations are rejected before networking. Optional `api_key` goes in the Authorization header; keep it in your own secret store. `timeout` defaults to 10 seconds (accepted range 0.1–30), used as an absolute response-acceptance deadline, checked after headers, between body chunks and before accepting a result. HTTPX also applies per-phase timeouts. An already-blocked network read may finish later at its phase timeout; this is not a hard wall-clock cancellation guarantee. No automatic retries occur. Each check uses a fresh idempotency key. Managed API usage may be billable under your account's terms.
44
+
45
+ **Data and limits:** this is remote HTTP checking, not an embedded local checker. Your complete policy and reply are sent to the fixed `https://api.curbi.io/v1/check` endpoint. Redirects are refused; text/request/response sizes and verdict/finding spans are validated. Inputs support up to 4,000 UTF-16 code units and 64 KiB JSON; responses up to 256 KiB. Async checking runs the bounded synchronous client in a worker thread. Cancellation does not guarantee that an already-sent HTTP request is cancelled.
46
+
47
+ This checks completed text, not tokens as they stream; it does not prevent tools/actions already executed by the model. A pass means no configured rule fired. It grants no permission and proves no provider outcome or general truth. The adapter makes no model calls and prints no inputs, keys or provider payloads. LangChain's separately configured tracing may still record your application data.
48
+
49
+ MIT. Source and issue tracker: https://github.com/Curbi-Inc/curbi-check. Package version 0.1.0 is preparation for registry publication, not evidence it is already listed.
50
+
51
+ Validated framework version: langchain-core 1.7.4; httpx 0.28.1, Python 3.11. Tests use real framework classes and mocked HTTP, with no paid model or API calls.
52
+
53
+ The response must explicitly report `proof.authorizationGranted: false`; missing or contradictory authority metadata is rejected. A passing check never grants execution authority.
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/curbi_langchain/__init__.py
5
+ src/curbi_langchain/_check.py
6
+ src/curbi_langchain.egg-info/PKG-INFO
7
+ src/curbi_langchain.egg-info/SOURCES.txt
8
+ src/curbi_langchain.egg-info/dependency_links.txt
9
+ src/curbi_langchain.egg-info/requires.txt
10
+ src/curbi_langchain.egg-info/top_level.txt
11
+ tests/test_langchain_framework.py
12
+ tests/test_transport_langchain.py
@@ -0,0 +1,2 @@
1
+ langchain-core<2,>=1.0
2
+ httpx<1,>=0.28
@@ -0,0 +1 @@
1
+ curbi_langchain
@@ -0,0 +1,37 @@
1
+ import asyncio
2
+ import pytest
3
+ import httpx
4
+ from langchain_core.runnables import Runnable
5
+ from langchain_core.language_models.fake_chat_models import FakeListChatModel
6
+ from langchain_core.output_parsers import StrOutputParser
7
+ from curbi_langchain import curbi_guard, CurbiBlocked, CurbiUnavailable
8
+ from test_transport_langchain import wire, POLICY, PASS
9
+
10
+
11
+ def test_real_lcel_model_parser_guard_batch(wire):
12
+ guard = curbi_guard(POLICY)
13
+ assert isinstance(guard, Runnable)
14
+ chain = FakeListChatModel(responses=["Pro is $49."]) | StrOutputParser() | guard
15
+ assert chain.invoke("price?") == "Pro is $49."
16
+ assert chain.batch(["price?", "price?"]) == ["Pro is $49."] * 2
17
+
18
+
19
+ def test_real_lcel_async_and_abatch(wire):
20
+ chain = FakeListChatModel(responses=["Pro is $49."]) | StrOutputParser() | curbi_guard(POLICY)
21
+ assert asyncio.run(chain.ainvoke("price?")) == "Pro is $49."
22
+ assert asyncio.run(chain.abatch(["one", "two"])) == ["Pro is $49."] * 2
23
+
24
+
25
+ def test_real_lcel_block_is_not_an_ai_message_or_unchecked_reply(wire):
26
+ state, _ = wire
27
+ state["response"] = lambda req: httpx.Response(200, json={**PASS, "pass": False, "findings": [{"rule": "price:mismatch", "span": [7, 10], "text": "$99", "why": "Wrong price"}]})
28
+ chain = FakeListChatModel(responses=["Pro is $99."]) | StrOutputParser() | curbi_guard(POLICY)
29
+ with pytest.raises(CurbiBlocked):
30
+ chain.invoke("price?")
31
+ with pytest.raises(CurbiBlocked):
32
+ asyncio.run(chain.ainvoke("price?"))
33
+
34
+
35
+ def test_ai_message_without_parser_fails_closed(wire):
36
+ with pytest.raises(CurbiUnavailable):
37
+ (FakeListChatModel(responses=["Pro is $49."]) | curbi_guard(POLICY)).invoke("price?")
@@ -0,0 +1,148 @@
1
+ import importlib
2
+ import json
3
+ import time
4
+ import httpx
5
+ import pytest
6
+
7
+ check = importlib.import_module("curbi_langchain._check")
8
+ POLICY = {"prices": [{"item": "Pro", "amount": 49}]}
9
+ PASS = {"object": "check", "version": "2026-11-01", "pass": True, "findings": [], "proof": {"authorizationGranted": False}}
10
+
11
+
12
+ @pytest.fixture
13
+ def wire(monkeypatch):
14
+ original = httpx.Client
15
+ calls = []
16
+ state = {"response": lambda req: httpx.Response(200, json=PASS)}
17
+
18
+ def handler(request):
19
+ calls.append(request)
20
+ assert str(request.url) == "https://api.curbi.io/v1/check"
21
+ assert request.method == "POST"
22
+ return state["response"](request)
23
+
24
+ def client(**kwargs):
25
+ assert kwargs["follow_redirects"] is False
26
+ assert kwargs["trust_env"] is False
27
+ assert 0.1 <= kwargs["timeout"] <= 30
28
+ return original(transport=httpx.MockTransport(handler), **kwargs)
29
+
30
+ monkeypatch.setattr(check.httpx, "Client", client)
31
+ monkeypatch.setenv("LANGCHAIN_TRACING_V2", "false")
32
+ monkeypatch.setenv("LANGSMITH_TRACING", "false")
33
+ return state, calls
34
+
35
+
36
+ def test_pass_preserves_unicode_policy_snapshot_auth_and_idempotency(wire):
37
+ state, calls = wire
38
+ policy = {"prices": [{"item": "Pro", "amount": 49}]}
39
+ c = check.Checker(policy, api_key="private-synthetic-test")
40
+ policy["prices"][0]["amount"] = 999
41
+ for _ in range(2):
42
+ assert c.check("😀 Pro is $49.") == "😀 Pro is $49."
43
+ assert json.loads(calls[0].content)["policy"]["prices"][0]["amount"] == 49
44
+ assert calls[0].headers["Authorization"] == "Bearer private-synthetic-test"
45
+ assert calls[0].headers["Idempotency-Key"] != calls[1].headers["Idempotency-Key"]
46
+ assert "private-synthetic-test" not in repr(c)
47
+
48
+
49
+ def test_block_returns_structured_findings_with_utf16_span(wire):
50
+ state, _ = wire
51
+ finding = {"rule": "price:mismatch", "span": [3, 6], "text": "$99", "why": "Configured price differs"}
52
+ state["response"] = lambda req: httpx.Response(200, json={**PASS, "pass": False, "findings": [finding]})
53
+ with pytest.raises(check.CurbiBlocked) as error:
54
+ check.Checker(POLICY).check("😀 $99")
55
+ assert error.value.findings == (finding,)
56
+
57
+
58
+ @pytest.mark.parametrize("status", [301, 302, 307, 308, 400, 401, 403, 429, 500, 503])
59
+ def test_http_error_and_redirect_never_release_reply(wire, status):
60
+ state, calls = wire
61
+ state["response"] = lambda req: httpx.Response(status, headers={"Location": "https://elsewhere.invalid"})
62
+ with pytest.raises(check.CurbiUnavailable):
63
+ check.Checker(POLICY).check("Pro is $49.")
64
+ assert len(calls) == 1
65
+
66
+
67
+ @pytest.mark.parametrize("verdict", [[], {}, {**PASS, "object": "check.batch"}, {**PASS, "version": "unknown"}, {**PASS, "pass": 1}, {**PASS, "findings": None}, {**PASS, "pass": False}, {**PASS, "findings": [{"rule": "x"}]}, {**PASS, "pass": False, "findings": [{"rule": "x", "why": "x", "span": [-1, 2], "text": "Pr"}]}, {**PASS, "pass": False, "findings": [{"rule": "x", "why": "x", "span": [0, 3], "text": "wrong"}]}, {**PASS, "pass": False, "findings": [{"rule": "x", "why": "x", "span": [False, 2], "text": "Pr"}]}])
68
+ def test_malformed_or_inconsistent_verdict_fails_closed(wire, verdict):
69
+ state, _ = wire
70
+ state["response"] = lambda req: httpx.Response(200, json=verdict)
71
+ with pytest.raises(check.CurbiUnavailable):
72
+ check.Checker(POLICY).check("Pro is $49.")
73
+
74
+
75
+ @pytest.mark.parametrize("response", [httpx.Response(200, content=b"{", headers={"Content-Type": "application/json"}), httpx.Response(200, json=PASS, headers={"Content-Type": "text/html"}), httpx.Response(200, content=b" " * 262145, headers={"Content-Type": "application/json"})])
76
+ def test_bad_json_content_type_and_oversized_response(wire, response):
77
+ state, _ = wire
78
+ state["response"] = lambda req: response
79
+ with pytest.raises(check.CurbiUnavailable):
80
+ check.Checker(POLICY).check("Pro is $49.")
81
+
82
+
83
+ def test_timeout_is_typed_sanitized_and_not_retried(wire):
84
+ state, calls = wire
85
+ def timeout(req):
86
+ raise httpx.ReadTimeout("private-synthetic-test must not appear")
87
+ state["response"] = timeout
88
+ with pytest.raises(check.CurbiUnavailable) as error:
89
+ check.Checker(POLICY, timeout=0.1).check("Pro is $49.")
90
+ assert "private-synthetic-test" not in str(error.value)
91
+ assert len(calls) == 1
92
+
93
+
94
+ @pytest.mark.parametrize("reply", [None, {}, "", " ", "x" * 4001, "😀" * 2001, "\ud800"])
95
+ def test_bad_reply_is_refused_before_network(wire, reply):
96
+ _, calls = wire
97
+ with pytest.raises(check.CurbiUnavailable):
98
+ check.Checker(POLICY).check(reply)
99
+ assert not calls
100
+
101
+
102
+ def test_oversized_json_refused_before_network(wire):
103
+ _, calls = wire
104
+ with pytest.raises(check.CurbiUnavailable):
105
+ check.Checker({**POLICY, "large": "x" * 65536}).check("hello")
106
+ assert not calls
107
+
108
+
109
+ @pytest.mark.parametrize("kwargs", [{"policy": {}}, {"policy": []}, {"policy": POLICY, "timeout": 0}, {"policy": POLICY, "timeout": True}, {"policy": POLICY, "timeout": float("inf")}, {"policy": POLICY, "api_key": "secret\nheader"}])
110
+ def test_invalid_constructor(kwargs):
111
+ with pytest.raises(ValueError):
112
+ check.Checker(**kwargs)
113
+
114
+
115
+ @pytest.mark.parametrize("policy", [{"prices": []}, {"forbid": []}, {"actions": {}}, {"prices": [], "forbid": [], "actions": {}}, {"metadata": "not a rule"}])
116
+ def test_policy_with_no_rules_refused_at_construction(policy):
117
+ with pytest.raises(ValueError, match="no_rules"):
118
+ check.Checker(policy)
119
+
120
+
121
+ def test_dribbling_body_cannot_extend_total_acceptance_deadline(wire, monkeypatch):
122
+ state, _ = wire
123
+ clock = [0.0]
124
+ monkeypatch.setattr(time, "monotonic", lambda: clock[0])
125
+ consumed = []
126
+ class Dribble(httpx.SyncByteStream):
127
+ def __iter__(self):
128
+ for byte in json.dumps(PASS).encode():
129
+ clock[0] += 0.06 # each chunk arrives inside the0.1s read timeout
130
+ consumed.append(byte)
131
+ yield bytes([byte])
132
+ state["response"] = lambda req: httpx.Response(200, headers={"Content-Type": "application/json"}, stream=Dribble())
133
+ with pytest.raises(check.CurbiUnavailable, match="deadline"):
134
+ check.Checker(POLICY, timeout=0.1).check("Pro is $49.")
135
+ assert len(consumed) < len(json.dumps(PASS))
136
+
137
+
138
+ @pytest.mark.parametrize("proof", ["missing", None, {}, {"authorizationGranted": True}, {"authorizationGranted": 0}, "authority"])
139
+ def test_verdict_must_explicitly_deny_execution_authority(wire, proof):
140
+ state, _ = wire
141
+ verdict = dict(PASS)
142
+ if proof == "missing":
143
+ verdict.pop("proof")
144
+ else:
145
+ verdict["proof"] = proof
146
+ state["response"] = lambda req: httpx.Response(200, json=verdict)
147
+ with pytest.raises(check.CurbiUnavailable):
148
+ check.Checker(POLICY).check("Pro is $49.")