diff --git a/core/approval_store.py b/core/approval_store.py index a55befb..67c0494 100644 --- a/core/approval_store.py +++ b/core/approval_store.py @@ -22,7 +22,8 @@ from core.approval import ( ApprovalError, ) -from core.rehearsal import approval_context +from core.rehearsal import BASE_FIELDS, RehearsalError +from core.trusted_rehearsal import TrustedRehearsal from core.compatibility import canonical_hash from core.locking import DeploymentLock from core.operator_approval import OperatorApprovalPolicy @@ -58,9 +59,10 @@ class ApprovalStore: MAX_BYTES = 4 * 1024 * 1024 - def __init__(self, directory, *, operator_policy=None): + def __init__(self, directory, *, operator_policy=None, trusted_rehearsal=None): self.operator_policy = operator_policy + self.trusted_rehearsal = trusted_rehearsal self.directory = Path(directory).absolute() self.validate_directory() @@ -323,11 +325,20 @@ class ApprovalStore: except ApprovalError as error: raise ApprovalStoreError(str(error)) from error + def rehearsal_context(self, rehearsal, base_context, *, now): + require(isinstance(self.trusted_rehearsal, TrustedRehearsal), + "Trusted rehearsal verifier required") + try: + return self.trusted_rehearsal.approval_context(rehearsal, base_context, now=now) + except RehearsalError as error: + raise ApprovalStoreError(str(error)) from error + def save( self, approval, context, *, + rehearsal=None, confirmation, now, ): @@ -365,7 +376,11 @@ class ApprovalStore: ) try: - record = self.require_operator_policy().issue(record, now) + policy = self.require_operator_policy() + base = {name: context[name] for name in BASE_FIELDS} + require(self.rehearsal_context(rehearsal, base, now=now) == context, + "Approval does not bind the trusted rehearsal") + record = policy.issue(record, now) except ApprovalError as error: raise ApprovalStoreError(str(error)) from error @@ -404,7 +419,7 @@ class ApprovalStore: try: - context = approval_context( + context = self.rehearsal_context( rehearsal, base_context, now=now, diff --git a/core/dev3/operations.py b/core/dev3/operations.py index c5dca20..a0d8951 100644 --- a/core/dev3/operations.py +++ b/core/dev3/operations.py @@ -10,7 +10,7 @@ from core.transactions import TransactionJournal class SiteOperations: - def __init__(self, root, *, operator_policy=None): + def __init__(self, root, *, operator_policy=None, trusted_rehearsal=None): root = Path(root) if root.resolve() != root: raise ValueError("Site runtime directory must be canonical") @@ -21,7 +21,8 @@ class SiteOperations: self.lock_path = state / ".deployment.lock" self.journal = TransactionJournal(state) self.backup_evidence = BackupEvidence(state) - self.approvals = ApprovalStore(approvals, operator_policy=operator_policy) + self.approvals = ApprovalStore(approvals, operator_policy=operator_policy, + trusted_rehearsal=trusted_rehearsal) self.journal.bind_migration_guard(self.approvals) self.guard = OperationGuard(self.approvals) diff --git a/core/migration.py b/core/migration.py index 47bb109..cb229a6 100644 --- a/core/migration.py +++ b/core/migration.py @@ -10,7 +10,6 @@ import re from pathlib import Path from core.approval import timestamp -from core.rehearsal import approval_context from core.compatibility import canonical_hash from core.locking import DeploymentLock from core.operation_guard import OperationGuard @@ -161,7 +160,7 @@ class MigrationCoordinator: base = copy.deepcopy(self.context_probe()) current_time = timestamp(self.clock()) - context = approval_context( + context = self.store.rehearsal_context( rehearsal, base, now=current_time ) diff --git a/core/trusted_rehearsal.py b/core/trusted_rehearsal.py new file mode 100644 index 0000000..799c707 --- /dev/null +++ b/core/trusted_rehearsal.py @@ -0,0 +1,44 @@ +"""Bind rehearsal results to a configured runner and an independent trust key.""" + +import copy +import hmac + +from core.rehearsal import ( + RECORD_FIELDS, approval_context, create_rehearsal, matches, require, + validate_base_context, +) + + +class TrustedRehearsal: + def __init__(self, runner_id, runner, *, key, 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(isinstance(key, bytes) and len(key) >= 32, "Invalid rehearsal trust key") + self.runner_id = runner_id + self._runner = runner + self._key = key + self._clock = clock + + def _seal(self, fingerprint): + payload = f"absdev:trusted-rehearsal:v1:{self.runner_id}:{fingerprint}".encode("ascii") + return hmac.digest(self._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 diff --git a/docs/TRUSTED-REHEARSAL.md b/docs/TRUSTED-REHEARSAL.md new file mode 100644 index 0000000..4c61244 --- /dev/null +++ b/docs/TRUSTED-REHEARSAL.md @@ -0,0 +1,25 @@ +# Trusted rehearsal evidence + +Configure `TrustedRehearsal(runner_id, runner, key=..., clock=...)` in trusted +runtime code and supply it to `SiteOperations(trusted_rehearsal=...)`. +Use a separately managed random key of at least 32 bytes and a stable runner +identifier. Only trusted runtime processes may have access to this key. +This is a symmetric attestation shared by the runner and approval runtime. +Keep it separate from the operator approval sealing key. + +The configured runner receives a copy of the exact rehearsal context. It must +verify the candidate inventory, restore the verified backup into an isolated +database, run the approved migrations, observe migration history and application +checks, and clean up before returning execution evidence. The runner and clock +come from trusted composition, and callers cannot supply either per rehearsal. + +Call `run(context)` to obtain evidence, then derive the approval context with +`approval_context(evidence, context, now=...)` and pass the same evidence as +`rehearsal` when saving the approval and attempting execution. The approval +store and migration coordinator independently verify the attestation. The +underlying structural rehearsal format remains readable for audit. Unsigned +historical evidence must be rerun under the trusted adapter before it can +authorise a migration. + +The configured runner and protected key provisioning are deployment inputs. +Production execution remains disabled. diff --git a/tests/unit/test_approval_store.py b/tests/unit/test_approval_store.py index 8e665f1..498de73 100644 --- a/tests/unit/test_approval_store.py +++ b/tests/unit/test_approval_store.py @@ -14,7 +14,8 @@ from core.approval import approval_checksum, issue_approval from core.approval_store import ApprovalStore, ApprovalStoreError from core.operator_approval import OperatorApprovalPolicy, OperatorGrant from core.locking import DeploymentLock, LockError -from core.rehearsal import create_rehearsal, approval_context +from core.rehearsal import create_rehearsal, fingerprint +from core.trusted_rehearsal import TrustedRehearsal class ApprovalStoreTests(unittest.TestCase): @@ -62,16 +63,13 @@ class ApprovalStoreTests(unittest.TestCase): }, } - self.rehearsal = create_rehearsal( - self.base, - self.execution, - completed_at=self.now, + self.trusted_rehearsal = TrustedRehearsal( + "fixture-runner", lambda _context: self.execution, + key=os.urandom(32), clock=lambda: self.now, ) - - self.context = approval_context( - self.rehearsal, - self.base, - now=self.now, + self.rehearsal = self.trusted_rehearsal.run(self.base) + self.context = self.trusted_rehearsal.approval_context( + self.rehearsal, self.base, now=self.now, ) self.approval = issue_approval( @@ -96,13 +94,15 @@ class ApprovalStoreTests(unittest.TestCase): for operation in ("issue", "execute") ] self.policy = OperatorApprovalPolicy(self.grants, sealing_key=self.key) - self.store = ApprovalStore(self.root, operator_policy=lambda: self.policy) + self.store = ApprovalStore(self.root, operator_policy=lambda: self.policy, + trusted_rehearsal=self.trusted_rehearsal) def save(self): return self.store.save( self.approval, self.context, + rehearsal=self.rehearsal, confirmation=self.approval["confirmation"], now=self.now, ) @@ -171,7 +171,8 @@ class ApprovalStoreTests(unittest.TestCase): self.save() self.consume() - self.store = ApprovalStore(self.root, operator_policy=lambda: self.policy) + self.store = ApprovalStore(self.root, operator_policy=lambda: self.policy, + trusted_rehearsal=self.trusted_rehearsal) with self.assertRaisesRegex(ApprovalStoreError, "already consumed"): self.consume() @@ -216,6 +217,7 @@ class ApprovalStoreTests(unittest.TestCase): self.store.save( self.approval, self.context, + rehearsal=self.rehearsal, confirmation=self.approval["confirmation"], now=self.now + timedelta(hours=20), ) @@ -476,6 +478,7 @@ class ApprovalStoreTests(unittest.TestCase): self.store.save( self.approval, self.context, + rehearsal=self.rehearsal, confirmation=self.approval["confirmation"], now=self.now + timedelta(hours=25), ) @@ -543,5 +546,31 @@ class ApprovalStoreTests(unittest.TestCase): self.assertFalse(self.store.consumed_path(self.identifier).exists()) + def test_unsigned_rehearsal_cannot_authorise_issuance_or_consumption(self): + signed = self.rehearsal + self.rehearsal = {name: value for name, value in signed.items() + if name not in ("runner_id", "runner_seal")} + with self.assertRaisesRegex(ApprovalStoreError, "Trusted rehearsal evidence required"): + self.save() + self.assertFalse(self.store.approval_path(self.identifier).exists()) + self.rehearsal = signed + self.save() + self.rehearsal = create_rehearsal(self.base, self.execution, completed_at=self.now) + with self.assertRaises(ApprovalStoreError): + self.consume() + self.assertFalse(self.store.consumed_path(self.identifier).exists()) + + def test_recomputed_fingerprint_does_not_authorise_forgery(self): + self.rehearsal["rehearsal_id"] = "f" * 32 + unsigned = {name: value for name, value in self.rehearsal.items() + if name not in ("runner_id", "runner_seal")} + self.rehearsal["fingerprint"] = fingerprint(unsigned) + self.context["rehearsal_fingerprint"] = self.rehearsal["fingerprint"] + self.approval = issue_approval(self.context, approver="operator", now=self.now) + with self.assertRaisesRegex(ApprovalStoreError, "Untrusted rehearsal runner"): + self.save() + self.assertFalse(self.store.approval_path(self.approval["approval_id"]).exists()) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/test_migration.py b/tests/unit/test_migration.py index 0d49b0f..a1257ce 100644 --- a/tests/unit/test_migration.py +++ b/tests/unit/test_migration.py @@ -17,7 +17,8 @@ class MigrationTests(unittest.TestCase): self.fixture = test_approval_store.ApprovalStoreTests() self.addCleanup(self.fixture.doCleanups) self.fixture.setUp() - self.ops = SiteOperations(self.fixture.root, operator_policy=lambda: self.fixture.policy) + self.ops = SiteOperations(self.fixture.root, operator_policy=lambda: self.fixture.policy, + trusted_rehearsal=self.fixture.trusted_rehearsal) self.fixture.store = self.ops.approvals self.fixture.save()