PingPongRealWorldRL / runtime /motion_attestation.py
KurisiTOMA's picture
chore: publish H2 real-world RL system
d8290eb verified
Raw History Blame Contribute Delete
6.86 kB
"""Short-lived, same-host attestation for the H2 MotionSwitcher check."""
from __future__ import annotations
import json
import math
import os
from pathlib import Path
import stat
import time
ATTESTATION_VERSION = 1
ATTESTATION_MAX_AGE_S = 60.0
ATTESTATION_PATH = Path("/dev/shm/h2_motion_switcher_attestation.json")
MOTION_SWITCHER_ACK = "H2-MOTION-SWITCHER-VERIFIED"
def interface_hash(interface: str) -> int:
"""32-bit FNV-1a over the exact Linux interface name (shared with C++)."""
value = 2166136261
for byte in interface.encode("utf-8"):
value ^= byte
value = (value * 16777619) & 0xFFFFFFFF
if value == 0:
raise RuntimeError("network interface hash unexpectedly equals zero")
return value
def motion_switcher_released(status: int, result: object) -> bool:
"""Validate CheckMode's schema; only an exact empty string means released."""
if isinstance(status, bool) or not isinstance(status, int) or status != 0:
raise RuntimeError(f"MotionSwitcher CheckMode failed: status={status!r}, result={result!r}")
if not isinstance(result, dict) or "name" not in result or not isinstance(result["name"], str):
raise RuntimeError(
"MotionSwitcher CheckMode returned an ambiguous schema; expected a string 'name': "
f"{result!r}"
)
return result["name"] == ""
def _boot_id() -> str:
path = Path("/proc/sys/kernel/random/boot_id")
if not path.is_file():
raise RuntimeError("Linux boot_id is unavailable; cannot bind MotionSwitcher attestation")
value = path.read_text(encoding="utf-8").strip()
if not value:
raise RuntimeError("Linux boot_id is empty")
return value
def require_interface_up(interface: str) -> None:
if not interface or "/" in interface or interface in {".", ".."}:
raise ValueError("network interface name is invalid")
state_path = Path("/sys/class/net") / interface / "operstate"
if not state_path.is_file():
raise RuntimeError(f"network interface does not exist: {interface}")
state = state_path.read_text(encoding="utf-8").strip()
if state != "up":
raise RuntimeError(f"network interface {interface} is not UP (operstate={state!r})")
def write_attestation(interface: str, path: Path = ATTESTATION_PATH) -> dict[str, object]:
"""Atomically write an owner-only token after a successful CheckMode."""
require_interface_up(interface)
payload: dict[str, object] = {
"version": ATTESTATION_VERSION,
"interface": interface,
"boot_id": _boot_id(),
"checked_monotonic_ns": time.monotonic_ns(),
}
encoded = (json.dumps(payload, sort_keys=True, separators=(",", ":")) + "\n").encode()
path = Path(path)
temporary = path.with_name(f".{path.name}.{os.getpid()}.{time.monotonic_ns()}.tmp")
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
if hasattr(os, "O_NOFOLLOW"):
flags |= os.O_NOFOLLOW
fd = os.open(temporary, flags, 0o600)
try:
with os.fdopen(fd, "wb", closefd=False) as stream:
stream.write(encoded)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
os.chmod(path, 0o600)
finally:
os.close(fd)
try:
temporary.unlink()
except FileNotFoundError:
pass
return payload
def consume_attestation(
interface: str,
path: Path = ATTESTATION_PATH,
*,
max_age_s: float = ATTESTATION_MAX_AGE_S,
) -> float:
"""Validate and consume a fresh owner-only attestation; return its age."""
require_interface_up(interface)
if not math.isfinite(max_age_s) or not 1.0 <= max_age_s <= ATTESTATION_MAX_AGE_S:
raise ValueError(
f"MotionSwitcher attestation max age must be finite and in [1,{ATTESTATION_MAX_AGE_S:g}]s"
)
path = Path(path)
# Rename is the one-time claim: only one runner can atomically move this
# token away from the well-known path. Validation failures consume it too.
claimed = path.with_name(f".{path.name}.claimed.{os.getpid()}.{time.monotonic_ns()}")
os.rename(path, claimed)
flags = os.O_RDONLY
if hasattr(os, "O_NOFOLLOW"):
flags |= os.O_NOFOLLOW
fd = -1
try:
fd = os.open(claimed, flags)
metadata = os.fstat(fd)
if not stat.S_ISREG(metadata.st_mode):
raise RuntimeError("MotionSwitcher attestation is not a regular file")
if metadata.st_uid != os.getuid() or metadata.st_mode & 0o077:
raise RuntimeError("MotionSwitcher attestation must be owner-only and owned by this user")
if metadata.st_size <= 0 or metadata.st_size > 4096:
raise RuntimeError("MotionSwitcher attestation size is invalid")
encoded = b""
while len(encoded) < metadata.st_size:
block = os.read(fd, metadata.st_size - len(encoded))
if not block:
break
encoded += block
try:
payload = json.loads(encoded.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError) as error:
raise RuntimeError("MotionSwitcher attestation is not valid JSON") from error
if not isinstance(payload, dict):
raise RuntimeError("MotionSwitcher attestation payload must be an object")
if payload.get("version") != ATTESTATION_VERSION:
raise RuntimeError("MotionSwitcher attestation version mismatch")
if payload.get("interface") != interface:
raise RuntimeError(
f"MotionSwitcher attestation interface mismatch: {payload.get('interface')!r} != {interface!r}"
)
if payload.get("boot_id") != _boot_id():
raise RuntimeError("MotionSwitcher attestation was created during another boot")
stamp = payload.get("checked_monotonic_ns")
if isinstance(stamp, bool) or not isinstance(stamp, int) or stamp <= 0:
raise RuntimeError("MotionSwitcher attestation timestamp is invalid")
now_ns = time.monotonic_ns()
if stamp > now_ns:
raise RuntimeError("MotionSwitcher attestation timestamp is in the future")
age_s = (now_ns - stamp) * 1.0e-9
if age_s > max_age_s:
raise RuntimeError(
f"MotionSwitcher attestation is stale ({age_s:.3f}s > {max_age_s:.3f}s)"
)
return age_s
finally:
if fd >= 0:
os.close(fd)
try:
claimed.unlink()
except FileNotFoundError:
pass
__all__ = [
"ATTESTATION_MAX_AGE_S",
"ATTESTATION_PATH",
"ATTESTATION_VERSION",
"MOTION_SWITCHER_ACK",
"consume_attestation",
"interface_hash",
"motion_switcher_released",
"require_interface_up",
"write_attestation",
]