"""Local operator identity and scoped migration approval policy.""" import hmac import json import os import stat from dataclasses import dataclass from datetime import datetime from os import geteuid from pathlib import Path 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", "reconcile"), "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 = 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) def read_protected_authority(path, *, group, max_bytes): # Ancestors are trusted; open the parent and file without following links. directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC) try: info = os.fstat(directory) require(info.st_uid == 0 and info.st_gid == group and stat.S_IMODE(info.st_mode) == 0o750, "Unsafe operator authority directory") descriptor = os.open(path.name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, dir_fd=directory) with os.fdopen(descriptor, "rb") as stream: info = os.fstat(stream.fileno()) require(stat.S_ISREG(info.st_mode) and info.st_uid == 0 and info.st_gid == group and info.st_nlink == 1 and stat.S_IMODE(info.st_mode) == 0o440, "Unsafe operator authority file") data = stream.read(max_bytes + 1) finally: os.close(directory) require(0 < len(data) <= max_bytes, "Invalid operator authority size") return data class FileOperatorAuthority: """Load a fresh, atomic authority snapshot from a trusted local provisioner.""" MAX_BYTES = 65536 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 operator authority binding") def __call__(self): data = read_protected_authority(self.path, group=self.group, max_bytes=self.MAX_BYTES) snapshot = json.loads(data) require(isinstance(snapshot, dict) and set(snapshot) == {"grants", "sealing_key"} and isinstance(snapshot["grants"], list), "Invalid operator authority snapshot") grants = [ OperatorGrant(**dict(grant, expires_at=datetime.fromisoformat(grant["expires_at"]))) for grant in snapshot["grants"] ] return OperatorApprovalPolicy(grants, sealing_key=bytes.fromhex(snapshot["sealing_key"]))