haltstate-sdk 0.8.0.dev1__tar.gz → 0.8.0.dev2__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.
Files changed (26) hide show
  1. {haltstate_sdk-0.8.0.dev1/haltstate_sdk.egg-info → haltstate_sdk-0.8.0.dev2}/PKG-INFO +9 -1
  2. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/README.md +8 -0
  3. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/haltstate/__init__.py +5 -1
  4. haltstate_sdk-0.8.0.dev2/haltstate/private_flow.py +282 -0
  5. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2/haltstate_sdk.egg-info}/PKG-INFO +9 -1
  6. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/haltstate_sdk.egg-info/SOURCES.txt +3 -0
  7. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/janus/__init__.py +1 -1
  8. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/pyproject.toml +1 -1
  9. haltstate_sdk-0.8.0.dev2/tests/test_private_flow.py +238 -0
  10. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/LICENSE +0 -0
  11. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/haltstate/decorators.py +0 -0
  12. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/haltstate_sdk.egg-info/dependency_links.txt +0 -0
  13. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/haltstate_sdk.egg-info/requires.txt +0 -0
  14. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/haltstate_sdk.egg-info/top_level.txt +0 -0
  15. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/janus/async_client.py +0 -0
  16. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/janus/client.py +0 -0
  17. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/janus/decorators.py +0 -0
  18. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/janus/exceptions.py +0 -0
  19. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/janus/models.py +0 -0
  20. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/janus/recording.py +0 -0
  21. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/janus/semiotic_probe.py +0 -0
  22. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/setup.cfg +0 -0
  23. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/tests/test_client.py +0 -0
  24. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/tests/test_governed_message_capture.py +0 -0
  25. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/tests/test_import.py +0 -0
  26. {haltstate_sdk-0.8.0.dev1 → haltstate_sdk-0.8.0.dev2}/tests/test_semiotic_probe.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: haltstate-sdk
3
- Version: 0.8.0.dev1
3
+ Version: 0.8.0.dev2
4
4
  Summary: HaltState Python SDK - action control and Proof Packs for AI agents
5
5
  Author-email: Krystal Unity <support@krystalunity.com>
6
6
  License: MIT License
@@ -50,6 +50,14 @@ Dynamic: license-file
50
50
 
