Files
absdev-deployment/core/archive.py
T
2026-11-28 09:31:26 +00:00

467 lines
12 KiB
Python

"""Verified deployment transaction archival.
Failed and migration transactions are not archived here.
External verification operations are injected.
"""
import json
import os
import re
import stat
import uuid
from datetime import datetime, timezone
from pathlib import Path
from core.backup_evidence import FIELDS
from core.compatibility import (
canonical_hash,
validate_provenance,
)
from core.locking import DeploymentLock
class ArchiveError(RuntimeError):
"""Transaction archival is unsafe or incomplete."""
def require(condition, message):
if not condition:
raise ArchiveError(message)
def unique_keys(items):
result = {}
for key, value in items:
require(
key not in result,
"Duplicate archive record key",
)
result[key] = value
return result
def digest(record):
return canonical_hash({
key: value
for key, value in record.items()
if key != "checksum"
})
def sync_directory(path):
fd = os.open(
path,
os.O_RDONLY
| os.O_DIRECTORY
| os.O_NOFOLLOW
| os.O_CLOEXEC,
)
try:
os.fsync(fd)
finally:
os.close(fd)
class TransactionArchive:
MAX_BYTES = 1024 * 1024
def __init__(
self,
*,
site,
directory,
lock_path,
journal,
releases,
provenance,
backup_evidence,
backup_verify,
health_probe,
):
self.site = site
self.directory = Path(directory).absolute()
self.lock_path = Path(lock_path)
self.journal = journal
self.releases = releases
self.provenance = provenance
self.backup_evidence = backup_evidence
self.backup_verify = backup_verify
self.health_probe = health_probe
self.validate_directory()
def validate_directory(self):
root = self.directory
require(
root.is_dir()
and not root.is_symlink()
and root.resolve() == root,
"Invalid archive directory",
)
details = root.stat()
require(
details.st_uid == os.getuid()
and stat.S_IMODE(details.st_mode) == 0o700,
"Archive directory must be private",
)
require(
root != self.journal.directory,
"Archive and active journal must be separate",
)
def path(self, identifier):
require(
isinstance(identifier, str)
and re.fullmatch(
r"[a-f0-9]{32}", identifier
) is not None,
"Invalid transaction identifier",
)
return self.directory / (
identifier + ".archive.json"
)
def load(self, identifier):
self.validate_directory()
fd = None
try:
fd = os.open(
self.path(identifier),
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 archive file",
)
with os.fdopen(fd, "rb") as handle:
fd = None
raw = handle.read(self.MAX_BYTES + 1)
require(
len(raw) <= self.MAX_BYTES,
"Archive exceeds size limit",
)
record = json.loads(
raw,
object_pairs_hook=unique_keys,
)
require(
isinstance(record, dict)
and set(record) == {
"format_version",
"status",
"site",
"transaction",
"backup_evidence",
"plan_fingerprint",
"database_restored",
"archived_at",
"checksum",
},
"Invalid archive structure",
)
require(
type(record["format_version"]) is int
and record["format_version"] == 1
and record["status"] == "ARCHIVED"
and record["site"] == self.site
and record["database_restored"] is False
and record["checksum"] == digest(record),
"Invalid archive checksum or state",
)
transaction = record["transaction"]
self.journal.validate(transaction)
require(
transaction["transaction_id"] == identifier
and transaction["site"] == self.site
and transaction["phase"] == "VERIFIED",
"Invalid archived transaction",
)
self.backup_evidence.validate(
record["backup_evidence"],
identifier,
)
return record
except ArchiveError:
raise
except Exception:
raise ArchiveError(
"Unable to validate archived transaction"
) from None
finally:
if fd is not None:
os.close(fd)
def _plan(self):
self.validate_directory()
transaction = self.journal.load()
require(
transaction is not None
and transaction["phase"] == "VERIFIED",
"Only verified transactions may be archived",
)
require(
transaction["site"] == self.site,
"Transaction site mismatch",
)
identifier = transaction["transaction_id"]
require(
not os.path.lexists(self.path(identifier)),
"Existing archive requires inspection",
)
candidate = transaction["candidate"]
require(
self.releases.current() == candidate,
"Active release differs from transaction",
)
provenance = self.provenance.verify(
self.releases.validate(candidate)
)
validate_provenance(provenance)
require(
provenance["revision"] == transaction["revision"]
and provenance["fingerprint"] == transaction["provenance"],
"Active release provenance changed",
)
evidence = self.backup_evidence.load(identifier)
backup = evidence["backup"]
manifest = self.backup_verify(
backup["backup_id"]
)
require(
isinstance(manifest, dict)
and FIELDS <= set(manifest)
and {
field: manifest[field]
for field in FIELDS
} == backup,
"Backup integrity verification failed",
)
health = self.health_probe(candidate)
require(
isinstance(health, dict)
and health.get("healthy") is True
and health.get("release") == candidate,
"Application health verification failed",
)
require(
self.journal.load() == transaction
and self.releases.current() == candidate,
"Deployment state changed during planning",
)
result = {
"format_version": 1,
"status": "ARCHIVE_READY",
"site": self.site,
"transaction_id": identifier,
"transaction_checksum": transaction["checksum"],
"backup_evidence_checksum": evidence["checksum"],
"active_release": candidate,
"confirmation": "ARCHIVE-" + identifier,
}
result["fingerprint"] = canonical_hash(result)
return result
def plan(self):
with DeploymentLock(self.lock_path):
try:
return self._plan()
except ArchiveError:
raise
except Exception:
raise ArchiveError(
"Transaction archive preflight failed"
) from None
def publish(self, identifier, record):
path = self.path(identifier)
temporary = self.directory / (
".archive-" + uuid.uuid4().hex
)
created = False
try:
with temporary.open("x", encoding="utf-8") as handle:
created = True
os.fchmod(handle.fileno(), 0o600)
json.dump(
record,
handle,
sort_keys=True,
indent=2,
allow_nan=False,
)
handle.write("\n")
handle.flush()
os.fsync(handle.fileno())
os.link(
temporary,
path,
follow_symlinks=False,
)
temporary.unlink()
created = False
sync_directory(self.directory)
require(
self.load(identifier) == record,
"Archive readback verification failed",
)
finally:
if created:
temporary.unlink(missing_ok=True)
def execute(self, *, confirmation, fingerprint):
with DeploymentLock(self.lock_path):
try:
return self._execute(
confirmation,
fingerprint,
)
except ArchiveError:
raise
except Exception:
raise ArchiveError(
"Archival failed; inspect preserved evidence"
) from None
def _execute(self, confirmation, fingerprint):
plan = self._plan()
require(
confirmation == plan["confirmation"]
and fingerprint == plan["fingerprint"],
"Archive confirmation or fingerprint mismatch",
)
with DeploymentLock(self.journal.lock_path):
self.journal.require_writes_allowed()
transaction = self.journal.load()
identifier = plan["transaction_id"]
require(
transaction is not None
and transaction["transaction_id"] == identifier
and transaction["checksum"]
== plan["transaction_checksum"],
"Active transaction changed",
)
evidence = self.backup_evidence.load(
identifier
)
require(
evidence["checksum"]
== plan["backup_evidence_checksum"],
"Backup evidence changed",
)
record = {
"format_version": 1,
"status": "ARCHIVED",
"site": self.site,
"transaction": transaction,
"backup_evidence": evidence,
"plan_fingerprint": fingerprint,
"database_restored": False,
"archived_at": datetime.now(
timezone.utc
).isoformat(),
}
record["checksum"] = digest(record)
# Publish and synchronise the archive before
# removing the active journal entry.
self.publish(identifier, record)
require(
self.journal.load() == transaction
and self.releases.current()
== plan["active_release"],
"State changed before journal retirement",
)
self.journal.path.unlink()
sync_directory(self.journal.directory)
require(
self.journal.load() is None,
"Active transaction was not retired",
)
return record