441 lines
10 KiB
Python
441 lines
10 KiB
Python
"""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,
|
|
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):
|
|
"""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, *, operator_policy=None):
|
|
|
|
self.operator_policy = operator_policy
|
|
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) in (APPROVAL_FIELDS, SEALED_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 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,
|
|
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",
|
|
)
|
|
|
|
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,
|
|
)
|
|
|
|
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,
|
|
)
|
|
|
|
self.verify_execution(
|
|
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)
|