robot-gate 0.2.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.
robot_gate/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ """robot-gate: Deterministic on-robot deployment harness and change-triggered test gate."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "0.2.0"
6
+
7
+ SAFETY_BOUNDARY_STATEMENT = (
8
+ "robot-gate and robot-md-gateway provide a deterministic, default-deny software "
9
+ "enforcement gateway, pre-flight regression gate, and offline-verifiable audit layer. "
10
+ "They are NOT a safety-rated emergency stop (ISO 13850) and never replace certified "
11
+ "hardwired power cutoffs or ISO 13849-1 safety relays."
12
+ )
13
+
14
+ __all__ = ["SAFETY_BOUNDARY_STATEMENT", "__version__"]
robot_gate/audit.py ADDED
@@ -0,0 +1,128 @@
1
+ """Offline-verifiable SHA-256 hash-chained audit log (EU 2023/1230 traceability)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import threading
9
+ import time
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ try:
15
+ import fcntl
16
+ except ImportError: # pragma: no cover - non-POSIX fallback
17
+ fcntl = None # type: ignore[assignment]
18
+
19
+ from .bounded_bridge import sha256_canonical
20
+
21
+ GENESIS_HASH = "0" * 64
22
+ _AUDIT_THREAD_LOCK = threading.Lock()
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class AuditVerifyResult:
27
+ valid: bool
28
+ record_count: int
29
+ head_hash: str
30
+ error: str | None = None
31
+
32
+
33
+ def _compute_record_hash(entry_without_hash: dict[str, Any]) -> str:
34
+ return sha256_canonical(entry_without_hash)
35
+
36
+
37
+ def read_audit_tail_hash(audit_path: Path) -> str:
38
+ if not audit_path.exists():
39
+ return GENESIS_HASH
40
+ last_hash = GENESIS_HASH
41
+ for line in audit_path.read_text(encoding="utf-8").splitlines():
42
+ if not line.strip():
43
+ continue
44
+ rec = json.loads(line)
45
+ last_hash = str(rec.get("hash", GENESIS_HASH))
46
+ return last_hash
47
+
48
+
49
+ def append_audit_record(
50
+ audit_path: Path,
51
+ *,
52
+ event: str,
53
+ decision: str,
54
+ details: dict[str, Any],
55
+ ) -> dict[str, Any]:
56
+ """Append a hash-chained audit record (thread-safe & inter-process locked)."""
57
+ audit_path.parent.mkdir(parents=True, exist_ok=True)
58
+ with _AUDIT_THREAD_LOCK:
59
+ with audit_path.open("a+", encoding="utf-8") as f:
60
+ if fcntl is not None:
61
+ fcntl.flock(f.fileno(), fcntl.LOCK_EX)
62
+ try:
63
+ f.seek(0)
64
+ prev_hash = GENESIS_HASH
65
+ for line in f.read().splitlines():
66
+ if not line.strip():
67
+ continue
68
+ rec = json.loads(line)
69
+ prev_hash = str(rec.get("hash", GENESIS_HASH))
70
+ payload = {
71
+ "ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
72
+ "event": event,
73
+ "decision": decision,
74
+ "prev_hash": prev_hash,
75
+ "details": details,
76
+ }
77
+ rec_hash = _compute_record_hash(payload)
78
+ record = {**payload, "hash": rec_hash}
79
+ f.seek(0, os.SEEK_END)
80
+ f.write(json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n")
81
+ f.flush()
82
+ finally:
83
+ if fcntl is not None:
84
+ fcntl.flock(f.fileno(), fcntl.LOCK_UN)
85
+ return record
86
+
87
+
88
+ def verify_audit_chain(audit_path: Path) -> AuditVerifyResult:
89
+ """Cryptographically verify the entire SHA-256 hash chain offline."""
90
+ if not audit_path.exists():
91
+ return AuditVerifyResult(valid=True, record_count=0, head_hash=GENESIS_HASH)
92
+
93
+ prev = GENESIS_HASH
94
+ count = 0
95
+ for idx, raw_line in enumerate(audit_path.read_text(encoding="utf-8").splitlines(), start=1):
96
+ if not raw_line.strip():
97
+ continue
98
+ try:
99
+ rec = json.loads(raw_line)
100
+ except json.JSONDecodeError as exc:
101
+ return AuditVerifyResult(
102
+ valid=False,
103
+ record_count=count,
104
+ head_hash=prev,
105
+ error=f"line {idx}: invalid JSON ({exc})",
106
+ )
107
+ recorded_prev = rec.get("prev_hash")
108
+ recorded_hash = rec.get("hash")
109
+ if recorded_prev != prev:
110
+ return AuditVerifyResult(
111
+ valid=False,
112
+ record_count=count,
113
+ head_hash=prev,
114
+ error=f"line {idx}: broken prev_hash link (expected {prev[:12]}..., got {str(recorded_prev)[:12]}...)",
115
+ )
116
+ body = {k: v for k, v in rec.items() if k != "hash"}
117
+ expected_hash = _compute_record_hash(body)
118
+ if recorded_hash != expected_hash:
119
+ return AuditVerifyResult(
120
+ valid=False,
121
+ record_count=count,
122
+ head_hash=prev,
123
+ error=f"line {idx}: hash mismatch (tampering detected)",
124
+ )
125
+ prev = expected_hash
126
+ count += 1
127
+
128
+ return AuditVerifyResult(valid=True, record_count=count, head_hash=prev)