"""Persistent deployment transaction state journal.""" import hashlib import json import os import re import stat import uuid from datetime import datetime, timezone from pathlib import Path from core.locking import DeploymentLock class TransactionError(RuntimeError): """Invalid or unsafe deployment transaction.""" TRANSITIONS = { "PREPARED": {"BACKED_UP", "FAILED"}, "BACKED_UP": {"QUIESCED", "FAILED"}, "QUIESCED": {"ACTIVATING", "FAILED"}, "ACTIVATING": {"ACTIVATED", "FAILED"}, "ACTIVATED": {"VERIFIED", "FAILED"}, "VERIFIED": set(), "FAILED": set(), } def require(condition, message): if not condition: raise TransactionError(message) def matches(value, pattern): return ( isinstance(value, str) and re.fullmatch(pattern, value) is not None ) def now(): return datetime.now(timezone.utc).isoformat() def checksum(data): payload = { key: value for key, value in data.items() if key != "checksum" } return hashlib.sha256( json.dumps( payload, sort_keys=True, separators=(",", ":"), allow_nan=False, ).encode() ).hexdigest() def unique_keys(items): result = {} for key, value in items: require( key not in result, "Duplicate transaction JSON key", ) result[key] = value return result def validate_timestamp(value): require( isinstance(value, str), "Invalid transaction timestamp", ) try: parsed = datetime.fromisoformat(value) require( parsed.utcoffset() is not None and parsed.utcoffset().total_seconds() == 0, "Transaction timestamp must use UTC", ) except ValueError as error: raise TransactionError( "Invalid transaction timestamp" ) from error class TransactionJournal: MAX_BYTES = 65536 def __init__(self, directory): self.directory = Path(directory).absolute() self.path = ( self.directory / "transaction.json" ) self.lock_path = ( self.directory / ".journal.lock" ) self.validate_directory() def validate_directory(self): directory = self.directory require( directory.is_dir() and not directory.is_symlink() and directory.resolve() == directory, "Invalid transaction directory", ) details = directory.stat() require( details.st_uid == os.getuid() and not ( stat.S_IMODE(details.st_mode) & 0o022 ), "Unsafe transaction directory permissions", ) def validate(self, data): require( isinstance(data, dict) and set(data) == { "format_version", "transaction_id", "site", "previous", "candidate", "revision", "provenance", "previous_revision", "previous_provenance", "phase", "history", "checksum", }, "Invalid transaction structure", ) require( type(data["format_version"]) is int and data["format_version"] == 1, "Unsupported transaction format", ) require( matches( data["transaction_id"], r"[a-f0-9]{32}", ), "Invalid transaction identifier", ) require( matches( data["site"], r"[a-z0-9][a-z0-9-]{0,62}", ), "Invalid transaction site", ) for key in ("previous", "candidate"): require( matches( data[key], r"[1-9][0-9]{0,19}", ), "Invalid release identifier", ) require( data["previous"] != data["candidate"], "Candidate and previous release are identical", ) require( matches(data["revision"], r"[a-f0-9]{40}"), "Invalid Git revision", ) require( matches( data["provenance"], r"[a-f0-9]{64}", ), "Invalid provenance fingerprint", ) require( isinstance(data["phase"], str) and data["phase"] in TRANSITIONS, "Invalid transaction phase", ) previous_revision = data["previous_revision"] previous_provenance = data["previous_provenance"] require( ( previous_revision is None and previous_provenance is None ) or ( matches( previous_revision, r"[a-f0-9]{40}", ) and matches( previous_provenance, r"[a-f0-9]{64}", ) ), "Invalid previous release evidence", ) history = data["history"] require( isinstance(history, list) and 1 <= len(history) <= 6, "Invalid transaction history", ) previous = None for event in history: require( isinstance(event, dict) and set(event) == {"phase", "timestamp"} and isinstance(event["phase"], str) and event["phase"] in TRANSITIONS, "Invalid transaction event", ) validate_timestamp(event["timestamp"]) phase = event["phase"] if previous is None: require( phase == "PREPARED", "Invalid initial transaction phase", ) else: require( phase in TRANSITIONS[previous], "Invalid transaction history transition", ) previous = phase require( previous == data["phase"], "Transaction history does not match phase", ) require( matches(data["checksum"], r"[a-f0-9]{64}") and checksum(data) == data["checksum"], "Transaction checksum mismatch", ) def load(self): self.validate_directory() fd = None try: fd = os.open( self.path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, ) details = os.fstat(fd) require( stat.S_ISREG(details.st_mode) and details.st_uid == os.getuid() and details.st_nlink == 1 and stat.S_IMODE(details.st_mode) == 0o600 and details.st_size <= self.MAX_BYTES, "Unsafe transaction file", ) with os.fdopen(fd, "rb") as handle: fd = None raw = handle.read(self.MAX_BYTES + 1) require( len(raw) <= self.MAX_BYTES, "Transaction exceeds size limit", ) data = json.loads( raw, object_pairs_hook=unique_keys, ) self.validate(data) return data except FileNotFoundError: return None except TransactionError: raise except (OSError, ValueError, TypeError) as error: raise TransactionError( "Unable to read transaction journal" ) from error finally: if fd is not None: os.close(fd) def _write(self, data): self.validate_directory() data["checksum"] = checksum(data) self.validate(data) temporary = self.directory / ( ".transaction-" + uuid.uuid4().hex ) fd = None created = False try: fd = os.open( temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600, ) created = True with os.fdopen(fd, "w") as handle: fd = None json.dump( data, handle, sort_keys=True, indent=2, allow_nan=False, ) handle.write("\n") handle.flush() os.fsync(handle.fileno()) os.replace(temporary, self.path) directory_fd = os.open( self.directory, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, ) try: os.fsync(directory_fd) finally: os.close(directory_fd) except OSError as error: raise TransactionError( "Unable to persist transaction; inspect journal" ) from error finally: if fd is not None: os.close(fd) if created: temporary.unlink(missing_ok=True) require( self.load() == data, "Transaction persistence verification failed", ) return data def create( self, site, previous, candidate, revision, provenance, *, previous_revision=None, previous_provenance=None, ): with DeploymentLock(self.lock_path): require( self.load() is None, "Existing transaction requires review", ) data = { "format_version": 1, "transaction_id": uuid.uuid4().hex, "site": site, "previous": previous, "candidate": candidate, "revision": revision, "provenance": provenance, "previous_revision": previous_revision, "previous_provenance": previous_provenance, "phase": "PREPARED", "history": [ { "phase": "PREPARED", "timestamp": now(), } ], } return self._write(data) def transition( self, transaction_id, expected_phase, next_phase, ): with DeploymentLock(self.lock_path): data = self.load() require( data is not None, "No active transaction", ) require( data["transaction_id"] == transaction_id, "Transaction identity mismatch", ) require( data["phase"] == expected_phase, "Transaction phase changed", ) require( isinstance(next_phase, str) and next_phase in TRANSITIONS[data["phase"]], "Invalid transaction phase transition", ) data["phase"] = next_phase data["history"].append({ "phase": next_phase, "timestamp": now(), }) return self._write(data)