retvest-ril 0.3.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.
- retvest_ril-0.3.0/PKG-INFO +9 -0
- retvest_ril-0.3.0/pyproject.toml +19 -0
- retvest_ril-0.3.0/retvest_ril.egg-info/PKG-INFO +9 -0
- retvest_ril-0.3.0/retvest_ril.egg-info/SOURCES.txt +10 -0
- retvest_ril-0.3.0/retvest_ril.egg-info/dependency_links.txt +1 -0
- retvest_ril-0.3.0/retvest_ril.egg-info/top_level.txt +1 -0
- retvest_ril-0.3.0/ril_sdk/__init__.py +25 -0
- retvest_ril-0.3.0/ril_sdk/agent.py +229 -0
- retvest_ril-0.3.0/ril_sdk/client.py +209 -0
- retvest_ril-0.3.0/setup.cfg +4 -0
- retvest_ril-0.3.0/tests/test_agent.py +319 -0
- retvest_ril-0.3.0/tests/test_ril_sdk.py +127 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: retvest-ril
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Zero-dependency Python SDK for the RIL (Retvest Intent Language) verifier CLI
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Project-URL: Homepage, https://github.com/retvest/RIL
|
|
7
|
+
Project-URL: Repository, https://github.com/retvest/RIL
|
|
8
|
+
Project-URL: Documentation, https://github.com/retvest/RIL/blob/main/docs/RIL-SPEC-0.3.md
|
|
9
|
+
Requires-Python: >=3.10
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "retvest-ril"
|
|
7
|
+
version = "0.3.0"
|
|
8
|
+
description = "Zero-dependency Python SDK for the RIL (Retvest Intent Language) verifier CLI"
|
|
9
|
+
license = { text = "Apache-2.0" }
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
dependencies = []
|
|
12
|
+
|
|
13
|
+
[project.urls]
|
|
14
|
+
Homepage = "https://github.com/retvest/RIL"
|
|
15
|
+
Repository = "https://github.com/retvest/RIL"
|
|
16
|
+
Documentation = "https://github.com/retvest/RIL/blob/main/docs/RIL-SPEC-0.3.md"
|
|
17
|
+
|
|
18
|
+
[tool.setuptools]
|
|
19
|
+
packages = ["ril_sdk"]
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: retvest-ril
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Zero-dependency Python SDK for the RIL (Retvest Intent Language) verifier CLI
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Project-URL: Homepage, https://github.com/retvest/RIL
|
|
7
|
+
Project-URL: Repository, https://github.com/retvest/RIL
|
|
8
|
+
Project-URL: Documentation, https://github.com/retvest/RIL/blob/main/docs/RIL-SPEC-0.3.md
|
|
9
|
+
Requires-Python: >=3.10
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
pyproject.toml
|
|
2
|
+
retvest_ril.egg-info/PKG-INFO
|
|
3
|
+
retvest_ril.egg-info/SOURCES.txt
|
|
4
|
+
retvest_ril.egg-info/dependency_links.txt
|
|
5
|
+
retvest_ril.egg-info/top_level.txt
|
|
6
|
+
ril_sdk/__init__.py
|
|
7
|
+
ril_sdk/agent.py
|
|
8
|
+
ril_sdk/client.py
|
|
9
|
+
tests/test_agent.py
|
|
10
|
+
tests/test_ril_sdk.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ril_sdk
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""retvest-ril: zero-dependency Python SDK for the `ril` CLI."""
|
|
2
|
+
from .agent import RilApprovalRequiredError, RilDeniedError, RilToolGuard, ril_govern
|
|
3
|
+
from .client import (
|
|
4
|
+
RilCheckResult,
|
|
5
|
+
RilClient,
|
|
6
|
+
RilDiagnostic,
|
|
7
|
+
RilError,
|
|
8
|
+
RilTestCase,
|
|
9
|
+
RilTestResult,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
__version__ = "0.3.0"
|
|
13
|
+
__all__ = [
|
|
14
|
+
"RilClient",
|
|
15
|
+
"RilError",
|
|
16
|
+
"RilCheckResult",
|
|
17
|
+
"RilTestResult",
|
|
18
|
+
"RilDiagnostic",
|
|
19
|
+
"RilTestCase",
|
|
20
|
+
"RilDeniedError",
|
|
21
|
+
"RilApprovalRequiredError",
|
|
22
|
+
"ril_govern",
|
|
23
|
+
"RilToolGuard",
|
|
24
|
+
"__version__",
|
|
25
|
+
]
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"""AI Agent Framework Middleware — zero-dependency governance for AI tool calls."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import functools
|
|
5
|
+
import inspect
|
|
6
|
+
from typing import Any, Callable, TypeVar, cast
|
|
7
|
+
|
|
8
|
+
from .client import RilClient
|
|
9
|
+
|
|
10
|
+
F = TypeVar("F", bound=Callable[..., Any])
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class RilDeniedError(Exception):
|
|
14
|
+
"""Raised when an action is denied by RIL governance."""
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
verdict: str,
|
|
19
|
+
action: str,
|
|
20
|
+
reason: str,
|
|
21
|
+
matched_law: str | None,
|
|
22
|
+
decision: dict[str, Any],
|
|
23
|
+
):
|
|
24
|
+
super().__init__(f'Action "{action}" was denied by RIL: {reason}')
|
|
25
|
+
self.verdict = verdict
|
|
26
|
+
self.action = action
|
|
27
|
+
self.reason = reason
|
|
28
|
+
self.matched_law = matched_law
|
|
29
|
+
self.decision = decision
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class RilApprovalRequiredError(Exception):
|
|
33
|
+
"""Raised when an action requires approval."""
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
verdict: str,
|
|
38
|
+
action: str,
|
|
39
|
+
reason: str,
|
|
40
|
+
matched_law: str | None,
|
|
41
|
+
decision: dict[str, Any],
|
|
42
|
+
):
|
|
43
|
+
super().__init__(f'Action "{action}" requires approval: {reason}')
|
|
44
|
+
self.verdict = verdict
|
|
45
|
+
self.action = action
|
|
46
|
+
self.reason = reason
|
|
47
|
+
self.matched_law = matched_law
|
|
48
|
+
self.decision = decision
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def ril_govern(
|
|
52
|
+
client: RilClient,
|
|
53
|
+
law_file: str,
|
|
54
|
+
action: str,
|
|
55
|
+
*,
|
|
56
|
+
actor: str | None = None,
|
|
57
|
+
map_context: Callable[..., dict[str, Any]] | None = None,
|
|
58
|
+
on_ask: Callable[[dict[str, Any], tuple[Any, ...]], bool] | None = None,
|
|
59
|
+
on_decision: Callable[[dict[str, Any], tuple[Any, ...]], None] | None = None,
|
|
60
|
+
) -> Callable[[F], F]:
|
|
61
|
+
"""
|
|
62
|
+
Decorator to govern a function with RIL. Works on both sync and async functions.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
client: RIL client instance
|
|
66
|
+
law_file: Path to the .ril law file
|
|
67
|
+
action: Action name to evaluate
|
|
68
|
+
actor: Principal actor (defaults to Agent:ai)
|
|
69
|
+
map_context: Maps function args to context dict
|
|
70
|
+
on_ask: Called when verdict is "ask"; returns bool (sync or async)
|
|
71
|
+
on_decision: Called with decision after evaluation (sync or async)
|
|
72
|
+
|
|
73
|
+
Example:
|
|
74
|
+
@ril_govern(client, "laws.ril", "execute_code")
|
|
75
|
+
def run_code(code: str):
|
|
76
|
+
exec(code)
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
def decorator(fn: F) -> F:
|
|
80
|
+
is_async = inspect.iscoroutinefunction(fn)
|
|
81
|
+
|
|
82
|
+
if is_async:
|
|
83
|
+
|
|
84
|
+
@functools.wraps(fn)
|
|
85
|
+
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
86
|
+
context = map_context(*args, **kwargs) if map_context else {}
|
|
87
|
+
|
|
88
|
+
# Evaluate the action
|
|
89
|
+
decision = client.evaluate(
|
|
90
|
+
law_file,
|
|
91
|
+
action,
|
|
92
|
+
actor=actor or "Agent:ai",
|
|
93
|
+
context=context,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
# Invoke onDecision callback if provided
|
|
97
|
+
if on_decision:
|
|
98
|
+
result = on_decision(decision, args)
|
|
99
|
+
if inspect.iscoroutine(result):
|
|
100
|
+
await result
|
|
101
|
+
|
|
102
|
+
verdict = decision["verdict"]
|
|
103
|
+
laws = decision.get("laws", [])
|
|
104
|
+
reason = f"matched law(s): {', '.join(laws)}" if laws else "no matching laws"
|
|
105
|
+
matched_law = laws[0] if laws else None
|
|
106
|
+
|
|
107
|
+
if verdict == "allow":
|
|
108
|
+
return await fn(*args, **kwargs)
|
|
109
|
+
|
|
110
|
+
if verdict == "deny":
|
|
111
|
+
raise RilDeniedError(verdict, action, reason, matched_law, decision)
|
|
112
|
+
|
|
113
|
+
# "hold" is RIL's verdict for "ask"
|
|
114
|
+
if verdict == "hold":
|
|
115
|
+
if on_ask:
|
|
116
|
+
approval = on_ask(decision, args)
|
|
117
|
+
if inspect.iscoroutine(approval):
|
|
118
|
+
approval = await approval
|
|
119
|
+
if approval:
|
|
120
|
+
return await fn(*args, **kwargs)
|
|
121
|
+
raise RilApprovalRequiredError("ask", action, reason, matched_law, decision)
|
|
122
|
+
|
|
123
|
+
raise ValueError(f"Unknown verdict: {verdict}")
|
|
124
|
+
|
|
125
|
+
return cast(F, async_wrapper)
|
|
126
|
+
else:
|
|
127
|
+
|
|
128
|
+
@functools.wraps(fn)
|
|
129
|
+
def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
130
|
+
context = map_context(*args, **kwargs) if map_context else {}
|
|
131
|
+
|
|
132
|
+
# Evaluate the action
|
|
133
|
+
decision = client.evaluate(
|
|
134
|
+
law_file,
|
|
135
|
+
action,
|
|
136
|
+
actor=actor or "Agent:ai",
|
|
137
|
+
context=context,
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
# Invoke onDecision callback if provided
|
|
141
|
+
if on_decision:
|
|
142
|
+
result = on_decision(decision, args)
|
|
143
|
+
if inspect.iscoroutine(result):
|
|
144
|
+
raise TypeError("on_decision returned a coroutine but function is not async")
|
|
145
|
+
|
|
146
|
+
verdict = decision["verdict"]
|
|
147
|
+
laws = decision.get("laws", [])
|
|
148
|
+
reason = f"matched law(s): {', '.join(laws)}" if laws else "no matching laws"
|
|
149
|
+
matched_law = laws[0] if laws else None
|
|
150
|
+
|
|
151
|
+
if verdict == "allow":
|
|
152
|
+
return fn(*args, **kwargs)
|
|
153
|
+
|
|
154
|
+
if verdict == "deny":
|
|
155
|
+
raise RilDeniedError(verdict, action, reason, matched_law, decision)
|
|
156
|
+
|
|
157
|
+
# "hold" is RIL's verdict for "ask"
|
|
158
|
+
if verdict == "hold":
|
|
159
|
+
if on_ask:
|
|
160
|
+
approval = on_ask(decision, args)
|
|
161
|
+
if inspect.iscoroutine(approval):
|
|
162
|
+
raise TypeError("on_ask returned a coroutine but function is not async")
|
|
163
|
+
if approval:
|
|
164
|
+
return fn(*args, **kwargs)
|
|
165
|
+
raise RilApprovalRequiredError("ask", action, reason, matched_law, decision)
|
|
166
|
+
|
|
167
|
+
raise ValueError(f"Unknown verdict: {verdict}")
|
|
168
|
+
|
|
169
|
+
return cast(F, sync_wrapper)
|
|
170
|
+
|
|
171
|
+
return decorator
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class RilToolGuard:
|
|
175
|
+
"""
|
|
176
|
+
Helper for governing multiple tools with RIL.
|
|
177
|
+
|
|
178
|
+
Example:
|
|
179
|
+
guard = RilToolGuard(client, "laws.ril", action_prefix="tools")
|
|
180
|
+
tools = {
|
|
181
|
+
"read_file": read_file,
|
|
182
|
+
"write_file": write_file,
|
|
183
|
+
}
|
|
184
|
+
governed_tools = guard.wrap_all(tools)
|
|
185
|
+
"""
|
|
186
|
+
|
|
187
|
+
def __init__(
|
|
188
|
+
self,
|
|
189
|
+
client: RilClient,
|
|
190
|
+
law_file: str,
|
|
191
|
+
*,
|
|
192
|
+
actor: str | None = None,
|
|
193
|
+
action_prefix: str | None = None,
|
|
194
|
+
on_ask: Callable[[dict[str, Any], tuple[Any, ...]], bool] | None = None,
|
|
195
|
+
on_decision: Callable[[dict[str, Any], tuple[Any, ...]], None] | None = None,
|
|
196
|
+
):
|
|
197
|
+
self.client = client
|
|
198
|
+
self.law_file = law_file
|
|
199
|
+
self.actor = actor
|
|
200
|
+
self.action_prefix = action_prefix
|
|
201
|
+
self.on_ask = on_ask
|
|
202
|
+
self.on_decision = on_decision
|
|
203
|
+
|
|
204
|
+
def wrap(
|
|
205
|
+
self,
|
|
206
|
+
fn: F,
|
|
207
|
+
action: str | None = None,
|
|
208
|
+
map_context: Callable[..., dict[str, Any]] | None = None,
|
|
209
|
+
) -> F:
|
|
210
|
+
"""Wrap a single function with RIL governance."""
|
|
211
|
+
if action is None:
|
|
212
|
+
action = fn.__name__
|
|
213
|
+
return ril_govern(
|
|
214
|
+
self.client,
|
|
215
|
+
self.law_file,
|
|
216
|
+
action,
|
|
217
|
+
actor=self.actor,
|
|
218
|
+
map_context=map_context,
|
|
219
|
+
on_ask=self.on_ask,
|
|
220
|
+
on_decision=self.on_decision,
|
|
221
|
+
)(fn)
|
|
222
|
+
|
|
223
|
+
def wrap_all(self, tools: dict[str, Callable[..., Any]]) -> dict[str, Callable[..., Any]]:
|
|
224
|
+
"""Wrap a dictionary of tools with RIL governance."""
|
|
225
|
+
wrapped = {}
|
|
226
|
+
for name, fn in tools.items():
|
|
227
|
+
action = f"{self.action_prefix}.{name}" if self.action_prefix else name
|
|
228
|
+
wrapped[name] = self.wrap(fn, action=action)
|
|
229
|
+
return wrapped
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
"""Typed wrapper around the `ril` command line. Standard library only."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import base64
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import subprocess
|
|
9
|
+
import tempfile
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
# ASN.1 SubjectPublicKeyInfo prefix for a raw Ed25519 public key.
|
|
14
|
+
_ED25519_SPKI_PREFIX = bytes.fromhex("302a300506032b6570032100")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class RilError(RuntimeError):
|
|
18
|
+
"""The CLI could not be run or produced no structured result."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, message: str, stdout: str = "", stderr: str = "", status: int | None = None):
|
|
21
|
+
super().__init__(message)
|
|
22
|
+
self.stdout = stdout
|
|
23
|
+
self.stderr = stderr
|
|
24
|
+
self.status = status
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class RilDiagnostic:
|
|
29
|
+
kind: str
|
|
30
|
+
message: str
|
|
31
|
+
line: int | None = None
|
|
32
|
+
column: int | None = None
|
|
33
|
+
hint: str | None = None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class RilTestCase:
|
|
38
|
+
id: str
|
|
39
|
+
law: str
|
|
40
|
+
verdict: str
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class RilCheckResult:
|
|
45
|
+
ok: bool
|
|
46
|
+
name: str | None = None
|
|
47
|
+
version: int | None = None
|
|
48
|
+
digest: str | None = None
|
|
49
|
+
laws: int | None = None
|
|
50
|
+
promises: int | None = None
|
|
51
|
+
machines: list[dict[str, Any]] = field(default_factory=list)
|
|
52
|
+
proofs: list[dict[str, Any]] = field(default_factory=list)
|
|
53
|
+
tests: list[RilTestCase] = field(default_factory=list)
|
|
54
|
+
diagnostics: list[RilDiagnostic] = field(default_factory=list)
|
|
55
|
+
raw: dict[str, Any] = field(default_factory=dict)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class RilTestResult:
|
|
60
|
+
ok: bool
|
|
61
|
+
passed: int = 0
|
|
62
|
+
tests: list[RilTestCase] = field(default_factory=list)
|
|
63
|
+
diagnostics: list[RilDiagnostic] = field(default_factory=list)
|
|
64
|
+
raw: dict[str, Any] = field(default_factory=dict)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _diagnostics(raw: dict[str, Any]) -> list[RilDiagnostic]:
|
|
68
|
+
return [
|
|
69
|
+
RilDiagnostic(
|
|
70
|
+
kind=d.get("kind", ""),
|
|
71
|
+
message=d.get("message", ""),
|
|
72
|
+
line=d.get("line"),
|
|
73
|
+
column=d.get("column"),
|
|
74
|
+
hint=d.get("hint"),
|
|
75
|
+
)
|
|
76
|
+
for d in raw.get("diagnostics", [])
|
|
77
|
+
]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _tests(raw: dict[str, Any]) -> list[RilTestCase]:
|
|
81
|
+
return [RilTestCase(id=t["id"], law=t["law"], verdict=t["verdict"]) for t in raw.get("tests", [])]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class RilClient:
|
|
85
|
+
def __init__(self, bin_path: str = "ril"):
|
|
86
|
+
self.bin_path = bin_path
|
|
87
|
+
|
|
88
|
+
def _run(self, args: list[str]) -> subprocess.CompletedProcess[str]:
|
|
89
|
+
try:
|
|
90
|
+
return subprocess.run(
|
|
91
|
+
[self.bin_path, *args], capture_output=True, text=True, check=False
|
|
92
|
+
)
|
|
93
|
+
except OSError as exc:
|
|
94
|
+
raise RilError(f"cannot run `{self.bin_path}`: {exc}") from exc
|
|
95
|
+
|
|
96
|
+
def _run_json(self, cmd: str, file_path: str) -> dict[str, Any]:
|
|
97
|
+
# Exit 1 with a JSON body is a normal verification failure, not an exception.
|
|
98
|
+
r = self._run([cmd, os.fspath(file_path), "--json"])
|
|
99
|
+
try:
|
|
100
|
+
raw = json.loads(r.stdout)
|
|
101
|
+
except json.JSONDecodeError as exc:
|
|
102
|
+
raise RilError(
|
|
103
|
+
f"ril {cmd}: no JSON on stdout (exit {r.returncode}): {r.stderr or r.stdout}",
|
|
104
|
+
r.stdout, r.stderr, r.returncode,
|
|
105
|
+
) from exc
|
|
106
|
+
return raw
|
|
107
|
+
|
|
108
|
+
def check(self, file_path: str) -> RilCheckResult:
|
|
109
|
+
raw = self._run_json("check", file_path)
|
|
110
|
+
return RilCheckResult(
|
|
111
|
+
ok=raw.get("ok") is True,
|
|
112
|
+
name=raw.get("name"),
|
|
113
|
+
version=raw.get("version"),
|
|
114
|
+
digest=raw.get("digest"),
|
|
115
|
+
laws=raw.get("laws"),
|
|
116
|
+
promises=raw.get("promises"),
|
|
117
|
+
machines=raw.get("machines", []),
|
|
118
|
+
proofs=raw.get("proofs", []),
|
|
119
|
+
tests=_tests(raw),
|
|
120
|
+
diagnostics=_diagnostics(raw),
|
|
121
|
+
raw=raw,
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
def test(self, file_path: str) -> RilTestResult:
|
|
125
|
+
raw = self._run_json("test", file_path)
|
|
126
|
+
return RilTestResult(
|
|
127
|
+
ok=raw.get("ok") is True,
|
|
128
|
+
passed=raw.get("passed", 0),
|
|
129
|
+
tests=_tests(raw),
|
|
130
|
+
diagnostics=_diagnostics(raw),
|
|
131
|
+
raw=raw,
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
def codegen(self, file_path: str, lang: str = "ts", out_path: str | None = None) -> str:
|
|
135
|
+
args = ["codegen", os.fspath(file_path), "--lang", lang]
|
|
136
|
+
if out_path:
|
|
137
|
+
args += ["--out", os.fspath(out_path)]
|
|
138
|
+
r = self._run(args)
|
|
139
|
+
if r.returncode != 0:
|
|
140
|
+
raise RilError(f"ril codegen failed: {r.stderr.strip()}", r.stdout, r.stderr, r.returncode)
|
|
141
|
+
if out_path:
|
|
142
|
+
with open(out_path, encoding="utf-8") as fh:
|
|
143
|
+
return fh.read()
|
|
144
|
+
return r.stdout
|
|
145
|
+
|
|
146
|
+
def spec(self) -> str:
|
|
147
|
+
r = self._run(["spec"])
|
|
148
|
+
if r.returncode != 0:
|
|
149
|
+
raise RilError(f"ril spec failed: {r.stderr.strip()}", r.stdout, r.stderr, r.returncode)
|
|
150
|
+
return r.stdout
|
|
151
|
+
|
|
152
|
+
def verify_receipt(self, receipt_path: str, public_key_hex: str) -> tuple[bool, str]:
|
|
153
|
+
"""`public_key_hex`: 64 hex chars (raw Ed25519), PEM text, or a PEM file path."""
|
|
154
|
+
key = public_key_hex.strip()
|
|
155
|
+
with tempfile.TemporaryDirectory(prefix="ril-sdk-") as tmp:
|
|
156
|
+
key_path = key
|
|
157
|
+
if re.fullmatch(r"[0-9a-fA-F]{64}", key):
|
|
158
|
+
der = _ED25519_SPKI_PREFIX + bytes.fromhex(key)
|
|
159
|
+
pem = "-----BEGIN PUBLIC KEY-----\n" + base64.b64encode(der).decode() + "\n-----END PUBLIC KEY-----\n"
|
|
160
|
+
elif "BEGIN PUBLIC KEY" in key:
|
|
161
|
+
pem = key + "\n"
|
|
162
|
+
elif os.path.exists(key):
|
|
163
|
+
pem = None
|
|
164
|
+
else:
|
|
165
|
+
raise RilError("public_key_hex must be 64 hex chars, PEM text, or a PEM file path")
|
|
166
|
+
if pem is not None:
|
|
167
|
+
key_path = os.path.join(tmp, "seal.pub.pem")
|
|
168
|
+
with open(key_path, "w", encoding="utf-8") as fh:
|
|
169
|
+
fh.write(pem)
|
|
170
|
+
r = self._run(["verify-receipt", os.fspath(receipt_path), "--public-key", key_path])
|
|
171
|
+
return r.returncode == 0, (r.stdout + r.stderr).strip()
|
|
172
|
+
|
|
173
|
+
def evaluate(
|
|
174
|
+
self,
|
|
175
|
+
law_file: str,
|
|
176
|
+
action: str,
|
|
177
|
+
*,
|
|
178
|
+
actor: str = "Agent:ai",
|
|
179
|
+
resource: str = "Resource:default",
|
|
180
|
+
context: dict[str, Any] | None = None,
|
|
181
|
+
entities: list[str] | None = None,
|
|
182
|
+
) -> dict[str, Any]:
|
|
183
|
+
"""Evaluate an action against a law file."""
|
|
184
|
+
args = ["laws", "eval", os.fspath(law_file), "--action", action, "--resource", resource, "--principal", actor]
|
|
185
|
+
|
|
186
|
+
if context:
|
|
187
|
+
args += ["--context", json.dumps(context)]
|
|
188
|
+
|
|
189
|
+
for entity in entities or []:
|
|
190
|
+
args += ["--entity", entity]
|
|
191
|
+
|
|
192
|
+
args.append("--json")
|
|
193
|
+
|
|
194
|
+
r = self._run(args)
|
|
195
|
+
try:
|
|
196
|
+
raw = json.loads(r.stdout)
|
|
197
|
+
except json.JSONDecodeError as exc:
|
|
198
|
+
raise RilError(
|
|
199
|
+
f"ril laws eval: no JSON on stdout (exit {r.returncode}): {r.stderr or r.stdout}",
|
|
200
|
+
r.stdout, r.stderr, r.returncode,
|
|
201
|
+
) from exc
|
|
202
|
+
|
|
203
|
+
return {
|
|
204
|
+
"verdict": raw.get("verdict", "deny"),
|
|
205
|
+
"laws": raw.get("laws", []),
|
|
206
|
+
"errors": raw.get("errors", {}),
|
|
207
|
+
"law_set_digest": raw.get("law_set_digest", ""),
|
|
208
|
+
"raw": raw,
|
|
209
|
+
}
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
import unittest
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
8
|
+
from ril_sdk import RilApprovalRequiredError, RilClient, RilDeniedError, RilToolGuard, ril_govern # noqa: E402
|
|
9
|
+
|
|
10
|
+
ROOT = Path(__file__).resolve().parents[3]
|
|
11
|
+
BIN = next(
|
|
12
|
+
(
|
|
13
|
+
p
|
|
14
|
+
for p in [
|
|
15
|
+
os.environ.get("RIL_BIN"),
|
|
16
|
+
str(ROOT / "ril-core/target/debug/ril"),
|
|
17
|
+
str(ROOT / "ril-core/target/release/ril"),
|
|
18
|
+
]
|
|
19
|
+
if p and os.path.exists(p)
|
|
20
|
+
),
|
|
21
|
+
None,
|
|
22
|
+
)
|
|
23
|
+
LAW_FILE = str(ROOT / "sdks/fixtures/agent-test.ril")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def make_client_with_evaluate(ril_client, evaluate_override):
|
|
27
|
+
"""Create a client with a custom evaluate function."""
|
|
28
|
+
client = RilClient(ril_client.bin_path)
|
|
29
|
+
client.evaluate = evaluate_override
|
|
30
|
+
return client
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@unittest.skipUnless(BIN, "ril binary not built (cargo build --manifest-path ril-core/Cargo.toml)")
|
|
34
|
+
class RilAgentTest(unittest.TestCase):
|
|
35
|
+
def setUp(self):
|
|
36
|
+
self.ril = RilClient(BIN)
|
|
37
|
+
self.executed = False
|
|
38
|
+
self.decision_received = None
|
|
39
|
+
|
|
40
|
+
def test_sync_allowed_action_executes(self):
|
|
41
|
+
"""Synchronous allowed tool executes and returns value."""
|
|
42
|
+
|
|
43
|
+
def read_safe_file(filename):
|
|
44
|
+
self.executed = True
|
|
45
|
+
return f"contents of {filename}"
|
|
46
|
+
|
|
47
|
+
def eval_override(law_file, action, **kwargs):
|
|
48
|
+
return self.ril.evaluate(
|
|
49
|
+
law_file, "read", resource="File:test.txt", entities=['File:test.txt={"safe":true}']
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
client = make_client_with_evaluate(self.ril, eval_override)
|
|
53
|
+
governed = ril_govern(client, LAW_FILE, "read")(read_safe_file)
|
|
54
|
+
result = governed("test.txt")
|
|
55
|
+
|
|
56
|
+
self.assertEqual(result, "contents of test.txt")
|
|
57
|
+
self.assertTrue(self.executed, "wrapped function should have executed")
|
|
58
|
+
|
|
59
|
+
def test_async_allowed_action_executes(self):
|
|
60
|
+
"""Asynchronous allowed tool executes and returns value."""
|
|
61
|
+
|
|
62
|
+
async def read_safe_file_async(filename):
|
|
63
|
+
self.executed = True
|
|
64
|
+
await asyncio.sleep(0.001)
|
|
65
|
+
return f"contents of {filename}"
|
|
66
|
+
|
|
67
|
+
def eval_override(law_file, action, **kwargs):
|
|
68
|
+
return self.ril.evaluate(
|
|
69
|
+
law_file, "read", resource="File:test.txt", entities=['File:test.txt={"safe":true}']
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
client = make_client_with_evaluate(self.ril, eval_override)
|
|
73
|
+
governed = ril_govern(client, LAW_FILE, "read")(read_safe_file_async)
|
|
74
|
+
result = asyncio.run(governed("test.txt"))
|
|
75
|
+
|
|
76
|
+
self.assertEqual(result, "contents of test.txt")
|
|
77
|
+
self.assertTrue(self.executed, "wrapped function should have executed")
|
|
78
|
+
|
|
79
|
+
def test_sync_denied_action_raises_and_prevents_execution(self):
|
|
80
|
+
"""Synchronous denied tool raises RilDeniedError and proves side-effect never ran."""
|
|
81
|
+
|
|
82
|
+
def write_dangerous_file(filename, content):
|
|
83
|
+
self.executed = True
|
|
84
|
+
return f"wrote {content} to {filename}"
|
|
85
|
+
|
|
86
|
+
def eval_override(law_file, action, **kwargs):
|
|
87
|
+
return self.ril.evaluate(
|
|
88
|
+
law_file, "write", resource="File:danger.sh", entities=['File:danger.sh={"dangerous":true}']
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
client = make_client_with_evaluate(self.ril, eval_override)
|
|
92
|
+
governed = ril_govern(client, LAW_FILE, "write")(write_dangerous_file)
|
|
93
|
+
|
|
94
|
+
with self.assertRaises(RilDeniedError) as ctx:
|
|
95
|
+
governed("danger.sh", "rm -rf /")
|
|
96
|
+
|
|
97
|
+
self.assertEqual(ctx.exception.verdict, "deny")
|
|
98
|
+
self.assertEqual(ctx.exception.action, "write")
|
|
99
|
+
self.assertIsNotNone(ctx.exception.matched_law)
|
|
100
|
+
self.assertFalse(self.executed, "wrapped function should NOT have executed")
|
|
101
|
+
|
|
102
|
+
def test_async_denied_action_raises_and_prevents_execution(self):
|
|
103
|
+
"""Asynchronous denied tool raises RilDeniedError and proves side-effect never ran."""
|
|
104
|
+
|
|
105
|
+
async def write_dangerous_file_async(filename, content):
|
|
106
|
+
self.executed = True
|
|
107
|
+
await asyncio.sleep(0.001)
|
|
108
|
+
return f"wrote {content} to {filename}"
|
|
109
|
+
|
|
110
|
+
def eval_override(law_file, action, **kwargs):
|
|
111
|
+
return self.ril.evaluate(
|
|
112
|
+
law_file, "write", resource="File:danger.sh", entities=['File:danger.sh={"dangerous":true}']
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
client = make_client_with_evaluate(self.ril, eval_override)
|
|
116
|
+
governed = ril_govern(client, LAW_FILE, "write")(write_dangerous_file_async)
|
|
117
|
+
|
|
118
|
+
with self.assertRaises(RilDeniedError):
|
|
119
|
+
asyncio.run(governed("danger.sh", "rm -rf /"))
|
|
120
|
+
|
|
121
|
+
self.assertFalse(self.executed, "wrapped function should NOT have executed")
|
|
122
|
+
|
|
123
|
+
def test_sync_ask_without_on_ask_raises_approval_required(self):
|
|
124
|
+
"""ask tool without on_ask raises RilApprovalRequiredError and side-effect never runs."""
|
|
125
|
+
|
|
126
|
+
def access_sensitive(data_id):
|
|
127
|
+
self.executed = True
|
|
128
|
+
return f"accessed {data_id}"
|
|
129
|
+
|
|
130
|
+
def eval_override(law_file, action, **kwargs):
|
|
131
|
+
return self.ril.evaluate(
|
|
132
|
+
law_file, "access", resource="Data:secrets", entities=['Data:secrets={"sensitive":true}']
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
client = make_client_with_evaluate(self.ril, eval_override)
|
|
136
|
+
governed = ril_govern(client, LAW_FILE, "access")(access_sensitive)
|
|
137
|
+
|
|
138
|
+
with self.assertRaises(RilApprovalRequiredError) as ctx:
|
|
139
|
+
governed("secrets")
|
|
140
|
+
|
|
141
|
+
self.assertEqual(ctx.exception.verdict, "ask")
|
|
142
|
+
self.assertEqual(ctx.exception.action, "access")
|
|
143
|
+
self.assertFalse(self.executed, "wrapped function should NOT have executed")
|
|
144
|
+
|
|
145
|
+
def test_sync_ask_with_on_ask_false_raises_approval_required(self):
|
|
146
|
+
"""ask tool with on_ask returning False raises RilApprovalRequiredError and side-effect never runs."""
|
|
147
|
+
|
|
148
|
+
def access_sensitive(data_id):
|
|
149
|
+
self.executed = True
|
|
150
|
+
return f"accessed {data_id}"
|
|
151
|
+
|
|
152
|
+
def eval_override(law_file, action, **kwargs):
|
|
153
|
+
return self.ril.evaluate(
|
|
154
|
+
law_file, "access", resource="Data:secrets", entities=['Data:secrets={"sensitive":true}']
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
client = make_client_with_evaluate(self.ril, eval_override)
|
|
158
|
+
governed = ril_govern(client, LAW_FILE, "access", on_ask=lambda d, a: False)(access_sensitive)
|
|
159
|
+
|
|
160
|
+
with self.assertRaises(RilApprovalRequiredError):
|
|
161
|
+
governed("secrets")
|
|
162
|
+
|
|
163
|
+
self.assertFalse(self.executed, "wrapped function should NOT have executed")
|
|
164
|
+
|
|
165
|
+
def test_sync_ask_with_on_ask_true_executes(self):
|
|
166
|
+
"""ask tool with on_ask returning True executes and returns result."""
|
|
167
|
+
|
|
168
|
+
def access_sensitive(data_id):
|
|
169
|
+
self.executed = True
|
|
170
|
+
return f"accessed {data_id}"
|
|
171
|
+
|
|
172
|
+
def eval_override(law_file, action, **kwargs):
|
|
173
|
+
return self.ril.evaluate(
|
|
174
|
+
law_file, "access", resource="Data:secrets", entities=['Data:secrets={"sensitive":true}']
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
client = make_client_with_evaluate(self.ril, eval_override)
|
|
178
|
+
governed = ril_govern(client, LAW_FILE, "access", on_ask=lambda d, a: True)(access_sensitive)
|
|
179
|
+
|
|
180
|
+
result = governed("secrets")
|
|
181
|
+
self.assertEqual(result, "accessed secrets")
|
|
182
|
+
self.assertTrue(self.executed, "wrapped function should have executed")
|
|
183
|
+
|
|
184
|
+
def test_async_ask_with_async_on_ask_true_executes(self):
|
|
185
|
+
"""ask tool with async on_ask returning True executes and returns result."""
|
|
186
|
+
|
|
187
|
+
async def access_sensitive_async(data_id):
|
|
188
|
+
self.executed = True
|
|
189
|
+
await asyncio.sleep(0.001)
|
|
190
|
+
return f"accessed {data_id}"
|
|
191
|
+
|
|
192
|
+
async def async_on_ask(decision, args):
|
|
193
|
+
await asyncio.sleep(0.001)
|
|
194
|
+
return True
|
|
195
|
+
|
|
196
|
+
def eval_override(law_file, action, **kwargs):
|
|
197
|
+
return self.ril.evaluate(
|
|
198
|
+
law_file, "access", resource="Data:secrets", entities=['Data:secrets={"sensitive":true}']
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
client = make_client_with_evaluate(self.ril, eval_override)
|
|
202
|
+
governed = ril_govern(client, LAW_FILE, "access", on_ask=async_on_ask)(access_sensitive_async)
|
|
203
|
+
|
|
204
|
+
result = asyncio.run(governed("secrets"))
|
|
205
|
+
self.assertEqual(result, "accessed secrets")
|
|
206
|
+
self.assertTrue(self.executed, "wrapped function should have executed")
|
|
207
|
+
|
|
208
|
+
def test_sync_on_decision_callback_receives_decision(self):
|
|
209
|
+
"""on_decision callback receives the allow decision."""
|
|
210
|
+
|
|
211
|
+
def read_safe_file(filename):
|
|
212
|
+
return f"contents of {filename}"
|
|
213
|
+
|
|
214
|
+
def on_decision_callback(decision, args):
|
|
215
|
+
self.decision_received = decision
|
|
216
|
+
|
|
217
|
+
def eval_override(law_file, action, **kwargs):
|
|
218
|
+
return self.ril.evaluate(
|
|
219
|
+
law_file, "read", resource="File:test.txt", entities=['File:test.txt={"safe":true}']
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
client = make_client_with_evaluate(self.ril, eval_override)
|
|
223
|
+
governed = ril_govern(client, LAW_FILE, "read", on_decision=on_decision_callback)(read_safe_file)
|
|
224
|
+
governed("test.txt")
|
|
225
|
+
|
|
226
|
+
self.assertIsNotNone(self.decision_received)
|
|
227
|
+
self.assertEqual(self.decision_received["verdict"], "allow")
|
|
228
|
+
|
|
229
|
+
def test_async_on_decision_callback_receives_decision(self):
|
|
230
|
+
"""async on_decision callback receives the allow decision."""
|
|
231
|
+
|
|
232
|
+
async def read_safe_file_async(filename):
|
|
233
|
+
await asyncio.sleep(0.001)
|
|
234
|
+
return f"contents of {filename}"
|
|
235
|
+
|
|
236
|
+
async def async_on_decision_callback(decision, args):
|
|
237
|
+
await asyncio.sleep(0.001)
|
|
238
|
+
self.decision_received = decision
|
|
239
|
+
|
|
240
|
+
def eval_override(law_file, action, **kwargs):
|
|
241
|
+
return self.ril.evaluate(
|
|
242
|
+
law_file, "read", resource="File:test.txt", entities=['File:test.txt={"safe":true}']
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
client = make_client_with_evaluate(self.ril, eval_override)
|
|
246
|
+
governed = ril_govern(client, LAW_FILE, "read", on_decision=async_on_decision_callback)(
|
|
247
|
+
read_safe_file_async
|
|
248
|
+
)
|
|
249
|
+
asyncio.run(governed("test.txt"))
|
|
250
|
+
|
|
251
|
+
self.assertIsNotNone(self.decision_received)
|
|
252
|
+
self.assertEqual(self.decision_received["verdict"], "allow")
|
|
253
|
+
|
|
254
|
+
def test_ril_tool_guard_wrap_single_function(self):
|
|
255
|
+
"""RilToolGuard.wrap governs a single tool."""
|
|
256
|
+
|
|
257
|
+
def read_file(filename):
|
|
258
|
+
self.executed = True
|
|
259
|
+
return f"read {filename}"
|
|
260
|
+
|
|
261
|
+
def eval_override(law_file, action, **kwargs):
|
|
262
|
+
return self.ril.evaluate(
|
|
263
|
+
law_file, "read", resource="File:test.txt", entities=['File:test.txt={"safe":true}']
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
client = make_client_with_evaluate(self.ril, eval_override)
|
|
267
|
+
guard = RilToolGuard(client, LAW_FILE)
|
|
268
|
+
governed = guard.wrap(read_file, action="read")
|
|
269
|
+
|
|
270
|
+
result = governed("test.txt")
|
|
271
|
+
self.assertEqual(result, "read test.txt")
|
|
272
|
+
self.assertTrue(self.executed)
|
|
273
|
+
|
|
274
|
+
def test_ril_tool_guard_wrap_all(self):
|
|
275
|
+
"""RilToolGuard.wrap_all governs a multi-tool dict cleanly."""
|
|
276
|
+
read_executed = False
|
|
277
|
+
write_executed = False
|
|
278
|
+
|
|
279
|
+
def read_file(filename):
|
|
280
|
+
nonlocal read_executed
|
|
281
|
+
read_executed = True
|
|
282
|
+
return f"read {filename}"
|
|
283
|
+
|
|
284
|
+
def write_file(filename, content):
|
|
285
|
+
nonlocal write_executed
|
|
286
|
+
write_executed = True
|
|
287
|
+
return f"wrote {content} to {filename}"
|
|
288
|
+
|
|
289
|
+
tools = {"read_file": read_file, "write_file": write_file}
|
|
290
|
+
|
|
291
|
+
def eval_override(law_file, action, **kwargs):
|
|
292
|
+
if action == "tools.read_file":
|
|
293
|
+
return self.ril.evaluate(
|
|
294
|
+
law_file, "read", resource="File:test.txt", entities=['File:test.txt={"safe":true}']
|
|
295
|
+
)
|
|
296
|
+
elif action == "tools.write_file":
|
|
297
|
+
return self.ril.evaluate(
|
|
298
|
+
law_file, "write", resource="File:danger.sh", entities=['File:danger.sh={"dangerous":true}']
|
|
299
|
+
)
|
|
300
|
+
return {"verdict": "deny", "laws": [], "errors": {}, "law_set_digest": ""}
|
|
301
|
+
|
|
302
|
+
client = make_client_with_evaluate(self.ril, eval_override)
|
|
303
|
+
guard = RilToolGuard(client, LAW_FILE, action_prefix="tools")
|
|
304
|
+
governed = guard.wrap_all(tools)
|
|
305
|
+
|
|
306
|
+
# Allow action should work
|
|
307
|
+
result = governed["read_file"]("test.txt")
|
|
308
|
+
self.assertEqual(result, "read test.txt")
|
|
309
|
+
self.assertTrue(read_executed)
|
|
310
|
+
|
|
311
|
+
# Deny action should raise
|
|
312
|
+
with self.assertRaises(RilDeniedError):
|
|
313
|
+
governed["write_file"]("danger.sh", "bad")
|
|
314
|
+
|
|
315
|
+
self.assertFalse(write_executed, "write should not have executed")
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
if __name__ == "__main__":
|
|
319
|
+
unittest.main()
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
import sys
|
|
5
|
+
import tempfile
|
|
6
|
+
import unittest
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
10
|
+
from ril_sdk import RilClient, RilError # noqa: E402
|
|
11
|
+
|
|
12
|
+
ROOT = Path(__file__).resolve().parents[3]
|
|
13
|
+
BIN = next(
|
|
14
|
+
(p for p in [
|
|
15
|
+
os.environ.get("RIL_BIN"),
|
|
16
|
+
str(ROOT / "ril-core/target/debug/ril"),
|
|
17
|
+
str(ROOT / "ril-core/target/release/ril"),
|
|
18
|
+
] if p and os.path.exists(p)),
|
|
19
|
+
None,
|
|
20
|
+
)
|
|
21
|
+
# Signed by `ril-core/examples/receipt_fixture.rs` (fixed test-only seed): 2 rows of action a1.
|
|
22
|
+
FIXTURES = ROOT / "sdks/fixtures"
|
|
23
|
+
RECEIPT = str(FIXTURES / "receipt.json")
|
|
24
|
+
PUB_PEM_PATH = str(FIXTURES / "seal.pub.pem")
|
|
25
|
+
PUB_PEM = (FIXTURES / "seal.pub.pem").read_text()
|
|
26
|
+
PUB_HEX = base64.b64decode(re.sub(r"-----[^-]+-----|\s", "", PUB_PEM))[-32:].hex()
|
|
27
|
+
SETTLEMENT = str(ROOT / "examples/settlement.ril")
|
|
28
|
+
QUORUM = str(ROOT / "packs/quorum-settlement.ril")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@unittest.skipUnless(BIN, "ril binary not built (cargo build --manifest-path ril-core/Cargo.toml)")
|
|
32
|
+
class RilSdkTest(unittest.TestCase):
|
|
33
|
+
def setUp(self):
|
|
34
|
+
self.ril = RilClient(BIN)
|
|
35
|
+
self.tmp = tempfile.TemporaryDirectory()
|
|
36
|
+
self.addCleanup(self.tmp.cleanup)
|
|
37
|
+
|
|
38
|
+
def write(self, name, text):
|
|
39
|
+
p = os.path.join(self.tmp.name, name)
|
|
40
|
+
with open(p, "w") as fh:
|
|
41
|
+
fh.write(text)
|
|
42
|
+
return p
|
|
43
|
+
|
|
44
|
+
def test_check_settlement(self):
|
|
45
|
+
r = self.ril.check(SETTLEMENT)
|
|
46
|
+
self.assertTrue(r.ok, r.raw)
|
|
47
|
+
self.assertEqual(r.name, "Retvest Payment Settlement")
|
|
48
|
+
self.assertEqual(len(r.digest), 64)
|
|
49
|
+
self.assertGreater(r.machines[0]["states_explored"], 0)
|
|
50
|
+
self.assertEqual(r.diagnostics, [])
|
|
51
|
+
|
|
52
|
+
def test_check_quorum_pack(self):
|
|
53
|
+
r = self.ril.check(QUORUM)
|
|
54
|
+
self.assertTrue(r.ok, r.raw)
|
|
55
|
+
self.assertEqual(r.machines[0]["id"], "quorum-settlement")
|
|
56
|
+
|
|
57
|
+
def test_test_inline(self):
|
|
58
|
+
r = self.ril.test(SETTLEMENT)
|
|
59
|
+
self.assertTrue(r.ok)
|
|
60
|
+
self.assertEqual(r.passed, len(r.tests))
|
|
61
|
+
self.assertIn("deny", [t.verdict for t in r.tests])
|
|
62
|
+
|
|
63
|
+
def test_broken_file_diagnostics(self):
|
|
64
|
+
bad = self.write("broken.ril", "law x {\n")
|
|
65
|
+
r = self.ril.check(bad)
|
|
66
|
+
self.assertFalse(r.ok)
|
|
67
|
+
self.assertEqual(len(r.diagnostics), 1)
|
|
68
|
+
d = r.diagnostics[0]
|
|
69
|
+
self.assertEqual(d.kind, "parse")
|
|
70
|
+
self.assertEqual(d.line, 1)
|
|
71
|
+
self.assertIsInstance(d.column, int)
|
|
72
|
+
self.assertIn("expected", d.message)
|
|
73
|
+
self.assertFalse(self.ril.test(bad).ok)
|
|
74
|
+
|
|
75
|
+
def test_missing_file_is_io_diagnostic(self):
|
|
76
|
+
r = self.ril.check("/nonexistent/nope.ril")
|
|
77
|
+
self.assertFalse(r.ok)
|
|
78
|
+
self.assertEqual(r.diagnostics[0].kind, "io")
|
|
79
|
+
|
|
80
|
+
def test_codegen(self):
|
|
81
|
+
ts = self.ril.codegen(SETTLEMENT, "ts")
|
|
82
|
+
self.assertTrue(ts)
|
|
83
|
+
self.assertTrue(self.ril.codegen(SETTLEMENT, lang="rust"))
|
|
84
|
+
out = os.path.join(self.tmp.name, "guards.ts")
|
|
85
|
+
self.assertEqual(self.ril.codegen(SETTLEMENT, "ts", out), ts)
|
|
86
|
+
|
|
87
|
+
def test_codegen_broken_raises(self):
|
|
88
|
+
with self.assertRaises(RilError):
|
|
89
|
+
self.ril.codegen(self.write("b.ril", "nonsense\n"), "ts")
|
|
90
|
+
|
|
91
|
+
def test_spec(self):
|
|
92
|
+
self.assertIn("RIL v3 Language Grammar", self.ril.spec())
|
|
93
|
+
|
|
94
|
+
def test_verify_receipt_bogus(self):
|
|
95
|
+
receipt = self.write("r.json", "{}")
|
|
96
|
+
ok, output = self.ril.verify_receipt(receipt, "00" * 32)
|
|
97
|
+
self.assertFalse(ok)
|
|
98
|
+
self.assertIsInstance(output, str)
|
|
99
|
+
|
|
100
|
+
def test_verify_receipt_accepts_real_signed_receipt(self):
|
|
101
|
+
for key in (PUB_HEX, PUB_PEM, PUB_PEM_PATH):
|
|
102
|
+
ok, output = self.ril.verify_receipt(RECEIPT, key)
|
|
103
|
+
self.assertTrue(ok, output)
|
|
104
|
+
self.assertIn("receipt verified: 2 rows of action a1 (tenant acme)", output)
|
|
105
|
+
|
|
106
|
+
def test_verify_receipt_one_byte_tamper_flips_to_false(self):
|
|
107
|
+
with open(RECEIPT, encoding="utf-8") as fh:
|
|
108
|
+
original = fh.read()
|
|
109
|
+
self.assertIn("10:00:01", original)
|
|
110
|
+
tampered = self.write("tampered.json", original.replace("10:00:01", "10:00:02", 1))
|
|
111
|
+
ok, output = self.ril.verify_receipt(tampered, PUB_HEX)
|
|
112
|
+
self.assertFalse(ok, output)
|
|
113
|
+
self.assertIn("NOT verified", output)
|
|
114
|
+
|
|
115
|
+
def test_verify_receipt_rejects_other_key(self):
|
|
116
|
+
ok, output = self.ril.verify_receipt(RECEIPT, "11" * 32)
|
|
117
|
+
self.assertFalse(ok, output)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class MissingBinaryTest(unittest.TestCase):
|
|
121
|
+
def test_missing_binary(self):
|
|
122
|
+
with self.assertRaises(RilError):
|
|
123
|
+
RilClient("/nonexistent/ril").spec()
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
if __name__ == "__main__":
|
|
127
|
+
unittest.main()
|