rulebound 0.1.0__py3-none-any.whl

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.
rulebound/__init__.py ADDED
@@ -0,0 +1,26 @@
1
+ """rulebound — rules of engagement for AI security agents.
2
+
3
+ Scope, graduated autonomy, human approvals, a kill switch and a tamper-evident
4
+ audit trail, enforced at the tool-call boundary (MCP proxy, CLI wrapper or
5
+ Python API). Standard library only.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ __version__ = "0.1.0"
11
+
12
+ from .engine import ALLOW, DENY, ESCALATE, ActionBlocked, Decision, Guard # noqa: E402
13
+ from .policy import Policy, PolicyError, load_policy # noqa: E402
14
+
15
+ __all__ = [
16
+ "ALLOW",
17
+ "DENY",
18
+ "ESCALATE",
19
+ "ActionBlocked",
20
+ "Decision",
21
+ "Guard",
22
+ "Policy",
23
+ "PolicyError",
24
+ "__version__",
25
+ "load_policy",
26
+ ]
rulebound/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
rulebound/approval.py ADDED
@@ -0,0 +1,192 @@
1
+ """Human approval of escalated actions (supervised / semi-autonomous operation)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import getpass
7
+ import json
8
+ import os
9
+ import select
10
+ import time
11
+ from dataclasses import asdict, dataclass, field
12
+ from pathlib import Path
13
+ from typing import Any, Protocol
14
+
15
+ from .audit import utc_now
16
+
17
+
18
+ @dataclass
19
+ class ApprovalRequest:
20
+ request_id: str
21
+ engagement_id: str
22
+ tool: str
23
+ action_class: str | None
24
+ risk: str | None
25
+ targets: list[str]
26
+ reasons: list[str]
27
+ args: Any = None # already redacted
28
+ created: str = field(default_factory=utc_now)
29
+
30
+
31
+ @dataclass
32
+ class ApprovalResult:
33
+ approved: bool
34
+ mode: str
35
+ approver: str | None = None
36
+ note: str = ""
37
+ latency_seconds: float = 0.0
38
+
39
+ def to_dict(self) -> dict[str, Any]:
40
+ return asdict(self)
41
+
42
+
43
+ class Approver(Protocol):
44
+ mode: str
45
+
46
+ def request(self, req: ApprovalRequest) -> ApprovalResult: ...
47
+
48
+
49
+ def current_user() -> str:
50
+ try:
51
+ return getpass.getuser()
52
+ except Exception: # noqa: BLE001 - getuser can raise several platform errors
53
+ return "unknown"
54
+
55
+
56
+ class DenyApprover:
57
+ """Rejects every escalation (unattended runs)."""
58
+
59
+ mode = "deny"
60
+
61
+ def request(self, req: ApprovalRequest) -> ApprovalResult:
62
+ return ApprovalResult(False, self.mode, note="approval mode is 'deny': escalations are rejected")
63
+
64
+
65
+ class TTYApprover:
66
+ """Asks on the controlling terminal (``/dev/tty``), so it also works when stdin/stdout
67
+ carry a protocol such as MCP stdio."""
68
+
69
+ mode = "tty"
70
+
71
+ def __init__(self, timeout_seconds: float = 300.0, approvers: tuple[str, ...] = (),
72
+ tty_path: str = "/dev/tty") -> None:
73
+ self.timeout = timeout_seconds
74
+ self.approvers = approvers
75
+ self.tty_path = tty_path
76
+
77
+ def request(self, req: ApprovalRequest) -> ApprovalResult:
78
+ started = time.monotonic()
79
+ user = current_user()
80
+ if self.approvers and user not in self.approvers:
81
+ return ApprovalResult(False, self.mode, approver=user,
82
+ note=f"local user '{user}' is not a listed approver")
83
+ try:
84
+ tty = open(self.tty_path, "r+", buffering=1, encoding="utf-8") # noqa: SIM115
85
+ except OSError:
86
+ return ApprovalResult(False, self.mode, note="no terminal available for approval")
87
+ with tty:
88
+ tty.write("\n" + format_request(req) + "\n")
89
+ tty.write(f"Approve as '{user}'? [y/N] (auto-reject in {int(self.timeout)}s): ")
90
+ tty.flush()
91
+ ready, _, _ = select.select([tty], [], [], self.timeout)
92
+ if not ready:
93
+ tty.write("\n[rulebound] approval timed out - rejected\n")
94
+ return ApprovalResult(False, self.mode, approver=user, note="approval timed out",
95
+ latency_seconds=time.monotonic() - started)
96
+ answer = tty.readline().strip().lower()
97
+ approved = answer in ("y", "yes")
98
+ return ApprovalResult(approved, self.mode, approver=user,
99
+ note="approved on terminal" if approved else "rejected on terminal",
100
+ latency_seconds=time.monotonic() - started)
101
+
102
+
103
+ class FileApprover:
104
+ """Writes ``<pending_dir>/<id>.json`` and waits for ``rulebound approve|reject <id>``."""
105
+
106
+ mode = "file"
107
+
108
+ def __init__(self, pending_dir: str | Path, timeout_seconds: float = 300.0,
109
+ poll_interval: float = 0.25) -> None:
110
+ self.pending_dir = Path(pending_dir)
111
+ self.timeout = timeout_seconds
112
+ self.poll = poll_interval
113
+
114
+ def request(self, req: ApprovalRequest) -> ApprovalResult:
115
+ started = time.monotonic()
116
+ self.pending_dir.mkdir(parents=True, exist_ok=True)
117
+ pending = self.pending_dir / f"{req.request_id}.json"
118
+ decision = self.pending_dir / f"{req.request_id}.decision.json"
119
+ _atomic_write(pending, asdict(req))
120
+ try:
121
+ deadline = started + self.timeout
122
+ while time.monotonic() < deadline:
123
+ if decision.exists():
124
+ try:
125
+ data = json.loads(decision.read_text(encoding="utf-8"))
126
+ except (OSError, ValueError):
127
+ time.sleep(self.poll)
128
+ continue
129
+ return ApprovalResult(bool(data.get("approved")), self.mode,
130
+ approver=data.get("by"), note=str(data.get("note", "")),
131
+ latency_seconds=time.monotonic() - started)
132
+ time.sleep(self.poll)
133
+ return ApprovalResult(False, self.mode, note="approval timed out",
134
+ latency_seconds=time.monotonic() - started)
135
+ finally:
136
+ for f in (pending, decision):
137
+ with contextlib.suppress(FileNotFoundError):
138
+ f.unlink()
139
+
140
+
141
+ def make_approver(mode: str, *, timeout_seconds: float, approvers: tuple[str, ...],
142
+ pending_dir: Path) -> Approver:
143
+ if mode == "file":
144
+ return FileApprover(pending_dir, timeout_seconds)
145
+ if mode == "tty":
146
+ return TTYApprover(timeout_seconds, approvers)
147
+ return DenyApprover()
148
+
149
+
150
+ def list_pending(pending_dir: str | Path) -> list[dict[str, Any]]:
151
+ d = Path(pending_dir)
152
+ if not d.is_dir():
153
+ return []
154
+ out = []
155
+ for f in sorted(d.glob("*.json")):
156
+ if f.name.endswith(".decision.json"):
157
+ continue
158
+ try:
159
+ out.append(json.loads(f.read_text(encoding="utf-8")))
160
+ except (OSError, ValueError):
161
+ continue
162
+ return out
163
+
164
+
165
+ def write_decision(pending_dir: str | Path, request_id: str, *, approved: bool, by: str,
166
+ note: str = "") -> Path:
167
+ d = Path(pending_dir)
168
+ if not (d / f"{request_id}.json").exists():
169
+ raise FileNotFoundError(f"no pending request with id {request_id!r} in {d}")
170
+ target = d / f"{request_id}.decision.json"
171
+ _atomic_write(target, {"approved": approved, "by": by, "note": note, "ts": utc_now()})
172
+ return target
173
+
174
+
175
+ def format_request(req: ApprovalRequest) -> str:
176
+ lines = [
177
+ f"[rulebound] approval required (request {req.request_id}, engagement {req.engagement_id})",
178
+ f" tool: {req.tool}",
179
+ f" class: {req.action_class or '(unrecognized)'} risk: {req.risk or 'unknown'}",
180
+ f" targets: {', '.join(req.targets) if req.targets else '(none detected)'}",
181
+ ]
182
+ lines += [f" why: {r}" for r in req.reasons]
183
+ if req.args is not None:
184
+ text = json.dumps(req.args, ensure_ascii=False, default=str)
185
+ lines.append(f" args: {text[:500]}{'...' if len(text) > 500 else ''}")
186
+ return "\n".join(lines)
187
+
188
+
189
+ def _atomic_write(path: Path, data: Any) -> None:
190
+ tmp = path.with_name(path.name + f".{os.getpid()}.tmp")
191
+ tmp.write_text(json.dumps(data, indent=2, default=str), encoding="utf-8")
192
+ os.replace(tmp, path)
rulebound/audit.py ADDED
@@ -0,0 +1,303 @@
1
+ """Tamper-evident, append-only audit trail (JSON Lines, hash-chained).
2
+
3
+ Every entry carries ``prev_hash`` and ``hash`` where::
4
+
5
+ hash = SHA-256(prev_hash || canonical_json(entry without "hash"))
6
+
7
+ or HMAC-SHA-256 with a secret key when one is configured. Editing, deleting or
8
+ reordering any entry breaks the chain from that point on. Truncating the *end*
9
+ of the log cannot be detected from the log alone - anchor the head hash
10
+ (``rulebound audit head``) somewhere else, e.g. in a ticket or a SIEM.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import hmac
17
+ import json
18
+ import os
19
+ import re
20
+ import threading
21
+ from collections.abc import Iterable, Iterator
22
+ from contextlib import contextmanager
23
+ from dataclasses import dataclass
24
+ from datetime import UTC, datetime
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ try: # POSIX advisory locking; Windows falls back to an in-process lock only
29
+ import fcntl
30
+ except ImportError: # pragma: no cover - platform dependent
31
+ fcntl = None # type: ignore[assignment]
32
+
33
+ GENESIS = "0" * 64
34
+ REDACTED = "[REDACTED]"
35
+ _HEADER_SECRET_RE = re.compile(r"(?i)\b((?:proxy-)?authorization\s*:\s*|(?:set-)?cookie\s*:\s*)\S.*$")
36
+ _TOKEN_SECRET_RE = re.compile(r"(?i)\b(bearer\s+|basic\s+)(?!\[REDACTED\])\S+")
37
+ _PROCESS_LOCK = threading.Lock()
38
+
39
+
40
+ def canonical_json(obj: Any) -> str:
41
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
42
+
43
+
44
+ def sha256_hex(data: str | bytes) -> str:
45
+ if isinstance(data, str):
46
+ data = data.encode("utf-8")
47
+ return hashlib.sha256(data).hexdigest()
48
+
49
+
50
+ def utc_now() -> str:
51
+ return datetime.now(UTC).isoformat(timespec="milliseconds")
52
+
53
+
54
+ # --------------------------------------------------------------------------- redaction
55
+
56
+
57
+ def _norm_key(key: str) -> str:
58
+ return re.sub(r"[^a-z0-9]", "", key.lower())
59
+
60
+
61
+ def _key_is_secret(key: str, redact_keys: Iterable[str]) -> bool:
62
+ k = _norm_key(key)
63
+ for r in redact_keys:
64
+ rk = _norm_key(r)
65
+ if rk and (k == rk or k.startswith(rk) or k.endswith(rk)):
66
+ return True
67
+ return False
68
+
69
+
70
+ def redact(value: Any, redact_keys: Iterable[str]) -> Any:
71
+ """Recursively replace values of secret-looking keys and inline credentials."""
72
+ keys = tuple(redact_keys)
73
+ if isinstance(value, dict):
74
+ return {k: (REDACTED if isinstance(k, str) and _key_is_secret(k, keys) else redact(v, keys))
75
+ for k, v in value.items()}
76
+ if isinstance(value, list | tuple):
77
+ return [redact(v, keys) for v in value]
78
+ if isinstance(value, str):
79
+ value = _HEADER_SECRET_RE.sub(lambda m: m.group(1) + REDACTED, value)
80
+ return _TOKEN_SECRET_RE.sub(lambda m: m.group(1) + REDACTED, value)
81
+ return value
82
+
83
+
84
+ def redact_argv(argv: Iterable[str], redact_keys: Iterable[str]) -> list[str]:
85
+ """Redact ``--password X`` / ``--token=X`` style arguments in a command line."""
86
+ keys = tuple(redact_keys)
87
+ out: list[str] = []
88
+ hide_next = False
89
+ for arg in argv:
90
+ if hide_next:
91
+ out.append(REDACTED)
92
+ hide_next = False
93
+ continue
94
+ if arg.startswith("--") and len(arg) > 2:
95
+ name, eq, _ = arg[2:].partition("=")
96
+ if _key_is_secret(name, keys):
97
+ if eq:
98
+ out.append(f"--{name}={REDACTED}")
99
+ else:
100
+ out.append(arg)
101
+ hide_next = True
102
+ continue
103
+ out.append(redact(arg, keys))
104
+ return out
105
+
106
+
107
+ # --------------------------------------------------------------------------- writer
108
+
109
+
110
+ class AuditLog:
111
+ """Append-only hash-chained JSONL writer."""
112
+
113
+ def __init__(self, path: str | Path, *, engagement_id: str = "", hmac_key: bytes | None = None,
114
+ policy_sha256: str = "") -> None:
115
+ self.path = Path(path)
116
+ self.engagement_id = engagement_id
117
+ self.hmac_key = hmac_key
118
+ self.policy_sha256 = policy_sha256
119
+ self._lock_path = self.path.with_name(self.path.name + ".lock")
120
+
121
+ @property
122
+ def alg(self) -> str:
123
+ return "hmac-sha256" if self.hmac_key else "sha256"
124
+
125
+ @contextmanager
126
+ def _locked(self) -> Iterator[None]:
127
+ self.path.parent.mkdir(parents=True, exist_ok=True)
128
+ with _PROCESS_LOCK:
129
+ if fcntl is None: # pragma: no cover
130
+ yield
131
+ return
132
+ with open(self._lock_path, "a") as lock:
133
+ fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
134
+ try:
135
+ yield
136
+ finally:
137
+ fcntl.flock(lock.fileno(), fcntl.LOCK_UN)
138
+
139
+ def append(self, event: str, **fields: Any) -> dict[str, Any]:
140
+ with self._locked():
141
+ last = last_entry(self.path)
142
+ seq = int(last["seq"]) + 1 if last else 1
143
+ prev = str(last["hash"]) if last else GENESIS
144
+ entry: dict[str, Any] = {"seq": seq, "ts": utc_now(), "engagement_id": self.engagement_id,
145
+ "event": event}
146
+ if self.policy_sha256:
147
+ entry["policy_sha256"] = self.policy_sha256
148
+ entry.update({k: v for k, v in fields.items() if v is not None})
149
+ entry["prev_hash"] = prev
150
+ entry["alg"] = self.alg
151
+ entry["hash"] = compute_hash(entry, prev, self.hmac_key)
152
+ line = canonical_json(entry) + "\n"
153
+ fd = os.open(self.path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o640)
154
+ try:
155
+ os.write(fd, line.encode("utf-8"))
156
+ os.fsync(fd)
157
+ finally:
158
+ os.close(fd)
159
+ return entry
160
+
161
+
162
+ def compute_hash(entry: dict[str, Any], prev_hash: str, key: bytes | None) -> str:
163
+ body = {k: v for k, v in entry.items() if k != "hash"}
164
+ payload = (prev_hash + canonical_json(body)).encode("utf-8")
165
+ if key:
166
+ return hmac.new(key, payload, hashlib.sha256).hexdigest()
167
+ return hashlib.sha256(payload).hexdigest()
168
+
169
+
170
+ # --------------------------------------------------------------------------- reading
171
+
172
+
173
+ def _tail_lines(path: Path, max_bytes: int = 1 << 20) -> list[bytes]:
174
+ try:
175
+ size = path.stat().st_size
176
+ except FileNotFoundError:
177
+ return []
178
+ with open(path, "rb") as fh:
179
+ start = max(0, size - max_bytes)
180
+ fh.seek(start)
181
+ data = fh.read()
182
+ lines = data.splitlines()
183
+ if start > 0 and lines:
184
+ lines = lines[1:] # first line is probably partial
185
+ return [ln for ln in lines if ln.strip()]
186
+
187
+
188
+ def last_entry(path: str | Path) -> dict[str, Any] | None:
189
+ p = Path(path)
190
+ for raw in reversed(_tail_lines(p, 1 << 16)):
191
+ try:
192
+ entry = json.loads(raw)
193
+ except ValueError:
194
+ continue
195
+ if isinstance(entry, dict) and "seq" in entry and "hash" in entry:
196
+ return entry
197
+ if p.exists() and p.stat().st_size > (1 << 16):
198
+ for raw in reversed(_tail_lines(p, 1 << 24)):
199
+ try:
200
+ entry = json.loads(raw)
201
+ except ValueError:
202
+ continue
203
+ if isinstance(entry, dict) and "seq" in entry and "hash" in entry:
204
+ return entry
205
+ return None
206
+
207
+
208
+ def tail_entries(path: str | Path, max_bytes: int = 1 << 20) -> list[dict[str, Any]]:
209
+ out: list[dict[str, Any]] = []
210
+ for raw in _tail_lines(Path(path), max_bytes):
211
+ try:
212
+ entry = json.loads(raw)
213
+ except ValueError:
214
+ continue
215
+ if isinstance(entry, dict):
216
+ out.append(entry)
217
+ return out
218
+
219
+
220
+ def read_entries(path: str | Path) -> list[dict[str, Any]]:
221
+ out: list[dict[str, Any]] = []
222
+ with open(path, encoding="utf-8") as fh:
223
+ for line in fh:
224
+ line = line.strip()
225
+ if not line:
226
+ continue
227
+ try:
228
+ entry = json.loads(line)
229
+ except ValueError:
230
+ continue
231
+ if isinstance(entry, dict):
232
+ out.append(entry)
233
+ return out
234
+
235
+
236
+ @dataclass
237
+ class VerifyResult:
238
+ ok: bool
239
+ entries: int
240
+ head_seq: int | None = None
241
+ head_hash: str | None = None
242
+ broken_seq: int | None = None
243
+ line: int | None = None
244
+ error: str | None = None
245
+
246
+ def summary(self) -> str:
247
+ if self.ok:
248
+ return f"OK: {self.entries} entries, chain intact (head seq={self.head_seq} hash={self.head_hash})"
249
+ where = f"seq {self.broken_seq}" if self.broken_seq is not None else f"line {self.line}"
250
+ return f"BROKEN at {where} (line {self.line}): {self.error}"
251
+
252
+
253
+ def verify_log(path: str | Path, hmac_key: bytes | None = None) -> VerifyResult:
254
+ """Walk the whole chain and report the first inconsistency."""
255
+ p = Path(path)
256
+ if not p.exists():
257
+ return VerifyResult(False, 0, error=f"audit log not found: {p}")
258
+ prev = GENESIS
259
+ expected_seq = 1
260
+ count = 0
261
+ last_hash: str | None = None
262
+ with open(p, encoding="utf-8") as fh:
263
+ for lineno, line in enumerate(fh, start=1):
264
+ if not line.strip():
265
+ continue
266
+ try:
267
+ entry = json.loads(line)
268
+ except ValueError:
269
+ return VerifyResult(False, count, broken_seq=expected_seq, line=lineno,
270
+ error="line is not valid JSON")
271
+ if not isinstance(entry, dict):
272
+ return VerifyResult(False, count, broken_seq=expected_seq, line=lineno,
273
+ error="entry is not a JSON object")
274
+ seq = entry.get("seq")
275
+ if seq != expected_seq:
276
+ return VerifyResult(False, count, broken_seq=expected_seq, line=lineno,
277
+ error=f"expected seq {expected_seq}, found {seq!r} "
278
+ "(entry deleted, inserted or reordered)")
279
+ if entry.get("prev_hash") != prev:
280
+ return VerifyResult(False, count, broken_seq=expected_seq, line=lineno,
281
+ error="prev_hash does not match the previous entry")
282
+ alg = entry.get("alg", "sha256")
283
+ if alg == "hmac-sha256" and not hmac_key:
284
+ return VerifyResult(False, count, broken_seq=expected_seq, line=lineno,
285
+ error="entry is HMAC-protected; provide the key to verify")
286
+ key = hmac_key if alg == "hmac-sha256" else None
287
+ if not hmac.compare_digest(str(entry.get("hash")), compute_hash(entry, prev, key)):
288
+ return VerifyResult(False, count, broken_seq=expected_seq, line=lineno,
289
+ error="hash mismatch (entry content was modified)")
290
+ prev = str(entry["hash"])
291
+ last_hash = prev
292
+ expected_seq += 1
293
+ count += 1
294
+ if count == 0:
295
+ return VerifyResult(False, 0, error="audit log is empty")
296
+ return VerifyResult(True, count, head_seq=expected_seq - 1, head_hash=last_hash)
297
+
298
+
299
+ def load_hmac_key(env_name: str | None) -> bytes | None:
300
+ if not env_name:
301
+ return None
302
+ value = os.environ.get(env_name, "")
303
+ return value.encode("utf-8") if value else None