51
51
  [![PyPI](https://img.shields.io/pypi/v/haltstate-sdk.svg)](https://pypi.org/project/haltstate-sdk/)
52
52
 
53
+ ### Private reads and buffered replies
54
+
55
+ Use `PrivateFlowClient` or `AsyncPrivateFlowClient` on your application server.
56
+ Call `authorize_read` before fetching a private record and `authorize_reply`
57
+ with a distinct operation ID and the immutable bytes you will send. Proceed at
58
+ each gate only on `decision == "ALLOW" and may_proceed is True`. Replayed receipts
59
+ are evidence only. [Follow the setup and integration guide](https://haltstate.ai/haltstate/docs/private-read-and-reply).
60
+
53
61
  Action control and Proof Packs for autonomous AI agents. Perform pre-action checks, approvals, and post-action reporting with minimal code.
54
62
 
55
63
  ## Semiotic Probe (source candidate, not activated)
@@ -2,6 +2,14 @@
2
2
 
3
3
  [![PyPI](https://img.shields.io/pypi/v/haltstate-sdk.svg)](https://pypi.org/project/haltstate-sdk/)
4
4
 
5
+ ### Private reads and buffered replies
6
+
7
+ Use `PrivateFlowClient` or `AsyncPrivateFlowClient` on your application server.
8
+ Call `authorize_read` before fetching a private record and `authorize_reply`
9
+ with a distinct operation ID and the immutable bytes you will send. Proceed at
10
+ each gate only on `decision == "ALLOW" and may_proceed is True`. Replayed receipts
11
+ are evidence only. [Follow the setup and integration guide](https://haltstate.ai/haltstate/docs/private-read-and-reply).
12
+
5
13
  Action control and Proof Packs for autonomous AI agents. Perform pre-action checks, approvals, and post-action reporting with minimal code.
6
14
 
7
15
  ## Semiotic Probe (source candidate, not activated)
@@ -3,6 +3,7 @@
3
3
  # `from janus import JanusClient` continue to work.
4
4
 
5
5
  from janus.client import JanusClient as HaltStateClient, Permit
6
+ from .private_flow import AsyncPrivateFlowClient, PrivateFlowClient, PrivateFlowDecision
6
7
  from janus.semiotic_probe import SemioticProbeConnection, SemioticProbeError
7
8
  from janus.async_client import AsyncJanusClient as AsyncHaltStateClient
8
9
  from janus.models import (
@@ -49,6 +50,9 @@ from janus import (
49
50
  __all__ = [
50
51
  # HaltState branded names (new)
51
52
  "HaltStateClient",
53
+ "PrivateFlowClient",
54
+ "AsyncPrivateFlowClient",
55
+ "PrivateFlowDecision",
52
56
  "AsyncHaltStateClient",
53
57
  "SemioticProbeConnection",
54
58
  "SemioticProbeError",
@@ -88,4 +92,4 @@ __all__ = [
88
92
  "KillSwitchTriggered",
89
93
  ]
90
94
 
91
- __version__ = "0.8.0.dev1"
95
+ __version__ = "0.8.0.dev2"
@@ -0,0 +1,282 @@
1
+ """Server-side preflight for a private read and one buffered reply; never executes either."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import hashlib
7
+ import json
8
+ import re
9
+ from dataclasses import dataclass
10
+ from datetime import datetime, timezone
11
+ from typing import Any, Dict, Generic, Literal, Optional, TypeVar, Awaitable
12
+ from urllib.parse import urlsplit
13
+ from uuid import UUID
14
+
15
+ import httpx
16
+
17
+ from janus.exceptions import JanusError
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class PrivateFlowDecision:
22
+ decision: Literal["ALLOW", "DENY"]
23
+ may_proceed: bool
24
+ receipt_id: str
25
+ receipt: Dict[str, Any]
26
+ replay: bool
27
+
28
+
29
+ def _origin(base_url: str) -> str:
30
+ # Reject URL credentials, path rewriting, and parser-dependent delimiters.
31
+ if not isinstance(base_url, str) or re.search(r"[\s\\?#\x00-\x1f\x7f]", base_url):
32
+ raise ValueError("private-flow requires an HTTPS origin")
33
+ url = urlsplit(base_url)
34
+ if (
35
+ url.scheme != "https"
36
+ or not url.hostname
37
+ or url.username is not None
38
+ or url.password is not None
39
+ or url.path not in ("", "/")
40
+ or url.port == 0
41
+ ):
42
+ raise ValueError("private-flow requires an HTTPS origin")
43
+ return base_url.rstrip("/")
44
+
45
+
46
+ def _config(agent_token: str, base_url: str) -> dict:
47
+ if not isinstance(agent_token, str) or not re.fullmatch(
48
+ r"hs_prr_[A-Za-z0-9_-]{43}", agent_token
49
+ ):
50
+ raise ValueError("private-flow requires a server agent token")
51
+ return dict(
52
+ base_url=_origin(base_url),
53
+ headers={"Authorization": f"Bearer {agent_token}"},
54
+ follow_redirects=False,
55
+ trust_env=False,
56
+ timeout=10.0,
57
+ )
58
+
59
+
60
+ def _scope(
61
+ operation_id: str, subject_account: str, resource_account: str, resource_id: str
62
+ ) -> dict:
63
+ fields = dict(
64
+ operation_id=operation_id,
65
+ subject_account=subject_account,
66
+ resource_account=resource_account,
67
+ resource_id=resource_id,
68
+ )
69
+ if any(
70
+ not isinstance(v, str)
71
+ or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,127}", v)
72
+ for v in fields.values()
73
+ ):
74
+ raise ValueError("private-flow requires opaque identifiers")
75
+ return fields
76
+
77
+
78
+ def _uuid(value: Any) -> bool:
79
+ if not isinstance(value, str):
80
+ return False
81
+ try:
82
+ return str(UUID(value)) == value
83
+ except ValueError:
84
+ return False
85
+
86
+
87
+ def _timestamp(value: str) -> datetime:
88
+ if not isinstance(value, str):
89
+ raise ValueError
90
+ parsed = datetime.fromisoformat(
91
+ value[:-1] + "+00:00" if value.endswith("Z") else value
92
+ )
93
+ if parsed.utcoffset() is None:
94
+ raise ValueError
95
+ return parsed
96
+
97
+
98
+ def _digest(value: dict) -> str:
99
+ encoded = json.dumps(
100
+ value,
101
+ ensure_ascii=False,
102
+ sort_keys=True,
103
+ separators=(",", ":"),
104
+ allow_nan=False,
105
+ )
106
+ return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
107
+
108
+
109
+ def _envelope_matches(receipt: dict) -> bool:
110
+ signature, integrity = receipt["signature"], receipt["integrity"]
111
+ manifest = signature["manifest"]
112
+ signer = manifest["signer"]
113
+ digest = _digest(
114
+ {k: v for k, v in receipt.items() if k not in ("signature", "integrity")}
115
+ )
116
+ return (
117
+ signature["algorithm"] == "Ed25519"
118
+ and len(base64.b64decode(signature["value"], validate=True)) == 64
119
+ and manifest["schema_version"] == "haltstate.inline-proof-export.v1"
120
+ and manifest["export_id"] == receipt["receipt_id"]
121
+ and manifest["tenant_id"] == receipt["tenant_id"]
122
+ and integrity["evidence_mode"] == "signed"
123
+ and integrity["algorithm"] == "SHA-256"
124
+ and manifest["payload_sha256"] == digest == integrity["hash"]
125
+ and signature["hash"] == f"sha256:{digest}"
126
+ and signature["signed_at"] == receipt["generated_at"] == integrity["signed_at"]
127
+ and isinstance(signer["key_id"], str)
128
+ and bool(signer["key_id"].strip())
129
+ and signer["key_id"] == signature["signing_key_id"]
130
+ and re.fullmatch("[a-f0-9]{64}", signer["public_key_fingerprint"]) is not None
131
+ )
132
+
133
+
134
+ def _parse(response: httpx.Response, phase: str, payload: dict) -> PrivateFlowDecision:
135
+ if response.status_code != 200:
136
+ raise JanusError(f"private-flow request refused (HTTP {response.status_code})")
137
+ try:
138
+ data = response.json()
139
+ receipt = data["receipt"]
140
+ decision, identifier = data["decision"], data["receipt_id"]
141
+ proceed, replay = data["may_proceed"], data["replay"]
142
+ generated, expires = (
143
+ _timestamp(receipt["generated_at"]),
144
+ _timestamp(receipt["expires_at"]),
145
+ )
146
+ if not (
147
+ decision in ("ALLOW", "DENY")
148
+ and type(replay) is bool
149
+ and proceed is (decision == "ALLOW" and not replay)
150
+ and _uuid(identifier)
151
+ and identifier == receipt["receipt_id"] == receipt["export_id"]
152
+ and receipt["decision"] == decision
153
+ and receipt["phase"] == phase
154
+ and receipt["operation_id"] == payload["operation_id"]
155
+ and receipt["request_sha256"] == _digest(payload)
156
+ and receipt["reply_sha256"] == payload.get("reply_sha256")
157
+ and receipt["read_receipt_id"] == payload.get("read_receipt_id")
158
+ and receipt["schema_version"] == "haltstate.private-read-reply.v1"
159
+ and all(
160
+ isinstance(receipt[k], str) and receipt[k].strip()
161
+ for k in ("reason_code", "agent_id", "tenant_id")
162
+ )
163
+ and _envelope_matches(receipt)
164
+ and (not proceed or generated <= datetime.now(timezone.utc) < expires)
165
+ ):
166
+ raise ValueError
167
+ except (ValueError, TypeError, KeyError, OverflowError):
168
+ raise JanusError(
169
+ "private-flow response is invalid, unbound, or expired"
170
+ ) from None
171
+ # The HTTPS service is trusted here. Keep the entire signed object for independent key verification.
172
+ return PrivateFlowDecision(decision, proceed, identifier, receipt, replay)
173
+
174
+
175
+ _Result = TypeVar("_Result")
176
+
177
+
178
+ class _PrivateFlowRequests(Generic[_Result]):
179
+ def _post(self, phase: str, payload: dict) -> _Result:
180
+ raise NotImplementedError
181
+
182
+ def authorize_read(
183
+ self,
184
+ *,
185
+ operation_id: str,
186
+ subject_account: str,
187
+ resource_account: str,
188
+ resource_id: str,
189
+ ) -> _Result:
190
+ """Request authority before fetching private data. Never performs the read."""
191
+ return self._post(
192
+ "read", _scope(operation_id, subject_account, resource_account, resource_id)
193
+ )
194
+
195
+ def authorize_reply(
196
+ self,
197
+ *,
198
+ operation_id: str,
199
+ subject_account: str,
200
+ resource_account: str,
201
+ resource_id: str,
202
+ read_receipt_id: str,
203
+ reply_bytes: bytes,
204
+ ) -> _Result:
205
+ """Hash the final immutable bytes and authorize their release; never sends them."""
206
+ if not _uuid(read_receipt_id) or not isinstance(reply_bytes, bytes):
207
+ raise ValueError(
208
+ "private-flow requires a read receipt UUID and immutable reply bytes"
209
+ )
210
+ body = _scope(operation_id, subject_account, resource_account, resource_id)
211
+ body.update(
212
+ read_receipt_id=read_receipt_id,
213
+ reply_sha256=hashlib.sha256(reply_bytes).hexdigest(),
214
+ )
215
+ return self._post("reply", body)
216
+
217
+
218
+ _PATH = "/api/haltstate/private-flow/"
219
+
220
+
221
+ class PrivateFlowClient(_PrivateFlowRequests[PrivateFlowDecision]):
222
+ """Use as a context manager or call close(). Configure only a trusted server origin."""
223
+
224
+ def __init__(
225
+ self,
226
+ *,
227
+ agent_token: str,
228
+ base_url: str,
229
+ transport: Optional[httpx.BaseTransport] = None,
230
+ ):
231
+ self._http = httpx.Client(**_config(agent_token, base_url), transport=transport)
232
+
233
+ def __enter__(self):
234
+ return self
235
+
236
+ def __exit__(self, *args):
237
+ self.close()
238
+
239
+ def close(self) -> None:
240
+ self._http.close()
241
+
242
+ def _post(self, phase: str, payload: dict) -> PrivateFlowDecision:
243
+ try:
244
+ response = self._http.post(_PATH + phase, json=payload)
245
+ except httpx.HTTPError:
246
+ raise JanusError(
247
+ "private-flow transport unavailable; do not proceed"
248
+ ) from None
249
+ return _parse(response, phase, payload)
250
+
251
+
252
+ class AsyncPrivateFlowClient(_PrivateFlowRequests[Awaitable[PrivateFlowDecision]]):
253
+ """Use with async with or call aclose(); await authorize_read and authorize_reply."""
254
+
255
+ def __init__(
256
+ self,
257
+ *,
258
+ agent_token: str,
259
+ base_url: str,
260
+ transport: Optional[httpx.AsyncBaseTransport] = None,
261
+ ):
262
+ self._http = httpx.AsyncClient(
263
+ **_config(agent_token, base_url), transport=transport
264
+ )
265
+
266
+ async def __aenter__(self):
267
+ return self
268
+
269
+ async def __aexit__(self, *args):
270
+ await self.aclose()
271
+
272
+ async def aclose(self) -> None:
273
+ await self._http.aclose()
274
+
275
+ async def _post(self, phase: str, payload: dict) -> PrivateFlowDecision:
276
+ try:
277
+ response = await self._http.post(_PATH + phase, json=payload)
278
+ except httpx.HTTPError:
279
+ raise JanusError(
280
+ "private-flow transport unavailable; do not proceed"
281
+ ) from None
282
+ return _parse(response, phase, payload)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: haltstate-sdk
3
- Version: 0.8.0.dev1
3
+ Version: 0.8.0.dev2
4
4
  Summary: HaltState Python SDK - action control and Proof Packs for AI agents
5
5
  Author-email: Krystal Unity <support@krystalunity.com>
6
6
  License: MIT License
@@ -50,6 +50,14 @@ Dynamic: license-file
50
50
 
51
51
  [![PyPI](https://img.shields.io/pypi/v/haltstate-sdk.svg)](https://pypi.org/project/haltstate-sdk/)
52
52
 
53
+ ### Private reads and buffered replies
54
+
55
+ Use `PrivateFlowClient` or `AsyncPrivateFlowClient` on your application server.
56
+ Call `authorize_read` before fetching a private record and `authorize_reply`
57
+ with a distinct operation ID and the immutable bytes you will send. Proceed at
58
+ each gate only on `decision == "ALLOW" and may_proceed is True`. Replayed receipts
59
+ are evidence only. [Follow the setup and integration guide](https://haltstate.ai/haltstate/docs/private-read-and-reply).
60
+
53
61
  Action control and Proof Packs for autonomous AI agents. Perform pre-action checks, approvals, and post-action reporting with minimal code.
54
62
 
55
63
  ## Semiotic Probe (source candidate, not activated)
@@ -1,8 +1,10 @@
1
1
  LICENSE
2
2
  README.md
3
3
  pyproject.toml
4
+ setup.cfg
4
5
  haltstate/__init__.py
5
6
  haltstate/decorators.py
7
+ haltstate/private_flow.py
6
8
  haltstate_sdk.egg-info/PKG-INFO
7
9
  haltstate_sdk.egg-info/SOURCES.txt
8
10
  haltstate_sdk.egg-info/dependency_links.txt
@@ -19,4 +21,5 @@ janus/semiotic_probe.py
19
21
  tests/test_client.py
20
22
  tests/test_governed_message_capture.py
21
23
  tests/test_import.py
24
+ tests/test_private_flow.py
22
25
  tests/test_semiotic_probe.py
@@ -59,4 +59,4 @@ __all__ = [
59
59
  "KillSwitchTriggered",
60
60
  ]
61
61
 
62
- __version__ = "0.8.0.dev1" # Recording repair release candidate; not yet published
62
+ __version__ = "0.8.0.dev2"
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "haltstate-sdk"
7
- version = "0.8.0.dev1"
7
+ version = "0.8.0.dev2"
8
8
  description = "HaltState Python SDK - action control and Proof Packs for AI agents"
9
9
  readme = "README.md"
10
10
  authors = [{name = "Krystal Unity", email = "support@krystalunity.com"}]
@@ -0,0 +1,238 @@
1
+ import asyncio
2
+ import base64
3
+ import copy
4
+ import hashlib
5
+ import json
6
+
7
+ import httpx
8
+ import pytest
9
+
10
+ import haltstate
11
+
12
+
13
+ SCOPE = dict(
14
+ operation_id="op-1",
15
+ subject_account="acct-a",
16
+ resource_account="acct-a",
17
+ resource_id="res-1",
18
+ )
19
+ RID = "deab9555-9094-4799-8745-b23937234e1a"
20
+ TOKEN = "hs_prr_" + "q" * 43
21
+ SID = "45a96724-a536-4e2a-b49d-d2d3eeb1b325"
22
+ REPLY = b"\x00\xffreply\r\n"
23
+ REPLY_DIGEST = "e0e1fc0da40794c6ae1b8f9d330876b3f14bd3fc8d6d7cacf0a91c54479ccc6a"
24
+
25
+
26
+ def response(phase="read", decision="ALLOW", replay=False):
27
+ identifier = RID if phase == "read" else SID
28
+ receipt = dict(
29
+ schema_version="haltstate.private-read-reply.v1",
30
+ tenant_id="tenant-a",
31
+ agent_id="agent-a",
32
+ export_id=identifier,
33
+ receipt_id=identifier,
34
+ operation_id="op-1" if phase == "read" else "reply-1",
35
+ decision=decision,
36
+ phase=phase,
37
+ reason_code="test",
38
+ generated_at="2026-01-01T00:00:00+00:00",
39
+ expires_at="2099-01-01T00:00:00+00:00",
40
+ read_receipt_id=None if phase == "read" else RID,
41
+ reply_sha256=None if phase == "read" else REPLY_DIGEST,
42
+ request_sha256=(
43
+ "0eb9984b31ce72c865eb282f8d1bd7ba14c8616ef8cbcdd9b20c3a896bbe4b73"
44
+ if phase == "read"
45
+ else "f9027cb10ec450b12860491750dc919f6a8e36cc374cd19c1519f5a396c8d907"
46
+ ),
47
+ extra_evidence={"opaque": [1, 2]},
48
+ signature={
49
+ "algorithm": "Ed25519",
50
+ "value": base64.b64encode(bytes(range(64))).decode(),
51
+ "manifest": {
52
+ "schema_version": "haltstate.inline-proof-export.v1",
53
+ "export_id": identifier,
54
+ "tenant_id": "tenant-a",
55
+ },
56
+ },
57
+ integrity={"evidence_mode": "signed", "algorithm": "SHA-256"},
58
+ )
59
+ sign_shape(receipt)
60
+ return dict(
61
+ decision=decision,
62
+ receipt_id=identifier,
63
+ may_proceed=decision == "ALLOW" and not replay,
64
+ receipt=receipt,
65
+ replay=replay,
66
+ )
67
+
68
+
69
+ def sign_shape(receipt):
70
+ # Stand-in for the remote signer's envelope (verification keys are not SDK inputs).
71
+ digest = hashlib.sha256(
72
+ json.dumps(
73
+ {k: v for k, v in receipt.items() if k not in ("signature", "integrity")},
74
+ separators=(",", ":"),
75
+ sort_keys=True,
76
+ ).encode()
77
+ ).hexdigest()
78
+ receipt["signature"]["manifest"].update(
79
+ payload_sha256=digest,
80
+ signer={"key_id": "fixture", "public_key_fingerprint": "e" * 64},
81
+ )
82
+ receipt["signature"].update(
83
+ signing_key_id="fixture",
84
+ hash=f"sha256:{digest}",
85
+ signed_at=receipt["generated_at"],
86
+ )
87
+ receipt["integrity"].update(hash=digest, signed_at=receipt["generated_at"])
88
+
89
+
90
+ @pytest.fixture(params=[False, True], ids=["sync", "async"])
91
+ def invoke(request):
92
+ def call(handler, method="authorize_read", **fields):
93
+ arguments = dict(
94
+ agent_token=TOKEN,
95
+ base_url="https://haltstate.test/",
96
+ transport=httpx.MockTransport(handler),
97
+ )
98
+ params = {**SCOPE, **fields}
99
+ if request.param:
100
+
101
+ async def run():
102
+ async with haltstate.AsyncPrivateFlowClient(**arguments) as client:
103
+ return await getattr(client, method)(**params)
104
+
105
+ return asyncio.run(run())
106
+ with haltstate.PrivateFlowClient(**arguments) as client:
107
+ return getattr(client, method)(**params)
108
+
109
+ return call
110
+
111
+
112
+ @pytest.mark.parametrize("phase", ["read", "reply"])
113
+ def test_only_bound_metadata_sent_and_complete_receipt_preserved(invoke, phase):
114
+ body = response(phase)
115
+
116
+ def receive(req):
117
+ assert (
118
+ req.method == "POST"
119
+ and str(req.url)
120
+ == f"https://haltstate.test/api/haltstate/private-flow/{phase}"
121
+ )
122
+ assert req.headers["Authorization"] == f"Bearer {TOKEN}"
123
+ assert json.loads(req.content) == (
124
+ SCOPE
125
+ if phase == "read"
126
+ else dict(
127
+ SCOPE,
128
+ operation_id="reply-1",
129
+ read_receipt_id=RID,
130
+ reply_sha256=REPLY_DIGEST,
131
+ )
132
+ )
133
+ return httpx.Response(200, json=body)
134
+
135
+ kwargs = (
136
+ {}
137
+ if phase == "read"
138
+ else dict(operation_id="reply-1", read_receipt_id=RID, reply_bytes=REPLY)
139
+ )
140
+ result = invoke(receive, f"authorize_{phase}", **kwargs)
141
+ assert (result.decision, result.may_proceed, result.replay) == (
142
+ "ALLOW",
143
+ True,
144
+ False,
145
+ )
146
+ assert result.receipt_id == body["receipt_id"] and result.receipt == body["receipt"]
147
+
148
+
149
+ @pytest.mark.parametrize(
150
+ "decision,replay", [("ALLOW", True), ("DENY", True), ("DENY", False)]
151
+ )
152
+ def test_historical_allow_and_denial_are_evidence_only(invoke, decision, replay):
153
+ body = response(decision=decision, replay=replay)
154
+ body["receipt"]["expires_at"] = "2026-01-02T00:00:00Z"
155
+ sign_shape(body["receipt"])
156
+ result = invoke(lambda _: httpx.Response(200, json=body))
157
+ assert (
158
+ result.may_proceed is False
159
+ and result.replay is replay
160
+ and result.receipt == body["receipt"]
161
+ )
162
+
163
+
164
+ @pytest.mark.parametrize(
165
+ "path,bad",
166
+ [
167
+ ("decision", "DENY"),
168
+ ("receipt_id", SID),
169
+ ("may_proceed", "true"),
170
+ ("replay", True),
171
+ ("receipt.signature", {}),
172
+ ("receipt.signature.value", "abc"),
173
+ ("receipt.phase", "reply"),
174
+ ("receipt.operation_id", "another"),
175
+ ("receipt.request_sha256", "0" * 64),
176
+ ("receipt.read_receipt_id", RID),
177
+ ("receipt.reply_sha256", REPLY_DIGEST),
178
+ ("receipt.integrity", {}),
179
+ ("receipt.expires_at", "2000-01-01T00:00:00Z"),
180
+ ("receipt.signature.manifest.payload_sha256", "d" * 64),
181
+ ("receipt.signature.signing_key_id", ""),
182
+ ("receipt.extra_evidence", {"substituted": True}),
183
+ ],
184
+ )
185
+ def test_fails_closed_on_malformed_mismatched_or_stale_response(invoke, path, bad):
186
+ body = copy.deepcopy(response())
187
+ target = body
188
+ *parts, name = path.split(".")
189
+ for part in parts:
190
+ target = target[part]
191
+ target[name] = bad
192
+ with pytest.raises(haltstate.HaltStateError):
193
+ invoke(lambda _: httpx.Response(200, json=body))
194
+
195
+
196
+ @pytest.mark.parametrize("failure", ["redirect", "timeout", "json", "unauthorized"])
197
+ def test_one_request_no_redirect_retry_or_error_body_disclosure(invoke, failure):
198
+ seen = []
199
+
200
+ def receive(req):
201
+ seen.append(str(req.url))
202
+ if failure == "redirect":
203
+ return httpx.Response(
204
+ 307, headers={"Location": "https://other.invalid/private"}
205
+ )
206
+ if failure == "timeout":
207
+ raise httpx.ReadTimeout("private upstream detail", request=req)
208
+ return httpx.Response(
209
+ 200 if failure == "json" else 401, content=b"private upstream detail"
210
+ )
211
+
212
+ with pytest.raises(haltstate.HaltStateError) as err:
213
+ invoke(receive)
214
+ assert "private upstream detail" not in str(err.value)
215
+ assert seen == ["https://haltstate.test/api/haltstate/private-flow/read"]
216
+
217
+
218
+ @pytest.mark.parametrize(
219
+ "url",
220
+ [
221
+ "http://haltstate.test",
222
+ "https://user@haltstate.test",
223
+ "https://host/path",
224
+ "https://host?x=y",
225
+ "https://host/#frag",
226
+ "https://host\\@other.test",
227
+ ],
228
+ )
229
+ def test_requires_an_explicit_trusted_https_origin(url):
230
+ with pytest.raises(ValueError):
231
+ haltstate.PrivateFlowClient(base_url=url, agent_token=TOKEN)
232
+
233
+
234
+ def test_rejects_general_tenant_or_owner_credential_before_transport():
235
+ with pytest.raises(ValueError):
236
+ haltstate.PrivateFlowClient(
237
+ base_url="https://haltstate.test", agent_token="different-server-secret"
238
+ )