From eac09534c748016916c4e10424ab7812b667842a Mon Sep 17 00:00:00 2001 From: Mark Gregory Date: Sat, 28 Nov 2026 09:58:41 +0000 Subject: [PATCH] Authenticate and scope migration operator approvals --- core/approval.py | 9 ++- core/approval_store.py | 27 +++++++- core/dev3/operations.py | 4 +- core/migration.py | 4 +- core/migration_recovery.py | 1 + core/operator_approval.py | 84 ++++++++++++++++++++++++ docs/MIGRATION-OPERATOR-AUTHORISATION.md | 30 +++++++++ tests/unit/test_approval_store.py | 75 +++++++++++++++++---- tests/unit/test_migration.py | 15 ++++- 9 files changed, 228 insertions(+), 21 deletions(-) create mode 100644 core/operator_approval.py create mode 100644 docs/MIGRATION-OPERATOR-AUTHORISATION.md diff --git a/core/approval.py b/core/approval.py index 35a087a..01abe5d 100644 --- a/core/approval.py +++ b/core/approval.py @@ -41,6 +41,9 @@ APPROVAL_FIELDS = { } +SEALED_APPROVAL_FIELDS = APPROVAL_FIELDS | {"operator_seal"} + + def require(condition, message): if not condition: @@ -232,13 +235,15 @@ def verify_approval( require( isinstance(approval, dict) - and set(approval) == APPROVAL_FIELDS, + and set(approval) in (APPROVAL_FIELDS, SEALED_APPROVAL_FIELDS), "Invalid approval record", ) require( type(approval["format_version"]) is int - and approval["format_version"] == 1, + and (approval["format_version"], set(approval)) in ( + (1, APPROVAL_FIELDS), (2, SEALED_APPROVAL_FIELDS), + ), "Unsupported approval format", ) diff --git a/core/approval_store.py b/core/approval_store.py index 9e218f3..9777eac 100644 --- a/core/approval_store.py +++ b/core/approval_store.py @@ -18,11 +18,14 @@ from core.approval import ( timestamp, approval_checksum, APPROVAL_FIELDS, + SEALED_APPROVAL_FIELDS, + ApprovalError, ) from core.rehearsal import approval_context from core.compatibility import canonical_hash from core.locking import DeploymentLock +from core.operator_approval import OperatorApprovalPolicy class ApprovalStoreError(RuntimeError): @@ -55,8 +58,9 @@ class ApprovalStore: MAX_BYTES = 4 * 1024 * 1024 - def __init__(self, directory): + def __init__(self, directory, *, operator_policy=None): + self.operator_policy = operator_policy self.directory = Path(directory).absolute() self.validate_directory() @@ -280,7 +284,7 @@ class ApprovalStore: require( isinstance(record, dict) - and set(record) == APPROVAL_FIELDS, + and set(record) in (APPROVAL_FIELDS, SEALED_APPROVAL_FIELDS), "Invalid stored approval structure", ) @@ -302,6 +306,18 @@ class ApprovalStore: return record + def require_operator_policy(self): + require(isinstance(self.operator_policy, OperatorApprovalPolicy), + "Trusted migration operator policy required") + return self.operator_policy + + def verify_execution(self, approval, context, *, confirmation, now): + verify_approval(approval, context, confirmation=confirmation, now=now) + try: + self.require_operator_policy().verify_execution(approval, now) + except ApprovalError as error: + raise ApprovalStoreError(str(error)) from error + def save( self, approval, @@ -343,6 +359,11 @@ class ApprovalStore: "Approval has already been consumed", ) + try: + record = self.require_operator_policy().issue(record, now) + except ApprovalError as error: + raise ApprovalStoreError(str(error)) from error + return self.publish( self.approval_path(identifier), record, @@ -384,7 +405,7 @@ class ApprovalStore: now=now, ) - verify_approval( + self.verify_execution( approval, context, confirmation=confirmation, diff --git a/core/dev3/operations.py b/core/dev3/operations.py index f3b193a..c5dca20 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): + def __init__(self, root, *, operator_policy=None): root = Path(root) if root.resolve() != root: raise ValueError("Site runtime directory must be canonical") @@ -21,7 +21,7 @@ class SiteOperations: self.lock_path = state / ".deployment.lock" self.journal = TransactionJournal(state) self.backup_evidence = BackupEvidence(state) - self.approvals = ApprovalStore(approvals) + self.approvals = ApprovalStore(approvals, operator_policy=operator_policy) self.journal.bind_migration_guard(self.approvals) self.guard = OperationGuard(self.approvals) diff --git a/core/migration.py b/core/migration.py index afad13a..47bb109 100644 --- a/core/migration.py +++ b/core/migration.py @@ -9,7 +9,7 @@ import re from pathlib import Path -from core.approval import verify_approval, timestamp +from core.approval import timestamp from core.rehearsal import approval_context from core.compatibility import canonical_hash from core.locking import DeploymentLock @@ -167,7 +167,7 @@ class MigrationCoordinator: approval = self.store.load(identifier) - verify_approval( + self.store.verify_execution( approval, context, confirmation=confirmation, diff --git a/core/migration_recovery.py b/core/migration_recovery.py index 2cca1ce..5c497ac 100644 --- a/core/migration_recovery.py +++ b/core/migration_recovery.py @@ -139,6 +139,7 @@ class MigrationRecovery: def _inspect(self, identifier): approval = self.store.load(identifier) + self.store.require_operator_policy().verify_seal(approval) context = approval["context"] validate_context(context) diff --git a/core/operator_approval.py b/core/operator_approval.py new file mode 100644 index 0000000..ae9214b --- /dev/null +++ b/core/operator_approval.py @@ -0,0 +1,84 @@ +"""Local operator identity and scoped migration approval policy.""" + +import hmac +import os + +from dataclasses import dataclass +from datetime import datetime + +from core.approval import ( + ApprovalError, + approval_checksum, + require, + timestamp, + validate_approver, +) + + +@dataclass(frozen=True) +class OperatorGrant: + uid: int + principal: str + operation: str + site: str + revision: str + expires_at: datetime + + +class OperatorApprovalPolicy: + """Use the OS effective UID and grants supplied by trusted runtime configuration.""" + + def __init__(self, grants, *, sealing_key): + require(isinstance(sealing_key, bytes) and len(sealing_key) >= 32, + "Operator approval sealing key must contain at least 32 bytes") + self.grants = tuple(grants) + principals_by_uid = {} + uids_by_principal = {} + for grant in self.grants: + require(type(grant.uid) is int and grant.uid > 0, + "Operator grant requires a non-root OS account") + validate_approver(grant.principal) + require(grant.operation in ("issue", "execute"), "Invalid operator operation") + require(principals_by_uid.setdefault(grant.uid, grant.principal) == grant.principal + and uids_by_principal.setdefault(grant.principal, grant.uid) == grant.uid, + "Operator principals must map one-to-one to OS accounts") + timestamp(grant.expires_at) + self._key = sealing_key + + def authorise(self, approval, operation, now): + uid = os.geteuid() + principal = approval["approver"] + validate_approver(principal) + context = approval["context"] + require(any( + grant.uid == uid + and grant.principal == principal + and grant.operation == operation + and grant.site == context["site"] + and grant.revision == context["revision"] + and timestamp(now) < timestamp(grant.expires_at) + for grant in self.grants + ), "Operator is not authorised for this operation, site and revision") + + def _seal(self, approval): + unsigned = {key: value for key, value in approval.items() if key != "operator_seal"} + message = b"absdev:migration-operator-approval:v2:" + approval_checksum(unsigned).encode("ascii") + return hmac.digest(self._key, message, "sha256").hex() + + def issue(self, approval, now): + require(approval["format_version"] == 1, "Expected an unsigned approval draft") + self.authorise(approval, "issue", now) + record = dict(approval, format_version=2) + record["operator_seal"] = self._seal(record) + record["checksum"] = approval_checksum(record) + return record + + def verify_seal(self, approval): + seal = approval.get("operator_seal") + if (approval["format_version"] != 2 or not isinstance(seal, str) + or not seal.isascii() or not hmac.compare_digest(seal, self._seal(approval))): + raise ApprovalError("Missing or invalid operator approval seal") + + def verify_execution(self, approval, now): + self.verify_seal(approval) + self.authorise(approval, "execute", now) diff --git a/docs/MIGRATION-OPERATOR-AUTHORISATION.md b/docs/MIGRATION-OPERATOR-AUTHORISATION.md new file mode 100644 index 0000000..4189e01 --- /dev/null +++ b/docs/MIGRATION-OPERATOR-AUTHORISATION.md @@ -0,0 +1,30 @@ +# Local migration operator authorisation + +The supported development composition accepts an `OperatorApprovalPolicy` +through `SiteOperations(operator_policy=...)`. Configure the policy in trusted +runtime code with a one-to-one mapping from dedicated OS accounts to operator +principals. The policy authenticates the process's effective UID. The operator's +login or service launcher must authenticate access to that account. A shared +service account cannot provide individual operator identity. + +Each grant names the UID, principal, operation (`issue` or `execute`), site, +exact Git revision and UTC expiry. Issue and execute grants are independent. +Both must match the same approval principal. An issue grant allows saving a +draft. Execution requires a current execute grant, a valid approval seal, and +the original approval and rehearsal checks. The coordinator verifies authority +before writing intent and the store repeats verification under its lock before +publishing the single-use consumption record. + +Supply an independently generated random key of at least 32 bytes from protected +runtime configuration. Keep it stable across process restarts and separate from +approval state. The key authenticates the complete version 2 approval payload, +including the exact rehearsal, backup and pending migrations. A version 1 +draft or record cannot authorise execution. Historical records remain readable +for audit. Unsealed recovery evidence requires manual review. Recovery evidence +verification requires access to the sealing key used for issuance. + +The runtime process, its code, policy, key, clock and state directory are trusted. +The policy is constructed from a configuration snapshot. Reload it before +further execution when grants are revoked or changed. The approved account +must never be exposed as a shared application or arbitrary command identity. +The inspection CLI remains disabled for production execution. diff --git a/tests/unit/test_approval_store.py b/tests/unit/test_approval_store.py index b24ed93..3e34f52 100644 --- a/tests/unit/test_approval_store.py +++ b/tests/unit/test_approval_store.py @@ -5,12 +5,14 @@ import stat import tempfile import unittest +from dataclasses import replace from datetime import datetime, timedelta, timezone from pathlib import Path from unittest.mock import patch -from core.approval import issue_approval +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 @@ -23,7 +25,6 @@ class ApprovalStoreTests(unittest.TestCase): self.addCleanup(self.temp.cleanup) self.root = Path(self.temp.name) - self.store = ApprovalStore(self.root) self.now = datetime( 2026, 11, 26, 10, 0, @@ -81,6 +82,15 @@ class ApprovalStoreTests(unittest.TestCase): self.identifier = self.approval["approval_id"] + self.key = os.urandom(32) + self.grants = [ + OperatorGrant(os.geteuid(), "operator", operation, self.base["site"], + self.base["revision"], self.now + timedelta(days=2)) + for operation in ("issue", "execute") + ] + self.policy = OperatorApprovalPolicy(self.grants, sealing_key=self.key) + self.store = ApprovalStore(self.root, operator_policy=self.policy) + def save(self): return self.store.save( @@ -105,15 +115,17 @@ class ApprovalStoreTests(unittest.TestCase): ) def test_save_approval(self): - self.assertEqual(self.save(), self.approval) + saved = self.save() + self.assertEqual(saved["context"], self.approval["context"]) + self.assertEqual(saved["format_version"], 2) def test_persistent_approval(self): - self.save() + saved = self.save() self.assertEqual( ApprovalStore(self.root).load(self.identifier), - self.approval, + saved, ) def test_duplicate_approval_rejected(self): @@ -152,9 +164,9 @@ class ApprovalStoreTests(unittest.TestCase): self.save() self.consume() - self.store = ApprovalStore(self.root) + self.store = ApprovalStore(self.root, operator_policy=self.policy) - with self.assertRaises(ApprovalStoreError): + with self.assertRaisesRegex(ApprovalStoreError, "already consumed"): self.consume() def test_wrong_confirmation_rejected(self): @@ -371,23 +383,23 @@ class ApprovalStoreTests(unittest.TestCase): def test_original_approval_preserved(self): - self.save() + saved = self.save() self.consume() self.assertEqual( self.store.load(self.identifier), - self.approval, + saved, ) def test_consumption_bound_to_approval(self): - self.save() + saved = self.save() result = self.consume() self.assertEqual( result["approval_checksum"], - self.approval["checksum"], + saved["checksum"], ) def test_consumption_bound_to_rehearsal(self): @@ -462,5 +474,46 @@ class ApprovalStoreTests(unittest.TestCase): ) + def test_missing_policy_denies_issuance(self): + self.store = ApprovalStore(self.root) + with self.assertRaisesRegex(ApprovalStoreError, "policy required"): + self.save() + self.assertFalse(self.store.approval_path(self.identifier).exists()) + + def test_unrecognised_os_identity_denies_issuance(self): + other_account = [replace(grant, uid=os.geteuid() + 1) for grant in self.grants] + self.store.operator_policy = OperatorApprovalPolicy(other_account, sealing_key=self.key) + with self.assertRaisesRegex(ApprovalStoreError, "not authorised"): + self.save() + self.assertFalse(self.store.approval_path(self.identifier).exists()) + + def test_execution_scope_is_checked_again(self): + self.save() + execute = self.grants[1] + for grant in (self.grants[0], replace(execute, site="other-site"), + replace(execute, revision="0" * 40), + replace(execute, principal="other-operator"), + replace(execute, expires_at=self.now)): + with self.subTest(grant=grant): + self.store.operator_policy = OperatorApprovalPolicy([grant], sealing_key=self.key) + with self.assertRaises(ApprovalStoreError): + self.consume() + self.assertFalse(self.store.consumed_path(self.identifier).exists()) + + def test_legacy_unsigned_record_cannot_execute(self): + self.store.publish(self.store.approval_path(self.identifier), self.approval) + with self.assertRaises(ApprovalStoreError): + self.consume() + self.assertFalse(self.store.consumed_path(self.identifier).exists()) + + def test_recomputed_checksum_cannot_replace_operator_seal(self): + saved = self.save() + saved["operator_seal"] = "0" * 64 + saved["checksum"] = approval_checksum(saved) + self.store.approval_path(self.identifier).write_text(json.dumps(saved)) + with self.assertRaises(ApprovalStoreError): + self.consume() + self.assertFalse(self.store.consumed_path(self.identifier).exists()) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/test_migration.py b/tests/unit/test_migration.py index b29586a..7f58aab 100644 --- a/tests/unit/test_migration.py +++ b/tests/unit/test_migration.py @@ -17,7 +17,7 @@ class MigrationTests(unittest.TestCase): self.fixture = test_approval_store.ApprovalStoreTests() self.addCleanup(self.fixture.doCleanups) self.fixture.setUp() - self.ops = SiteOperations(self.fixture.root) + self.ops = SiteOperations(self.fixture.root, operator_policy=self.fixture.policy) self.fixture.store = self.ops.approvals self.fixture.save() @@ -364,5 +364,18 @@ class MigrationTests(unittest.TestCase): self.migrate.assert_not_called() + def test_missing_execution_authority_blocks_before_containment(self): + from core.operator_approval import OperatorApprovalPolicy + + self.fixture.store.operator_policy = OperatorApprovalPolicy( + self.fixture.grants[:1], sealing_key=self.fixture.key, + ) + with self.assertRaises(MigrationError): + self.execute() + self.contain.assert_not_called() + self.migrate.assert_not_called() + self.assertFalse(self.coordinator.intent_path(self.fixture.identifier).exists()) + self.assertFalse(self.fixture.store.consumed_path(self.fixture.identifier).exists()) + if __name__ == "__main__": unittest.main()