Initial ABSDEV deployment framework development preview
ABSDEV Framework CI / framework-validation (push) Canceled after 0s

This commit is contained in:
2026-11-26 11:35:28 +00:00
commit d6e2317016
76 changed files with 20260 additions and 0 deletions
+419
View File
@@ -0,0 +1,419 @@
"""Persistent single-use migration approvals.
Consumption records intent, not successful migration.
No database operations are implemented here.
"""
import copy
import json
import os
import re
import stat
import uuid
from pathlib import Path
from core.approval import (
verify_approval,
timestamp,
approval_checksum,
APPROVAL_FIELDS,
)
from core.rehearsal import approval_context
from core.compatibility import canonical_hash
from core.locking import DeploymentLock
class ApprovalStoreError(RuntimeError):
"""Unsafe, missing, invalid or consumed approval."""
def require(condition, message):
if not condition:
raise ApprovalStoreError(message)
def unique_keys(items):
result = {}
for key, value in items:
require(
key not in result,
"Duplicate approval record key",
)
result[key] = value
return result
class ApprovalStore:
MAX_BYTES = 4 * 1024 * 1024
def __init__(self, directory):
self.directory = Path(directory).absolute()
self.validate_directory()
def validate_directory(self):
root = self.directory
require(
root.is_dir()
and not root.is_symlink()
and root.resolve() == root,
"Invalid approval directory",
)
details = root.stat()
require(
details.st_uid == os.getuid()
and stat.S_IMODE(details.st_mode) == 0o700,
"Approval directory must be private",
)
def path(self, identifier, suffix):
require(
isinstance(identifier, str)
and re.fullmatch(
r"[a-f0-9]{32}",
identifier,
) is not None,
"Invalid approval identifier",
)
return self.directory / (
identifier + suffix
)
def approval_path(self, identifier):
return self.path(
identifier,
".approval.json",
)
def consumed_path(self, identifier):
return self.path(
identifier,
".consumed.json",
)
def read(self, path):
self.validate_directory()
require(
path.parent == self.directory,
"Invalid approval file path",
)
fd = None
try:
fd = os.open(
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 approval record file",
)
with os.fdopen(fd, "rb") as handle:
fd = None
raw = handle.read(self.MAX_BYTES + 1)
require(
len(raw) <= self.MAX_BYTES,
"Approval record exceeds size limit",
)
return json.loads(
raw,
object_pairs_hook=unique_keys,
)
except ApprovalStoreError:
raise
except (OSError, ValueError, TypeError):
raise ApprovalStoreError(
"Unable to read approval record"
) from None
finally:
if fd is not None:
os.close(fd)
def publish(self, path, record):
self.validate_directory()
require(
path.parent == self.directory
and not os.path.lexists(path),
"Approval record already exists or path is unsafe",
)
temporary = self.directory / (
".approval-tmp-" + uuid.uuid4().hex
)
fd = None
created = False
try:
payload = (
json.dumps(
record,
sort_keys=True,
indent=2,
allow_nan=False,
) + "\n"
).encode()
require(
len(payload) <= self.MAX_BYTES,
"Approval record exceeds size limit",
)
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, "wb") as handle:
fd = None
handle.write(payload)
handle.flush()
os.fsync(handle.fileno())
# Atomic publication without replacement.
os.link(
temporary,
path,
follow_symlinks=False,
)
temporary.unlink()
created = False
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)
require(
self.read(path) == record,
"Approval record readback failed",
)
return record
except ApprovalStoreError:
raise
except (OSError, ValueError, TypeError):
raise ApprovalStoreError(
"Approval publication failed; inspect evidence"
) from None
finally:
if fd is not None:
os.close(fd)
if created:
temporary.unlink(missing_ok=True)
def load(self, identifier):
record = self.read(
self.approval_path(identifier)
)
try:
require(
isinstance(record, dict)
and set(record) == APPROVAL_FIELDS,
"Invalid stored approval structure",
)
require(
record["approval_id"] == identifier
and record["checksum"]
== approval_checksum(record),
"Stored approval identity or checksum mismatch",
)
except ApprovalStoreError:
raise
except (ValueError, TypeError, KeyError):
raise ApprovalStoreError(
"Invalid stored approval"
) from None
return record
def save(
self,
approval,
context,
*,
confirmation,
now,
):
try:
record = copy.deepcopy(approval)
verify_approval(
record,
context,
confirmation=confirmation,
now=now,
)
except Exception:
raise ApprovalStoreError(
"Approval validation failed"
) from None
self.validate_directory()
with DeploymentLock(
self.directory / ".approval.lock"
):
identifier = record["approval_id"]
require(
not os.path.lexists(
self.consumed_path(identifier)
),
"Approval has already been consumed",
)
return self.publish(
self.approval_path(identifier),
record,
)
def consume(
self,
identifier,
base_context,
rehearsal,
*,
confirmation,
now,
):
self.validate_directory()
with DeploymentLock(
self.directory / ".approval.lock"
):
marker = self.consumed_path(identifier)
# Even corrupt or incomplete consumption
# evidence prevents another execution.
require(
not os.path.lexists(marker),
"Approval already consumed; review required",
)
approval = self.load(identifier)
try:
context = approval_context(
rehearsal,
base_context,
now=now,
)
verify_approval(
approval,
context,
confirmation=confirmation,
now=now,
)
except Exception:
raise ApprovalStoreError(
"Approval or rehearsal validation failed"
) from None
record = {
"format_version": 1,
"status": "CONSUMED",
"approval_id": identifier,
"approval_checksum": approval["checksum"],
"site": context["site"],
"release": context["release"],
"revision": context["revision"],
"database_identity": context["database_identity"],
"backup_sha256": context["backup_sha256"],
"rehearsal_fingerprint": (
context["rehearsal_fingerprint"]
),
"consumed_at": timestamp(now).isoformat(),
"migration_executed": False,
}
record["checksum"] = canonical_hash(record)
return self.publish(marker, record)