"""Bind rehearsal results to a configured runner and an independent trust key.""" import copy import hmac from pathlib import Path from core.operator_approval import read_protected_authority from core.rehearsal import ( RECORD_FIELDS, RehearsalError, approval_context, create_rehearsal, matches, require, validate_base_context, ) class TrustedRehearsal: def __init__(self, runner_id, runner, *, key_loader, clock): require(matches(runner_id, r"[a-zA-Z0-9_.-]{1,128}"), "Invalid rehearsal runner identity") require(callable(runner) and callable(clock), "Trusted rehearsal runner and clock required") require(callable(key_loader), "Trusted rehearsal key loader required") self.runner_id = runner_id self._runner = runner self._key_loader = key_loader self._clock = clock def _seal(self, fingerprint): payload = f"absdev:trusted-rehearsal:v1:{self.runner_id}:{fingerprint}".encode("ascii") try: key = self._key_loader() except Exception: raise RehearsalError("Unable to verify current rehearsal authority") from None require(isinstance(key, bytes) and len(key) >= 32, "Invalid rehearsal trust key") return hmac.digest(key, payload, "sha256").hex() def run(self, context): context = copy.deepcopy(context) validate_base_context(context) execution = self._runner(copy.deepcopy(context)) record = create_rehearsal(context, execution, completed_at=self._clock()) return dict(record, runner_id=self.runner_id, runner_seal=self._seal(record["fingerprint"])) def approval_context(self, evidence, context, *, now): require(isinstance(evidence, dict) and set(evidence) == RECORD_FIELDS | {"runner_id", "runner_seal"}, "Trusted rehearsal evidence required") require(evidence["runner_id"] == self.runner_id and matches(evidence["runner_seal"], r"[a-f0-9]{64}"), "Invalid rehearsal runner attestation") record = {name: evidence[name] for name in RECORD_FIELDS} approved = approval_context(record, context, now=now) require(hmac.compare_digest(evidence["runner_seal"], self._seal(record["fingerprint"])), "Untrusted rehearsal runner attestation") return approved class FileRehearsalKey: """Read a protected current key snapshot for each attestation operation.""" def __init__(self, path, *, group): self.path = Path(path) self.group = group require(self.path.is_absolute() and self.path.parent.resolve() == self.path.parent and type(group) is int and group > 0, "Invalid rehearsal key binding") def __call__(self): return read_protected_authority(self.path, group=self.group, max_bytes=4096)