Initial ABSDEV deployment framework development preview
ABSDEV Framework CI / framework-validation (push) Canceled after 0s
ABSDEV Framework CI / framework-validation (push) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,304 @@
|
||||
"""Strict migration approval validation.
|
||||
|
||||
This module validates approval records only.
|
||||
It does not authenticate operators or execute migrations.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from core.compatibility import canonical_hash
|
||||
|
||||
|
||||
class ApprovalError(RuntimeError):
|
||||
"""Invalid, expired or mismatched migration approval."""
|
||||
|
||||
|
||||
CONTEXT_FIELDS = {
|
||||
"site",
|
||||
"release",
|
||||
"revision",
|
||||
"provenance",
|
||||
"compatibility",
|
||||
"database_identity",
|
||||
"backup_sha256",
|
||||
"rehearsal_fingerprint",
|
||||
"pending_migrations",
|
||||
}
|
||||
|
||||
APPROVAL_FIELDS = {
|
||||
"format_version",
|
||||
"approval_id",
|
||||
"approver",
|
||||
"context",
|
||||
"issued_at",
|
||||
"expires_at",
|
||||
"confirmation",
|
||||
"checksum",
|
||||
}
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
|
||||
if not condition:
|
||||
raise ApprovalError(message)
|
||||
|
||||
|
||||
def matches(value, pattern):
|
||||
|
||||
return (
|
||||
isinstance(value, str)
|
||||
and re.fullmatch(pattern, value) is not None
|
||||
)
|
||||
|
||||
|
||||
def timestamp(value):
|
||||
|
||||
require(
|
||||
isinstance(value, datetime)
|
||||
and value.utcoffset() is not None,
|
||||
"Timezone-aware timestamp required",
|
||||
)
|
||||
|
||||
return value.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def parse_timestamp(value):
|
||||
|
||||
require(
|
||||
isinstance(value, str),
|
||||
"Invalid approval timestamp",
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
parsed = datetime.fromisoformat(value)
|
||||
|
||||
return timestamp(parsed)
|
||||
|
||||
except (ValueError, OverflowError):
|
||||
|
||||
raise ApprovalError(
|
||||
"Invalid approval timestamp"
|
||||
) from None
|
||||
|
||||
|
||||
def validate_context(context):
|
||||
|
||||
require(
|
||||
isinstance(context, dict)
|
||||
and set(context) == CONTEXT_FIELDS,
|
||||
"Invalid migration approval context",
|
||||
)
|
||||
|
||||
require(
|
||||
matches(
|
||||
context["site"],
|
||||
r"[a-z0-9][a-z0-9-]{0,62}",
|
||||
),
|
||||
"Invalid site identifier",
|
||||
)
|
||||
|
||||
require(
|
||||
matches(
|
||||
context["release"],
|
||||
r"[1-9][0-9]{0,19}",
|
||||
),
|
||||
"Invalid release identifier",
|
||||
)
|
||||
|
||||
require(
|
||||
matches(
|
||||
context["revision"],
|
||||
r"[a-f0-9]{40}",
|
||||
),
|
||||
"Invalid Git revision",
|
||||
)
|
||||
|
||||
for field in (
|
||||
"provenance",
|
||||
"compatibility",
|
||||
"database_identity",
|
||||
"backup_sha256",
|
||||
"rehearsal_fingerprint",
|
||||
):
|
||||
|
||||
require(
|
||||
matches(
|
||||
context[field],
|
||||
r"[a-f0-9]{64}",
|
||||
),
|
||||
f"Invalid approval evidence: {field}",
|
||||
)
|
||||
|
||||
pending = context["pending_migrations"]
|
||||
|
||||
require(
|
||||
isinstance(pending, list)
|
||||
and 1 <= len(pending) <= 10000,
|
||||
"Invalid pending migration inventory",
|
||||
)
|
||||
|
||||
for name in pending:
|
||||
|
||||
require(
|
||||
matches(
|
||||
name,
|
||||
r"[A-Za-z0-9_][A-Za-z0-9_-]{0,254}",
|
||||
),
|
||||
"Invalid pending migration name",
|
||||
)
|
||||
|
||||
require(
|
||||
len(set(pending)) == len(pending),
|
||||
"Duplicate pending migrations",
|
||||
)
|
||||
|
||||
|
||||
def validate_approver(approver):
|
||||
|
||||
require(
|
||||
matches(
|
||||
approver,
|
||||
r"[A-Za-z0-9][A-Za-z0-9_.@-]{0,127}",
|
||||
),
|
||||
"Invalid approver identifier",
|
||||
)
|
||||
|
||||
|
||||
def approval_checksum(approval):
|
||||
|
||||
return canonical_hash({
|
||||
key: value
|
||||
for key, value in approval.items()
|
||||
if key != "checksum"
|
||||
})
|
||||
|
||||
|
||||
def issue_approval(
|
||||
context,
|
||||
*,
|
||||
approver,
|
||||
now,
|
||||
ttl_hours=24,
|
||||
):
|
||||
|
||||
validate_context(context)
|
||||
validate_approver(approver)
|
||||
|
||||
issued = timestamp(now)
|
||||
|
||||
require(
|
||||
type(ttl_hours) is int
|
||||
and 1 <= ttl_hours <= 24,
|
||||
"Approval lifetime must be between 1 and 24 hours",
|
||||
)
|
||||
|
||||
approval_id = uuid.uuid4().hex
|
||||
|
||||
approval = {
|
||||
"format_version": 1,
|
||||
"approval_id": approval_id,
|
||||
"approver": approver,
|
||||
"context": copy.deepcopy(context),
|
||||
"issued_at": issued.isoformat(),
|
||||
"expires_at": (
|
||||
issued + timedelta(hours=ttl_hours)
|
||||
).isoformat(),
|
||||
"confirmation": (
|
||||
"MIGRATE-" + approval_id
|
||||
),
|
||||
}
|
||||
|
||||
approval["checksum"] = approval_checksum(
|
||||
approval
|
||||
)
|
||||
|
||||
return approval
|
||||
|
||||
|
||||
def verify_approval(
|
||||
approval,
|
||||
context,
|
||||
*,
|
||||
confirmation,
|
||||
now,
|
||||
):
|
||||
|
||||
validate_context(context)
|
||||
|
||||
require(
|
||||
isinstance(approval, dict)
|
||||
and set(approval) == APPROVAL_FIELDS,
|
||||
"Invalid approval record",
|
||||
)
|
||||
|
||||
require(
|
||||
type(approval["format_version"]) is int
|
||||
and approval["format_version"] == 1,
|
||||
"Unsupported approval format",
|
||||
)
|
||||
|
||||
require(
|
||||
matches(
|
||||
approval["approval_id"],
|
||||
r"[a-f0-9]{32}",
|
||||
),
|
||||
"Invalid approval identifier",
|
||||
)
|
||||
|
||||
validate_approver(approval["approver"])
|
||||
validate_context(approval["context"])
|
||||
|
||||
require(
|
||||
matches(
|
||||
approval["checksum"],
|
||||
r"[a-f0-9]{64}",
|
||||
)
|
||||
and approval_checksum(approval)
|
||||
== approval["checksum"],
|
||||
"Approval checksum mismatch",
|
||||
)
|
||||
|
||||
require(
|
||||
approval["context"] == context,
|
||||
"Migration approval context changed",
|
||||
)
|
||||
|
||||
expected = (
|
||||
"MIGRATE-" + approval["approval_id"]
|
||||
)
|
||||
|
||||
require(
|
||||
isinstance(confirmation, str)
|
||||
and confirmation == expected
|
||||
and approval["confirmation"] == expected,
|
||||
"Migration confirmation mismatch",
|
||||
)
|
||||
|
||||
issued = parse_timestamp(
|
||||
approval["issued_at"]
|
||||
)
|
||||
|
||||
expires = parse_timestamp(
|
||||
approval["expires_at"]
|
||||
)
|
||||
|
||||
current = timestamp(now)
|
||||
|
||||
require(
|
||||
timedelta(0)
|
||||
< expires - issued
|
||||
<= timedelta(hours=24),
|
||||
"Invalid approval lifetime",
|
||||
)
|
||||
|
||||
require(
|
||||
issued <= current < expires,
|
||||
"Approval expired or not yet valid",
|
||||
)
|
||||
|
||||
return True
|
||||
@@ -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)
|
||||
+465
@@ -0,0 +1,465 @@
|
||||
"""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):
|
||||
|
||||
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
|
||||
+450
@@ -0,0 +1,450 @@
|
||||
"""Recovery-aware database backup storage.
|
||||
|
||||
Execution is delegated to an explicitly supplied runner.
|
||||
This module does not connect directly to a database.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import tempfile
|
||||
import uuid
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class BackupError(RuntimeError):
|
||||
"""Invalid or unsuccessful backup operation."""
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
|
||||
if not condition:
|
||||
raise BackupError(message)
|
||||
|
||||
|
||||
def sync_directory(path):
|
||||
|
||||
fd = os.open(
|
||||
path,
|
||||
os.O_RDONLY
|
||||
| os.O_DIRECTORY
|
||||
| os.O_NOFOLLOW,
|
||||
)
|
||||
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def secure_directory(path):
|
||||
|
||||
details = path.lstat()
|
||||
|
||||
require(
|
||||
stat.S_ISDIR(details.st_mode)
|
||||
and details.st_uid == os.getuid()
|
||||
and stat.S_IMODE(details.st_mode) == 0o700,
|
||||
"Unsafe backup directory",
|
||||
)
|
||||
|
||||
|
||||
def secure_file(path):
|
||||
|
||||
details = path.lstat()
|
||||
|
||||
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,
|
||||
"Unsafe backup file",
|
||||
)
|
||||
|
||||
|
||||
def open_new(path):
|
||||
|
||||
fd = os.open(
|
||||
path,
|
||||
os.O_WRONLY
|
||||
| os.O_CREAT
|
||||
| os.O_EXCL
|
||||
| os.O_NOFOLLOW,
|
||||
0o600,
|
||||
)
|
||||
|
||||
return os.fdopen(fd, "wb")
|
||||
|
||||
|
||||
def checksum(path):
|
||||
|
||||
secure_file(path)
|
||||
|
||||
fd = os.open(
|
||||
path,
|
||||
os.O_RDONLY | os.O_NOFOLLOW,
|
||||
)
|
||||
|
||||
with os.fdopen(fd, "rb") as handle:
|
||||
|
||||
digest = hashlib.sha256()
|
||||
size = 0
|
||||
|
||||
for block in iter(
|
||||
lambda: handle.read(1024 * 1024),
|
||||
b"",
|
||||
):
|
||||
|
||||
digest.update(block)
|
||||
size += len(block)
|
||||
|
||||
return digest.hexdigest(), size
|
||||
|
||||
|
||||
def flush_file(handle):
|
||||
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
|
||||
|
||||
class BackupEngine:
|
||||
|
||||
def __init__(self, adapter, directory, runner):
|
||||
|
||||
self.adapter = adapter
|
||||
self.root = Path(directory).absolute()
|
||||
self.runner = runner
|
||||
|
||||
require(
|
||||
callable(runner),
|
||||
"Backup execution runner is required",
|
||||
)
|
||||
|
||||
require(
|
||||
adapter.database["driver"]
|
||||
in ("mysql", "pgsql"),
|
||||
"Unsupported backup adapter",
|
||||
)
|
||||
|
||||
self.filename = (
|
||||
"database.sql"
|
||||
if adapter.database["driver"] == "mysql"
|
||||
else "database.dump"
|
||||
)
|
||||
|
||||
def identity(self):
|
||||
|
||||
output = io.BytesIO()
|
||||
|
||||
self.runner(
|
||||
self.adapter.identity_command(),
|
||||
output,
|
||||
)
|
||||
|
||||
raw = output.getvalue().decode("utf-8").strip()
|
||||
|
||||
require(
|
||||
raw and "\n" not in raw,
|
||||
"Invalid database identity output",
|
||||
)
|
||||
|
||||
driver = self.adapter.database["driver"]
|
||||
|
||||
separator = "\t" if driver == "mysql" else "|"
|
||||
|
||||
parts = raw.split(separator)
|
||||
|
||||
require(
|
||||
len(parts) == (3 if driver == "mysql" else 2),
|
||||
"Unexpected database identity format",
|
||||
)
|
||||
|
||||
name = parts[0]
|
||||
account = parts[1]
|
||||
|
||||
username = (
|
||||
account.rsplit("@", 1)[0]
|
||||
if driver == "mysql"
|
||||
else account
|
||||
)
|
||||
|
||||
require(
|
||||
name == self.adapter.database["name"],
|
||||
"Database identity mismatch",
|
||||
)
|
||||
|
||||
require(
|
||||
username == self.adapter.database["username"],
|
||||
"Database account mismatch",
|
||||
)
|
||||
|
||||
if driver == "mysql":
|
||||
|
||||
require(
|
||||
bool(parts[2]),
|
||||
"Missing database server identity",
|
||||
)
|
||||
|
||||
return raw
|
||||
|
||||
def create(self):
|
||||
|
||||
temporary = None
|
||||
published = None
|
||||
|
||||
try:
|
||||
|
||||
secure_directory(self.root)
|
||||
|
||||
identity_before = self.identity()
|
||||
|
||||
stamp = datetime.now(timezone.utc).strftime(
|
||||
"%Y%m%dT%H%M%S"
|
||||
)
|
||||
|
||||
backup_id = (
|
||||
f"backup-{stamp}-{uuid.uuid4().hex}"
|
||||
)
|
||||
|
||||
destination = self.root / backup_id
|
||||
|
||||
temporary = Path(
|
||||
tempfile.mkdtemp(
|
||||
prefix=".partial-",
|
||||
dir=self.root,
|
||||
)
|
||||
)
|
||||
|
||||
secure_directory(temporary)
|
||||
|
||||
artifact = temporary / self.filename
|
||||
|
||||
with open_new(artifact) as handle:
|
||||
|
||||
self.runner(
|
||||
self.adapter.backup_command(),
|
||||
handle,
|
||||
)
|
||||
|
||||
flush_file(handle)
|
||||
|
||||
digest, size = checksum(artifact)
|
||||
|
||||
require(size > 0, "Database backup is empty")
|
||||
|
||||
identity_after = self.identity()
|
||||
|
||||
require(
|
||||
identity_before == identity_after,
|
||||
"Database identity changed during backup",
|
||||
)
|
||||
|
||||
manifest = {
|
||||
"format_version": 1,
|
||||
"backup_id": backup_id,
|
||||
"created_at": datetime.now(
|
||||
timezone.utc
|
||||
).isoformat(),
|
||||
"driver": self.adapter.database["driver"],
|
||||
"database": self.adapter.database["name"],
|
||||
"username": self.adapter.database["username"],
|
||||
"container": self.adapter.database["container"],
|
||||
"identity": identity_before,
|
||||
"filename": self.filename,
|
||||
"sha256": digest,
|
||||
"bytes": size,
|
||||
}
|
||||
|
||||
with open_new(
|
||||
temporary / "manifest.json"
|
||||
) as handle:
|
||||
|
||||
handle.write(
|
||||
(
|
||||
json.dumps(
|
||||
manifest,
|
||||
indent=2,
|
||||
sort_keys=True,
|
||||
)
|
||||
+ "\n"
|
||||
).encode()
|
||||
)
|
||||
|
||||
flush_file(handle)
|
||||
|
||||
sync_directory(temporary)
|
||||
|
||||
require(
|
||||
not destination.exists()
|
||||
and not destination.is_symlink(),
|
||||
"Backup destination already exists",
|
||||
)
|
||||
|
||||
os.rename(temporary, destination)
|
||||
|
||||
temporary = None
|
||||
published = destination
|
||||
|
||||
sync_directory(self.root)
|
||||
|
||||
self.verify(destination)
|
||||
|
||||
return destination
|
||||
|
||||
except Exception as error:
|
||||
|
||||
if temporary is not None:
|
||||
|
||||
shutil.rmtree(temporary)
|
||||
|
||||
sync_directory(self.root)
|
||||
|
||||
if published is not None:
|
||||
|
||||
# Withdraw an unsuccessful publication.
|
||||
# Preserve evidence rather than deleting it.
|
||||
|
||||
failed = self.root / (
|
||||
".failed-" + uuid.uuid4().hex
|
||||
)
|
||||
|
||||
os.rename(published, failed)
|
||||
sync_directory(self.root)
|
||||
|
||||
if isinstance(error, BackupError):
|
||||
raise
|
||||
|
||||
raise BackupError(
|
||||
"Backup creation failed"
|
||||
) from error
|
||||
|
||||
def verify(self, directory):
|
||||
|
||||
try:
|
||||
|
||||
secure_directory(self.root)
|
||||
|
||||
directory = Path(directory).absolute()
|
||||
|
||||
require(
|
||||
directory.parent == self.root,
|
||||
"Backup is outside the configured directory",
|
||||
)
|
||||
|
||||
require(
|
||||
re.fullmatch(
|
||||
r"backup-\d{8}T\d{6}-[a-f0-9]{32}",
|
||||
directory.name,
|
||||
) is not None,
|
||||
"Invalid backup directory name",
|
||||
)
|
||||
|
||||
secure_directory(directory)
|
||||
|
||||
require(
|
||||
{path.name for path in directory.iterdir()}
|
||||
== {self.filename, "manifest.json"},
|
||||
"Unexpected backup directory contents",
|
||||
)
|
||||
|
||||
manifest_path = directory / "manifest.json"
|
||||
|
||||
secure_file(manifest_path)
|
||||
|
||||
require(
|
||||
manifest_path.stat().st_size <= 65536,
|
||||
"Oversized backup manifest",
|
||||
)
|
||||
|
||||
fd = os.open(
|
||||
manifest_path,
|
||||
os.O_RDONLY | os.O_NOFOLLOW,
|
||||
)
|
||||
|
||||
with os.fdopen(fd, "r", encoding="utf-8") as handle:
|
||||
|
||||
manifest = json.load(handle)
|
||||
|
||||
fields = {
|
||||
"format_version",
|
||||
"backup_id",
|
||||
"created_at",
|
||||
"driver",
|
||||
"database",
|
||||
"username",
|
||||
"container",
|
||||
"identity",
|
||||
"filename",
|
||||
"sha256",
|
||||
"bytes",
|
||||
}
|
||||
|
||||
require(
|
||||
isinstance(manifest, dict)
|
||||
and set(manifest) == fields,
|
||||
"Invalid backup manifest",
|
||||
)
|
||||
|
||||
expected = {
|
||||
"format_version": 1,
|
||||
"backup_id": directory.name,
|
||||
"driver": self.adapter.database["driver"],
|
||||
"database": self.adapter.database["name"],
|
||||
"username": self.adapter.database["username"],
|
||||
"container": self.adapter.database["container"],
|
||||
"filename": self.filename,
|
||||
}
|
||||
|
||||
for key, value in expected.items():
|
||||
|
||||
require(
|
||||
manifest[key] == value,
|
||||
f"Backup manifest mismatch: {key}",
|
||||
)
|
||||
|
||||
require(
|
||||
isinstance(manifest["sha256"], str)
|
||||
and re.fullmatch(
|
||||
r"[a-f0-9]{64}",
|
||||
manifest["sha256"],
|
||||
) is not None,
|
||||
"Invalid backup checksum",
|
||||
)
|
||||
|
||||
require(
|
||||
type(manifest["bytes"]) is int
|
||||
and manifest["bytes"] > 0,
|
||||
"Invalid backup size",
|
||||
)
|
||||
|
||||
digest, size = checksum(
|
||||
directory / self.filename
|
||||
)
|
||||
|
||||
require(
|
||||
digest == manifest["sha256"],
|
||||
"Backup checksum mismatch",
|
||||
)
|
||||
|
||||
require(
|
||||
size == manifest["bytes"],
|
||||
"Backup size mismatch",
|
||||
)
|
||||
|
||||
return manifest
|
||||
|
||||
except BackupError:
|
||||
|
||||
raise
|
||||
|
||||
except Exception as error:
|
||||
|
||||
raise BackupError(
|
||||
"Backup verification failed"
|
||||
) from error
|
||||
@@ -0,0 +1,424 @@
|
||||
"""Persistent transaction-bound database backup evidence."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
import uuid
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from core.locking import DeploymentLock
|
||||
|
||||
|
||||
class EvidenceError(RuntimeError):
|
||||
"""Missing, invalid or unsafe backup evidence."""
|
||||
|
||||
|
||||
FIELDS = {
|
||||
"backup_id",
|
||||
"driver",
|
||||
"database",
|
||||
"username",
|
||||
"container",
|
||||
"identity",
|
||||
"filename",
|
||||
"sha256",
|
||||
"bytes",
|
||||
}
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
|
||||
if not condition:
|
||||
raise EvidenceError(message)
|
||||
|
||||
|
||||
def matches(value, pattern):
|
||||
|
||||
return (
|
||||
isinstance(value, str)
|
||||
and re.fullmatch(pattern, value) is not None
|
||||
)
|
||||
|
||||
|
||||
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 backup evidence key",
|
||||
)
|
||||
|
||||
result[key] = value
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class BackupEvidence:
|
||||
|
||||
MAX_BYTES = 65536
|
||||
|
||||
def __init__(self, directory):
|
||||
|
||||
self.directory = Path(directory).absolute()
|
||||
|
||||
self.validate_directory()
|
||||
|
||||
def validate_directory(self):
|
||||
|
||||
root = self.directory
|
||||
|
||||
require(
|
||||
root.is_dir()
|
||||
and root.resolve() == root
|
||||
and not root.is_symlink(),
|
||||
"Invalid backup evidence directory",
|
||||
)
|
||||
|
||||
details = root.stat()
|
||||
|
||||
require(
|
||||
details.st_uid == os.getuid()
|
||||
and not (
|
||||
stat.S_IMODE(details.st_mode) & 0o077
|
||||
),
|
||||
"Unsafe backup evidence directory permissions",
|
||||
)
|
||||
|
||||
def path(self, transaction_id):
|
||||
|
||||
require(
|
||||
matches(
|
||||
transaction_id,
|
||||
r"[a-f0-9]{32}",
|
||||
),
|
||||
"Invalid transaction identifier",
|
||||
)
|
||||
|
||||
return self.directory / (
|
||||
transaction_id + ".backup.json"
|
||||
)
|
||||
|
||||
def validate_backup(self, backup):
|
||||
|
||||
require(
|
||||
isinstance(backup, dict)
|
||||
and set(backup) == FIELDS,
|
||||
"Invalid backup evidence structure",
|
||||
)
|
||||
|
||||
require(
|
||||
matches(
|
||||
backup["backup_id"],
|
||||
r"[A-Za-z0-9][A-Za-z0-9_.-]{0,199}",
|
||||
)
|
||||
and ".." not in backup["backup_id"],
|
||||
"Invalid backup identifier",
|
||||
)
|
||||
|
||||
require(
|
||||
backup["driver"] in (
|
||||
"mysql",
|
||||
"postgresql",
|
||||
),
|
||||
"Invalid database driver",
|
||||
)
|
||||
|
||||
for field in (
|
||||
"database",
|
||||
"username",
|
||||
"container",
|
||||
):
|
||||
|
||||
require(
|
||||
matches(
|
||||
backup[field],
|
||||
r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}",
|
||||
),
|
||||
f"Invalid backup {field}",
|
||||
)
|
||||
|
||||
require(
|
||||
isinstance(backup["identity"], str)
|
||||
and 1 <= len(backup["identity"]) <= 4096
|
||||
and "\x00" not in backup["identity"],
|
||||
"Invalid database identity",
|
||||
)
|
||||
|
||||
filename = {
|
||||
"mysql": "database.sql",
|
||||
"postgresql": "database.dump",
|
||||
}[backup["driver"]]
|
||||
|
||||
require(
|
||||
backup["filename"] == filename,
|
||||
"Invalid backup filename",
|
||||
)
|
||||
|
||||
require(
|
||||
matches(
|
||||
backup["sha256"],
|
||||
r"[a-f0-9]{64}",
|
||||
),
|
||||
"Invalid backup checksum",
|
||||
)
|
||||
|
||||
require(
|
||||
type(backup["bytes"]) is int
|
||||
and backup["bytes"] > 0,
|
||||
"Invalid backup size",
|
||||
)
|
||||
|
||||
def validate(self, data, transaction_id):
|
||||
|
||||
require(
|
||||
isinstance(data, dict)
|
||||
and set(data) == {
|
||||
"format_version",
|
||||
"transaction_id",
|
||||
"backup",
|
||||
"checksum",
|
||||
},
|
||||
"Invalid backup evidence record",
|
||||
)
|
||||
|
||||
require(
|
||||
type(data["format_version"]) is int
|
||||
and data["format_version"] == 1,
|
||||
"Unsupported evidence format",
|
||||
)
|
||||
|
||||
require(
|
||||
data["transaction_id"] == transaction_id,
|
||||
"Backup evidence transaction mismatch",
|
||||
)
|
||||
|
||||
self.validate_backup(data["backup"])
|
||||
|
||||
require(
|
||||
matches(
|
||||
data["checksum"],
|
||||
r"[a-f0-9]{64}",
|
||||
)
|
||||
and checksum(data) == data["checksum"],
|
||||
"Backup evidence checksum mismatch",
|
||||
)
|
||||
|
||||
def load(self, transaction_id):
|
||||
|
||||
self.validate_directory()
|
||||
|
||||
path = self.path(transaction_id)
|
||||
|
||||
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 backup evidence file",
|
||||
)
|
||||
|
||||
with os.fdopen(fd, "rb") as handle:
|
||||
|
||||
fd = None
|
||||
|
||||
raw = handle.read(
|
||||
self.MAX_BYTES + 1
|
||||
)
|
||||
|
||||
require(
|
||||
len(raw) <= self.MAX_BYTES,
|
||||
"Backup evidence exceeds size limit",
|
||||
)
|
||||
|
||||
data = json.loads(
|
||||
raw,
|
||||
object_pairs_hook=unique_keys,
|
||||
)
|
||||
|
||||
self.validate(
|
||||
data,
|
||||
transaction_id,
|
||||
)
|
||||
|
||||
return data
|
||||
|
||||
except EvidenceError:
|
||||
|
||||
raise
|
||||
|
||||
except (
|
||||
OSError,
|
||||
ValueError,
|
||||
TypeError,
|
||||
) as error:
|
||||
|
||||
raise EvidenceError(
|
||||
"Unable to read backup evidence"
|
||||
) from error
|
||||
|
||||
finally:
|
||||
|
||||
if fd is not None:
|
||||
os.close(fd)
|
||||
|
||||
def create(self, transaction_id, manifest):
|
||||
|
||||
self.validate_directory()
|
||||
|
||||
path = self.path(transaction_id)
|
||||
|
||||
require(
|
||||
isinstance(manifest, dict)
|
||||
and FIELDS <= set(manifest),
|
||||
"Incomplete backup manifest",
|
||||
)
|
||||
|
||||
backup = {
|
||||
field: manifest[field]
|
||||
for field in FIELDS
|
||||
}
|
||||
|
||||
self.validate_backup(backup)
|
||||
|
||||
data = {
|
||||
"format_version": 1,
|
||||
"transaction_id": transaction_id,
|
||||
"backup": backup,
|
||||
}
|
||||
|
||||
data["checksum"] = checksum(data)
|
||||
|
||||
self.validate(
|
||||
data,
|
||||
transaction_id,
|
||||
)
|
||||
|
||||
with DeploymentLock(
|
||||
self.directory / ".backup-evidence.lock"
|
||||
):
|
||||
|
||||
require(
|
||||
not path.exists()
|
||||
and not path.is_symlink(),
|
||||
"Existing backup evidence cannot be overwritten",
|
||||
)
|
||||
|
||||
temporary = self.directory / (
|
||||
".backup-evidence-"
|
||||
+ 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())
|
||||
|
||||
# Publish without overwriting existing evidence.
|
||||
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)
|
||||
|
||||
except OSError as error:
|
||||
|
||||
raise EvidenceError(
|
||||
"Unable to persist backup evidence"
|
||||
) from error
|
||||
|
||||
finally:
|
||||
|
||||
if fd is not None:
|
||||
os.close(fd)
|
||||
|
||||
if created:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
require(
|
||||
self.load(transaction_id) == data,
|
||||
"Backup evidence verification failed",
|
||||
)
|
||||
|
||||
return data
|
||||
@@ -0,0 +1,221 @@
|
||||
"""Conservative migration compatibility assessment."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
|
||||
from pathlib import PurePosixPath
|
||||
|
||||
from core.provenance import DEPENDENCIES
|
||||
|
||||
|
||||
class CompatibilityError(RuntimeError):
|
||||
"""Migration compatibility could not be established."""
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
|
||||
if not condition:
|
||||
raise CompatibilityError(message)
|
||||
|
||||
|
||||
def valid_hash(value, length):
|
||||
|
||||
return (
|
||||
isinstance(value, str)
|
||||
and re.fullmatch(
|
||||
rf"[a-f0-9]{{{length}}}",
|
||||
value,
|
||||
) is not None
|
||||
)
|
||||
|
||||
|
||||
def canonical_hash(data):
|
||||
|
||||
encoded = json.dumps(
|
||||
data,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
allow_nan=False,
|
||||
).encode("utf-8")
|
||||
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def provenance_fingerprint(data):
|
||||
|
||||
require(
|
||||
isinstance(data, dict),
|
||||
"Invalid provenance evidence",
|
||||
)
|
||||
|
||||
return canonical_hash({
|
||||
key: value
|
||||
for key, value in data.items()
|
||||
if key != "fingerprint"
|
||||
})
|
||||
|
||||
|
||||
def validate_migration_path(value):
|
||||
|
||||
require(
|
||||
isinstance(value, str),
|
||||
"Invalid migration path",
|
||||
)
|
||||
|
||||
path = PurePosixPath(value)
|
||||
|
||||
require(
|
||||
not path.is_absolute()
|
||||
and path.as_posix() == value
|
||||
and ".." not in path.parts
|
||||
and len(path.parts) >= 3
|
||||
and path.parts[:2] == ("database", "migrations")
|
||||
and path.suffix == ".php"
|
||||
and all(
|
||||
re.fullmatch(
|
||||
r"[A-Za-z0-9_.-]+", part
|
||||
) is not None
|
||||
for part in path.parts
|
||||
),
|
||||
"Unsafe migration path",
|
||||
)
|
||||
|
||||
|
||||
def validate_provenance(data):
|
||||
|
||||
require(
|
||||
isinstance(data, dict)
|
||||
and set(data) == {
|
||||
"format_version",
|
||||
"revision",
|
||||
"migrations",
|
||||
"dependencies",
|
||||
"fingerprint",
|
||||
},
|
||||
"Invalid provenance evidence structure",
|
||||
)
|
||||
|
||||
require(
|
||||
type(data["format_version"]) is int
|
||||
and data["format_version"] == 1,
|
||||
"Unsupported provenance format",
|
||||
)
|
||||
|
||||
require(
|
||||
valid_hash(data["revision"], 40),
|
||||
"Invalid Git revision",
|
||||
)
|
||||
|
||||
require(
|
||||
isinstance(data["migrations"], dict),
|
||||
"Invalid migration inventory",
|
||||
)
|
||||
|
||||
require(
|
||||
isinstance(data["dependencies"], dict)
|
||||
and set(data["dependencies"]) == set(DEPENDENCIES),
|
||||
"Invalid dependency inventory",
|
||||
)
|
||||
|
||||
for name, digest in data["migrations"].items():
|
||||
|
||||
validate_migration_path(name)
|
||||
|
||||
require(
|
||||
valid_hash(digest, 64),
|
||||
"Invalid migration checksum",
|
||||
)
|
||||
|
||||
for digest in data["dependencies"].values():
|
||||
|
||||
require(
|
||||
valid_hash(digest, 64),
|
||||
"Invalid dependency checksum",
|
||||
)
|
||||
|
||||
require(
|
||||
valid_hash(data["fingerprint"], 64)
|
||||
and provenance_fingerprint(data)
|
||||
== data["fingerprint"],
|
||||
"Provenance fingerprint mismatch",
|
||||
)
|
||||
|
||||
|
||||
def compare_migrations(previous, candidate):
|
||||
|
||||
validate_provenance(previous)
|
||||
validate_provenance(candidate)
|
||||
|
||||
same_revision = (
|
||||
previous["revision"] == candidate["revision"]
|
||||
)
|
||||
|
||||
require(
|
||||
not same_revision
|
||||
or previous["fingerprint"] == candidate["fingerprint"],
|
||||
"Conflicting evidence for identical Git revision",
|
||||
)
|
||||
|
||||
old = previous["migrations"]
|
||||
new = candidate["migrations"]
|
||||
|
||||
old_names = set(old)
|
||||
new_names = set(new)
|
||||
|
||||
added = sorted(new_names - old_names)
|
||||
removed = sorted(old_names - new_names)
|
||||
|
||||
modified = sorted(
|
||||
name
|
||||
for name in old_names & new_names
|
||||
if old[name] != new[name]
|
||||
)
|
||||
|
||||
unchanged = sorted(
|
||||
name
|
||||
for name in old_names & new_names
|
||||
if old[name] == new[name]
|
||||
)
|
||||
|
||||
compatible = not (
|
||||
added or removed or modified
|
||||
)
|
||||
|
||||
result = {
|
||||
"format_version": 1,
|
||||
"previous_revision": previous["revision"],
|
||||
"candidate_revision": candidate["revision"],
|
||||
"previous_fingerprint": previous["fingerprint"],
|
||||
"candidate_fingerprint": candidate["fingerprint"],
|
||||
"same_revision": same_revision,
|
||||
"previous_count": len(old),
|
||||
"candidate_count": len(new),
|
||||
"unchanged_count": len(unchanged),
|
||||
"added": added,
|
||||
"removed": removed,
|
||||
"modified": modified,
|
||||
"unchanged": unchanged,
|
||||
"compatible_without_migrations": compatible,
|
||||
"requires_migration_review": not compatible,
|
||||
"database_runtime_verified": False,
|
||||
}
|
||||
|
||||
result["fingerprint"] = canonical_hash(result)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def require_compatible(previous, candidate):
|
||||
|
||||
result = compare_migrations(
|
||||
previous,
|
||||
candidate,
|
||||
)
|
||||
|
||||
require(
|
||||
result["compatible_without_migrations"],
|
||||
"Migration changes require review and explicit approval",
|
||||
)
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,442 @@
|
||||
"""Strict, non-secret deployment configuration validation."""
|
||||
|
||||
import copy
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path, PurePosixPath
|
||||
|
||||
|
||||
class ConfigurationError(ValueError):
|
||||
"""Invalid deployment configuration."""
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
|
||||
if not condition:
|
||||
raise ConfigurationError(message)
|
||||
|
||||
|
||||
def object_fields(value, fields, location):
|
||||
|
||||
require(
|
||||
isinstance(value, dict),
|
||||
f"{location} must be an object",
|
||||
)
|
||||
|
||||
require(
|
||||
set(value) == set(fields),
|
||||
f"{location} contains missing or unknown fields",
|
||||
)
|
||||
|
||||
|
||||
def string_pattern(value, pattern, location):
|
||||
|
||||
require(
|
||||
isinstance(value, str)
|
||||
and re.fullmatch(pattern, value) is not None,
|
||||
f"Invalid {location}",
|
||||
)
|
||||
|
||||
|
||||
def integer(value, minimum, maximum, location):
|
||||
|
||||
require(
|
||||
type(value) is int
|
||||
and minimum <= value <= maximum,
|
||||
f"Invalid {location}",
|
||||
)
|
||||
|
||||
|
||||
def required_true(value, location):
|
||||
|
||||
require(
|
||||
value is True,
|
||||
f"{location} must be enabled",
|
||||
)
|
||||
|
||||
|
||||
def absolute_path(value, location):
|
||||
|
||||
require(
|
||||
isinstance(value, str)
|
||||
and re.fullmatch(
|
||||
r"/[A-Za-z0-9._/-]+", value
|
||||
) is not None,
|
||||
f"Invalid {location}",
|
||||
)
|
||||
|
||||
path = PurePosixPath(value)
|
||||
|
||||
require(
|
||||
path.is_absolute()
|
||||
and str(path) == value
|
||||
and ".." not in path.parts
|
||||
and value != "/",
|
||||
f"Unsafe {location}",
|
||||
)
|
||||
|
||||
|
||||
def domain(value):
|
||||
|
||||
require(
|
||||
isinstance(value, str)
|
||||
and len(value) <= 253,
|
||||
"Invalid site domain",
|
||||
)
|
||||
|
||||
parts = value.split(".")
|
||||
|
||||
require(
|
||||
len(parts) >= 2,
|
||||
"Invalid site domain",
|
||||
)
|
||||
|
||||
for part in parts:
|
||||
|
||||
string_pattern(
|
||||
part,
|
||||
r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",
|
||||
"domain label",
|
||||
)
|
||||
|
||||
|
||||
def repository_url(value):
|
||||
|
||||
require(
|
||||
isinstance(value, str),
|
||||
"Invalid repository URL",
|
||||
)
|
||||
|
||||
patterns = (
|
||||
r"(?:[A-Za-z0-9_-]+@)?"
|
||||
r"[A-Za-z0-9.-]+:"
|
||||
r"[A-Za-z0-9_./-]+\.git",
|
||||
|
||||
r"https://[A-Za-z0-9.-]+"
|
||||
r"(?::[0-9]+)?"
|
||||
r"/[A-Za-z0-9_./-]+\.git",
|
||||
|
||||
r"ssh://(?:[A-Za-z0-9_-]+@)?"
|
||||
r"[A-Za-z0-9.-]+"
|
||||
r"(?::[0-9]+)?"
|
||||
r"/[A-Za-z0-9_./-]+\.git",
|
||||
)
|
||||
|
||||
require(
|
||||
any(
|
||||
re.fullmatch(pattern, value)
|
||||
for pattern in patterns
|
||||
)
|
||||
and ".." not in value,
|
||||
"Unsafe or unsupported repository URL",
|
||||
)
|
||||
|
||||
|
||||
def validate_config(data):
|
||||
|
||||
object_fields(
|
||||
data,
|
||||
{
|
||||
"schema_version",
|
||||
"site",
|
||||
"repository",
|
||||
"database",
|
||||
"docker",
|
||||
"retention",
|
||||
"migration",
|
||||
"backup",
|
||||
"health",
|
||||
},
|
||||
"Configuration",
|
||||
)
|
||||
|
||||
require(
|
||||
type(data["schema_version"]) is int
|
||||
and data["schema_version"] == 1,
|
||||
"Unsupported configuration schema",
|
||||
)
|
||||
|
||||
identifier = r"[a-z0-9][a-z0-9-]{0,62}"
|
||||
service_name = r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}"
|
||||
database_name = r"[A-Za-z_][A-Za-z0-9_]{0,62}"
|
||||
|
||||
site = data["site"]
|
||||
|
||||
object_fields(
|
||||
site,
|
||||
{"identifier", "domain", "root", "origin_port"},
|
||||
"site",
|
||||
)
|
||||
|
||||
string_pattern(
|
||||
site["identifier"], identifier, "site identifier"
|
||||
)
|
||||
|
||||
domain(site["domain"])
|
||||
absolute_path(site["root"], "site root")
|
||||
|
||||
integer(
|
||||
site["origin_port"], 1024, 65535, "origin port"
|
||||
)
|
||||
|
||||
repository = data["repository"]
|
||||
|
||||
object_fields(
|
||||
repository,
|
||||
{"url", "branch"},
|
||||
"repository",
|
||||
)
|
||||
|
||||
repository_url(repository["url"])
|
||||
|
||||
branch = repository["branch"]
|
||||
|
||||
string_pattern(
|
||||
branch,
|
||||
r"[A-Za-z0-9][A-Za-z0-9_./-]{0,127}",
|
||||
"repository branch",
|
||||
)
|
||||
|
||||
require(
|
||||
".." not in branch
|
||||
and all(
|
||||
part
|
||||
and not part.startswith(".")
|
||||
and not part.endswith(".lock")
|
||||
and not part.endswith(".")
|
||||
for part in branch.split("/")
|
||||
),
|
||||
"Unsafe repository branch",
|
||||
)
|
||||
|
||||
database = data["database"]
|
||||
|
||||
object_fields(
|
||||
database,
|
||||
{
|
||||
"driver",
|
||||
"container",
|
||||
"host",
|
||||
"port",
|
||||
"name",
|
||||
"username",
|
||||
},
|
||||
"database",
|
||||
)
|
||||
|
||||
require(
|
||||
database["driver"] in ("mysql", "pgsql"),
|
||||
"Unsupported database driver",
|
||||
)
|
||||
|
||||
string_pattern(
|
||||
database["container"],
|
||||
service_name,
|
||||
"database container",
|
||||
)
|
||||
|
||||
string_pattern(
|
||||
database["host"],
|
||||
r"[A-Za-z0-9][A-Za-z0-9.-]{0,252}",
|
||||
"database host",
|
||||
)
|
||||
|
||||
string_pattern(
|
||||
database["name"],
|
||||
database_name,
|
||||
"database name",
|
||||
)
|
||||
|
||||
string_pattern(
|
||||
database["username"],
|
||||
database_name,
|
||||
"database username",
|
||||
)
|
||||
|
||||
integer(
|
||||
database["port"], 1, 65535, "database port"
|
||||
)
|
||||
|
||||
docker = data["docker"]
|
||||
|
||||
object_fields(
|
||||
docker,
|
||||
{
|
||||
"project",
|
||||
"application_path",
|
||||
"php_service",
|
||||
"web_service",
|
||||
"queue_service",
|
||||
"scheduler_service",
|
||||
"backend_network",
|
||||
"proxy_network",
|
||||
},
|
||||
"docker",
|
||||
)
|
||||
|
||||
absolute_path(
|
||||
docker["application_path"],
|
||||
"container application path",
|
||||
)
|
||||
|
||||
service_keys = (
|
||||
"php_service",
|
||||
"web_service",
|
||||
"queue_service",
|
||||
"scheduler_service",
|
||||
)
|
||||
|
||||
for key in (
|
||||
"project",
|
||||
*service_keys,
|
||||
"backend_network",
|
||||
"proxy_network",
|
||||
):
|
||||
|
||||
string_pattern(
|
||||
docker[key], service_name, f"docker.{key}"
|
||||
)
|
||||
|
||||
require(
|
||||
len({docker[key] for key in service_keys}) == 4,
|
||||
"Docker service names must be distinct",
|
||||
)
|
||||
|
||||
retention = data["retention"]
|
||||
|
||||
object_fields(
|
||||
retention,
|
||||
{"keep_releases", "automatic_deletion"},
|
||||
"retention",
|
||||
)
|
||||
|
||||
integer(
|
||||
retention["keep_releases"],
|
||||
1, 100,
|
||||
"retention count",
|
||||
)
|
||||
|
||||
require(
|
||||
retention["automatic_deletion"] is False,
|
||||
"Automatic destructive cleanup is prohibited",
|
||||
)
|
||||
|
||||
migration = data["migration"]
|
||||
|
||||
object_fields(
|
||||
migration,
|
||||
{
|
||||
"require_approval",
|
||||
"require_rehearsal",
|
||||
"approval_ttl_hours",
|
||||
},
|
||||
"migration",
|
||||
)
|
||||
|
||||
required_true(
|
||||
migration["require_approval"], "migration approval"
|
||||
)
|
||||
|
||||
required_true(
|
||||
migration["require_rehearsal"], "migration rehearsal"
|
||||
)
|
||||
|
||||
integer(
|
||||
migration["approval_ttl_hours"],
|
||||
1, 72,
|
||||
"migration approval TTL",
|
||||
)
|
||||
|
||||
backup = data["backup"]
|
||||
|
||||
object_fields(
|
||||
backup,
|
||||
{"required", "verify_checksum"},
|
||||
"backup",
|
||||
)
|
||||
|
||||
required_true(backup["required"], "database backup")
|
||||
|
||||
required_true(
|
||||
backup["verify_checksum"], "backup checksum"
|
||||
)
|
||||
|
||||
health = data["health"]
|
||||
|
||||
object_fields(
|
||||
health,
|
||||
{"endpoints", "timeout_seconds"},
|
||||
"health",
|
||||
)
|
||||
|
||||
endpoints = health["endpoints"]
|
||||
|
||||
require(
|
||||
isinstance(endpoints, list)
|
||||
and 1 <= len(endpoints) <= 20,
|
||||
"Invalid health endpoint list",
|
||||
)
|
||||
|
||||
for endpoint in endpoints:
|
||||
|
||||
string_pattern(
|
||||
endpoint,
|
||||
r"/[A-Za-z0-9/_-]*",
|
||||
"health endpoint",
|
||||
)
|
||||
|
||||
require(
|
||||
not endpoint.startswith("//"),
|
||||
"External health endpoints are prohibited",
|
||||
)
|
||||
|
||||
require(
|
||||
len(set(endpoints)) == len(endpoints),
|
||||
"Duplicate health endpoints",
|
||||
)
|
||||
|
||||
integer(
|
||||
health["timeout_seconds"],
|
||||
1, 120,
|
||||
"health timeout",
|
||||
)
|
||||
|
||||
return copy.deepcopy(data)
|
||||
|
||||
|
||||
def unique_json_object(pairs):
|
||||
|
||||
result = {}
|
||||
|
||||
for key, value in pairs:
|
||||
|
||||
require(
|
||||
key not in result,
|
||||
"Duplicate JSON configuration field",
|
||||
)
|
||||
|
||||
result[key] = value
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def load_config(path):
|
||||
|
||||
try:
|
||||
|
||||
with Path(path).open(
|
||||
"r", encoding="utf-8"
|
||||
) as handle:
|
||||
|
||||
data = json.load(
|
||||
handle,
|
||||
object_pairs_hook=unique_json_object,
|
||||
)
|
||||
|
||||
except (OSError, UnicodeError, ValueError) as error:
|
||||
|
||||
raise ConfigurationError(
|
||||
"Unable to read valid configuration"
|
||||
) from error
|
||||
|
||||
return validate_config(data)
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Database adapter interface and validated adapter factory."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from types import MappingProxyType
|
||||
import re
|
||||
|
||||
from core.configuration import (
|
||||
ConfigurationError,
|
||||
validate_config,
|
||||
)
|
||||
|
||||
|
||||
class DatabaseError(RuntimeError):
|
||||
"""Invalid or unsafe database operation."""
|
||||
|
||||
|
||||
class DatabaseAdapter(ABC):
|
||||
|
||||
def __init__(self, config):
|
||||
|
||||
try:
|
||||
|
||||
validated = validate_config(config)
|
||||
|
||||
except ConfigurationError as error:
|
||||
|
||||
raise DatabaseError(
|
||||
"Invalid database configuration"
|
||||
) from error
|
||||
|
||||
self.database = MappingProxyType(
|
||||
validated["database"]
|
||||
)
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def backup_extension(self):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def ping_command(self):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def version_command(self):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def identity_command(self):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def backup_command(self):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def restore_command(self, target):
|
||||
pass
|
||||
|
||||
def docker_exec(self, interactive=False):
|
||||
|
||||
command = ["docker", "exec"]
|
||||
|
||||
if interactive:
|
||||
command.append("-i")
|
||||
|
||||
command.append(
|
||||
self.database["container"]
|
||||
)
|
||||
|
||||
return command
|
||||
|
||||
def validate_restore_target(self, target):
|
||||
|
||||
if (
|
||||
not isinstance(target, str)
|
||||
or re.fullmatch(
|
||||
r"isolated_restore_[a-z0-9_]{1,45}",
|
||||
target,
|
||||
) is None
|
||||
):
|
||||
|
||||
raise DatabaseError(
|
||||
"Only isolated restoration targets are permitted"
|
||||
)
|
||||
|
||||
if target.lower() == self.database["name"].lower():
|
||||
|
||||
raise DatabaseError(
|
||||
"Restoration into the configured database is prohibited"
|
||||
)
|
||||
|
||||
return target
|
||||
|
||||
|
||||
def get_adapter(config):
|
||||
|
||||
try:
|
||||
|
||||
validated = validate_config(config)
|
||||
|
||||
except ConfigurationError as error:
|
||||
|
||||
raise DatabaseError(
|
||||
"Invalid database configuration"
|
||||
) from error
|
||||
|
||||
driver = validated["database"]["driver"]
|
||||
|
||||
if driver == "mysql":
|
||||
|
||||
from adapters.mysql.adapter import MySQLAdapter
|
||||
|
||||
return MySQLAdapter(validated)
|
||||
|
||||
if driver == "pgsql":
|
||||
|
||||
from adapters.postgresql.adapter import PostgreSQLAdapter
|
||||
|
||||
return PostgreSQLAdapter(validated)
|
||||
|
||||
raise DatabaseError("Unsupported database driver")
|
||||
@@ -0,0 +1,363 @@
|
||||
"""Coordinated deployment with conservative failure containment.
|
||||
|
||||
External service operations must be provided by trusted adapters.
|
||||
This module does not directly execute Docker or database commands.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from core.compatibility import require_compatible
|
||||
from core.backup_evidence import BackupEvidence
|
||||
from core.operation_guard import OperationGuard
|
||||
from core.locking import DeploymentLock
|
||||
|
||||
|
||||
class DeploymentError(RuntimeError):
|
||||
"""Deployment failed or requires explicit recovery."""
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
|
||||
if not condition:
|
||||
raise DeploymentError(message)
|
||||
|
||||
|
||||
class DeploymentController:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
site,
|
||||
lock_path,
|
||||
releases,
|
||||
provenance,
|
||||
journal,
|
||||
backup,
|
||||
services,
|
||||
health,
|
||||
runtime_check,
|
||||
stopped_check,
|
||||
backup_evidence,
|
||||
operation_guard,
|
||||
):
|
||||
|
||||
self.site = site
|
||||
self.lock_path = Path(lock_path)
|
||||
self.releases = releases
|
||||
self.provenance = provenance
|
||||
self.journal = journal
|
||||
self.backup = backup
|
||||
self.services = services
|
||||
self.health = health
|
||||
self.runtime_check = runtime_check
|
||||
self.stopped_check = stopped_check
|
||||
|
||||
require(
|
||||
isinstance(backup_evidence, BackupEvidence),
|
||||
"A persistent backup evidence store is required",
|
||||
)
|
||||
|
||||
self.backup_evidence = backup_evidence
|
||||
|
||||
require(
|
||||
isinstance(operation_guard, OperationGuard),
|
||||
"A shared operation guard is required",
|
||||
)
|
||||
|
||||
self.operation_guard = operation_guard
|
||||
|
||||
def deploy(self, candidate):
|
||||
|
||||
with DeploymentLock(self.lock_path):
|
||||
|
||||
return self._deploy(candidate)
|
||||
|
||||
def _deploy(self, candidate):
|
||||
|
||||
transaction = None
|
||||
quiesce_started = False
|
||||
operation = "preflight"
|
||||
|
||||
try:
|
||||
|
||||
self.operation_guard.require_clear()
|
||||
|
||||
require(
|
||||
self.journal.load() is None,
|
||||
"Existing transaction requires review",
|
||||
)
|
||||
|
||||
previous = self.releases.current()
|
||||
|
||||
require(
|
||||
previous is not None,
|
||||
"Initial deployment requires separate provisioning",
|
||||
)
|
||||
|
||||
require(
|
||||
previous != candidate,
|
||||
"Candidate is already active",
|
||||
)
|
||||
|
||||
old_path = self.releases.validate(previous)
|
||||
|
||||
new_path = self.releases.validate(candidate)
|
||||
|
||||
old_evidence = self.provenance.verify(old_path)
|
||||
|
||||
new_evidence = self.provenance.verify(new_path)
|
||||
|
||||
require_compatible(
|
||||
old_evidence,
|
||||
new_evidence,
|
||||
)
|
||||
|
||||
require(
|
||||
self.runtime_check() is True,
|
||||
"Database runtime verification failed",
|
||||
)
|
||||
|
||||
operation = "create transaction"
|
||||
|
||||
transaction = self.journal.create(
|
||||
site=self.site,
|
||||
previous=previous,
|
||||
candidate=candidate,
|
||||
revision=new_evidence["revision"],
|
||||
provenance=new_evidence["fingerprint"],
|
||||
previous_revision=old_evidence["revision"],
|
||||
previous_provenance=old_evidence["fingerprint"],
|
||||
)
|
||||
|
||||
def advance(phase):
|
||||
|
||||
nonlocal transaction
|
||||
|
||||
transaction = self.journal.transition(
|
||||
transaction["transaction_id"],
|
||||
transaction["phase"],
|
||||
phase,
|
||||
)
|
||||
|
||||
operation = "database backup"
|
||||
|
||||
backup = self.backup.create()
|
||||
manifest = self.backup.verify(backup)
|
||||
|
||||
operation = "persist backup evidence"
|
||||
|
||||
evidence = self.backup_evidence.create(
|
||||
transaction["transaction_id"],
|
||||
manifest,
|
||||
)
|
||||
|
||||
require(
|
||||
self.backup_evidence.load(
|
||||
transaction["transaction_id"]
|
||||
) == evidence,
|
||||
"Backup evidence readback failed",
|
||||
)
|
||||
|
||||
advance("BACKED_UP")
|
||||
|
||||
operation = "quiesce background workers"
|
||||
|
||||
quiesce_started = True
|
||||
|
||||
self.services.quiesce()
|
||||
|
||||
require(
|
||||
self.stopped_check() is True,
|
||||
"Worker shutdown could not be verified",
|
||||
)
|
||||
|
||||
advance("QUIESCED")
|
||||
|
||||
operation = "revalidate deployment"
|
||||
|
||||
require(
|
||||
self.releases.current() == previous,
|
||||
"Active release changed during deployment",
|
||||
)
|
||||
|
||||
require(
|
||||
self.runtime_check() is True,
|
||||
"Database runtime verification changed",
|
||||
)
|
||||
|
||||
require(
|
||||
self.provenance.verify(
|
||||
self.releases.validate(previous)
|
||||
) == old_evidence,
|
||||
"Previous release provenance changed",
|
||||
)
|
||||
|
||||
require(
|
||||
self.provenance.verify(
|
||||
self.releases.validate(candidate)
|
||||
) == new_evidence,
|
||||
"Candidate provenance changed",
|
||||
)
|
||||
|
||||
operation = "activate candidate"
|
||||
|
||||
advance("ACTIVATING")
|
||||
|
||||
self.releases.activate(candidate)
|
||||
|
||||
advance("ACTIVATED")
|
||||
|
||||
operation = "refresh application services"
|
||||
|
||||
self.services.refresh()
|
||||
|
||||
operation = "restore background workers"
|
||||
|
||||
self.services.resume()
|
||||
|
||||
operation = "verify application health"
|
||||
|
||||
report = self.health.verify(candidate)
|
||||
|
||||
require(
|
||||
isinstance(report, dict)
|
||||
and report.get("healthy") is True
|
||||
and report.get("release") == candidate,
|
||||
"Application health verification failed",
|
||||
)
|
||||
|
||||
require(
|
||||
self.releases.current() == candidate,
|
||||
"Active release changed after verification",
|
||||
)
|
||||
|
||||
operation = "finalise deployment"
|
||||
|
||||
advance("VERIFIED")
|
||||
|
||||
return transaction
|
||||
|
||||
except Exception:
|
||||
|
||||
containment_ok = True
|
||||
journal_ok = True
|
||||
|
||||
if quiesce_started:
|
||||
|
||||
try:
|
||||
|
||||
self.services.quiesce()
|
||||
|
||||
containment_ok = (
|
||||
self.stopped_check() is True
|
||||
)
|
||||
|
||||
except Exception:
|
||||
|
||||
containment_ok = False
|
||||
|
||||
if transaction is not None:
|
||||
|
||||
try:
|
||||
|
||||
actual = self.journal.load()
|
||||
|
||||
if (
|
||||
actual is None
|
||||
or actual["transaction_id"]
|
||||
!= transaction["transaction_id"]
|
||||
):
|
||||
|
||||
journal_ok = False
|
||||
|
||||
elif actual["phase"] not in (
|
||||
"VERIFIED",
|
||||
"FAILED",
|
||||
):
|
||||
|
||||
self.journal.transition(
|
||||
actual["transaction_id"],
|
||||
actual["phase"],
|
||||
"FAILED",
|
||||
)
|
||||
|
||||
elif actual["phase"] == "VERIFIED":
|
||||
|
||||
journal_ok = False
|
||||
|
||||
except Exception:
|
||||
|
||||
journal_ok = False
|
||||
|
||||
raise DeploymentError(
|
||||
f"Deployment failed during {operation}; "
|
||||
f"containment={containment_ok}; "
|
||||
f"journal={journal_ok}; "
|
||||
"explicit inspection required"
|
||||
) from None
|
||||
|
||||
def recovery_plan(self):
|
||||
|
||||
with DeploymentLock(self.lock_path):
|
||||
|
||||
transaction = self.journal.load()
|
||||
|
||||
if transaction is None:
|
||||
|
||||
return {
|
||||
"status": "CLEAR",
|
||||
"automatic_rollback_allowed": False,
|
||||
}
|
||||
|
||||
current = self.releases.current()
|
||||
|
||||
transaction_id = transaction["transaction_id"]
|
||||
|
||||
evidence_path = self.backup_evidence.path(
|
||||
transaction_id
|
||||
)
|
||||
|
||||
evidence_present = (
|
||||
evidence_path.exists()
|
||||
or evidence_path.is_symlink()
|
||||
)
|
||||
|
||||
backup_id = None
|
||||
|
||||
if evidence_present:
|
||||
|
||||
try:
|
||||
evidence = self.backup_evidence.load(
|
||||
transaction_id
|
||||
)
|
||||
|
||||
backup_id = evidence["backup"]["backup_id"]
|
||||
|
||||
except Exception:
|
||||
raise DeploymentError(
|
||||
"Invalid backup evidence; recovery blocked"
|
||||
) from None
|
||||
|
||||
backup_required = any(
|
||||
event["phase"] == "BACKED_UP"
|
||||
for event in transaction["history"]
|
||||
)
|
||||
|
||||
require(
|
||||
not backup_required or evidence_present,
|
||||
"Required backup evidence is missing",
|
||||
)
|
||||
|
||||
return {
|
||||
"backup_evidence_present": evidence_present,
|
||||
"backup_id": backup_id,
|
||||
"status": transaction["phase"],
|
||||
"transaction_id": (
|
||||
transaction["transaction_id"]
|
||||
),
|
||||
"previous": transaction["previous"],
|
||||
"candidate": transaction["candidate"],
|
||||
"current": current,
|
||||
"automatic_rollback_allowed": False,
|
||||
"explicit_review_required": True,
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Explicitly authorised, non-interactive command execution."""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
class ExecutionError(RuntimeError):
|
||||
"""Command execution failed or was prohibited."""
|
||||
|
||||
|
||||
def normalise_command(command):
|
||||
|
||||
if (
|
||||
not isinstance(command, (tuple, list))
|
||||
or not command
|
||||
):
|
||||
|
||||
raise ExecutionError(
|
||||
"Invalid command"
|
||||
)
|
||||
|
||||
if any(
|
||||
not isinstance(argument, str)
|
||||
or "\x00" in argument
|
||||
for argument in command
|
||||
):
|
||||
|
||||
raise ExecutionError(
|
||||
"Invalid command argument"
|
||||
)
|
||||
|
||||
if not command[0]:
|
||||
|
||||
raise ExecutionError(
|
||||
"Missing executable"
|
||||
)
|
||||
|
||||
return tuple(command)
|
||||
|
||||
|
||||
class CommandRunner:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
allowed_commands,
|
||||
timeout=300,
|
||||
):
|
||||
|
||||
if (
|
||||
type(timeout) is not int
|
||||
or not 1 <= timeout <= 3600
|
||||
):
|
||||
|
||||
raise ExecutionError(
|
||||
"Invalid command timeout"
|
||||
)
|
||||
|
||||
self.allowed = frozenset(
|
||||
normalise_command(command)
|
||||
for command in allowed_commands
|
||||
)
|
||||
|
||||
if not self.allowed:
|
||||
|
||||
raise ExecutionError(
|
||||
"Command allowlist is empty"
|
||||
)
|
||||
|
||||
self.timeout = timeout
|
||||
|
||||
def __call__(self, command, output):
|
||||
|
||||
command = normalise_command(command)
|
||||
|
||||
if command not in self.allowed:
|
||||
|
||||
raise ExecutionError(
|
||||
"Command is not authorised"
|
||||
)
|
||||
|
||||
if not callable(
|
||||
getattr(output, "write", None)
|
||||
):
|
||||
|
||||
raise ExecutionError(
|
||||
"Invalid output destination"
|
||||
)
|
||||
|
||||
# Stage output privately until the subprocess
|
||||
# has completed successfully. No partial output
|
||||
# is published on command failure.
|
||||
|
||||
with tempfile.TemporaryFile(
|
||||
mode="w+b"
|
||||
) as staged:
|
||||
|
||||
try:
|
||||
|
||||
process = subprocess.Popen(
|
||||
command,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=staged,
|
||||
stderr=subprocess.DEVNULL,
|
||||
shell=False,
|
||||
start_new_session=True,
|
||||
)
|
||||
|
||||
except OSError:
|
||||
|
||||
raise ExecutionError(
|
||||
"Unable to start authorised command"
|
||||
) from None
|
||||
|
||||
try:
|
||||
|
||||
status = process.wait(
|
||||
timeout=self.timeout
|
||||
)
|
||||
|
||||
except BaseException as error:
|
||||
|
||||
try:
|
||||
|
||||
os.killpg(
|
||||
process.pid,
|
||||
signal.SIGKILL,
|
||||
)
|
||||
|
||||
except ProcessLookupError:
|
||||
|
||||
pass
|
||||
|
||||
process.wait()
|
||||
|
||||
if isinstance(
|
||||
error,
|
||||
subprocess.TimeoutExpired,
|
||||
):
|
||||
|
||||
raise ExecutionError(
|
||||
"Command execution timed out"
|
||||
) from None
|
||||
|
||||
raise
|
||||
|
||||
if status != 0:
|
||||
|
||||
raise ExecutionError(
|
||||
f"Command exited with status {status}"
|
||||
)
|
||||
|
||||
staged.seek(0)
|
||||
|
||||
shutil.copyfileobj(
|
||||
staged,
|
||||
output,
|
||||
length=1024 * 1024,
|
||||
)
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
"""Read-only application health assessment.
|
||||
|
||||
All external operations are supplied through injected probes.
|
||||
"""
|
||||
|
||||
import re
|
||||
import time
|
||||
|
||||
from core.configuration import (
|
||||
ConfigurationError,
|
||||
validate_config,
|
||||
)
|
||||
|
||||
|
||||
class HealthError(RuntimeError):
|
||||
"""Application health could not be established."""
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
|
||||
if not condition:
|
||||
raise HealthError(message)
|
||||
|
||||
|
||||
class HealthVerifier:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config,
|
||||
*,
|
||||
http_probe,
|
||||
service_probe,
|
||||
database_probe,
|
||||
redis_probe,
|
||||
asset_probe,
|
||||
release_probe,
|
||||
attempts=1,
|
||||
retry_delay=2,
|
||||
sleep=time.sleep,
|
||||
):
|
||||
|
||||
try:
|
||||
|
||||
validated = validate_config(config)
|
||||
|
||||
except ConfigurationError:
|
||||
|
||||
raise HealthError(
|
||||
"Invalid health configuration"
|
||||
) from None
|
||||
|
||||
require(
|
||||
type(attempts) is int
|
||||
and 1 <= attempts <= 10,
|
||||
"Invalid health verification attempt count",
|
||||
)
|
||||
|
||||
require(
|
||||
type(retry_delay) is int
|
||||
and 0 <= retry_delay <= 30,
|
||||
"Invalid health retry delay",
|
||||
)
|
||||
|
||||
for probe in (
|
||||
http_probe,
|
||||
service_probe,
|
||||
database_probe,
|
||||
redis_probe,
|
||||
asset_probe,
|
||||
release_probe,
|
||||
sleep,
|
||||
):
|
||||
|
||||
require(
|
||||
callable(probe),
|
||||
"Invalid health probe",
|
||||
)
|
||||
|
||||
site = validated["site"]
|
||||
docker = validated["docker"]
|
||||
health = validated["health"]
|
||||
|
||||
self._origin = (
|
||||
"http://127.0.0.1:"
|
||||
+ str(site["origin_port"])
|
||||
)
|
||||
|
||||
self._domain = site["domain"]
|
||||
|
||||
self._endpoints = tuple(
|
||||
health["endpoints"]
|
||||
)
|
||||
|
||||
self._timeout = health["timeout_seconds"]
|
||||
|
||||
self._services = (
|
||||
docker["php_service"],
|
||||
docker["web_service"],
|
||||
docker["queue_service"],
|
||||
docker["scheduler_service"],
|
||||
)
|
||||
|
||||
self._http = http_probe
|
||||
self._service = service_probe
|
||||
self._database = database_probe
|
||||
self._redis = redis_probe
|
||||
self._assets = asset_probe
|
||||
self._release = release_probe
|
||||
|
||||
self._attempts = attempts
|
||||
self._retry_delay = retry_delay
|
||||
self._sleep = sleep
|
||||
|
||||
def _invoke(self, label, probe, *args, **kwargs):
|
||||
|
||||
try:
|
||||
|
||||
return probe(*args, **kwargs)
|
||||
|
||||
except Exception:
|
||||
|
||||
raise HealthError(
|
||||
f"Health probe failed: {label}"
|
||||
) from None
|
||||
|
||||
def _check_release(self, expected):
|
||||
|
||||
actual = self._invoke(
|
||||
"active release",
|
||||
self._release,
|
||||
)
|
||||
|
||||
require(
|
||||
isinstance(actual, str)
|
||||
and actual == expected,
|
||||
"Active release identity mismatch",
|
||||
)
|
||||
|
||||
def _verify_once(self, expected, attempt):
|
||||
|
||||
self._check_release(expected)
|
||||
|
||||
result = {
|
||||
"format_version": 1,
|
||||
"release": expected,
|
||||
"attempt": attempt,
|
||||
"http": {},
|
||||
"services": {},
|
||||
"database": False,
|
||||
"redis": False,
|
||||
"assets": False,
|
||||
"healthy": False,
|
||||
}
|
||||
|
||||
for endpoint in self._endpoints:
|
||||
|
||||
status = self._invoke(
|
||||
f"HTTP {endpoint}",
|
||||
self._http,
|
||||
self._origin + endpoint,
|
||||
host=self._domain,
|
||||
timeout=self._timeout,
|
||||
)
|
||||
|
||||
require(
|
||||
type(status) is int
|
||||
and status == 200,
|
||||
f"HTTP health check failed: {endpoint}",
|
||||
)
|
||||
|
||||
result["http"][endpoint] = status
|
||||
|
||||
for service in self._services:
|
||||
|
||||
ready = self._invoke(
|
||||
f"service {service}",
|
||||
self._service,
|
||||
service,
|
||||
timeout=self._timeout,
|
||||
)
|
||||
|
||||
require(
|
||||
ready is True,
|
||||
f"Service not ready: {service}",
|
||||
)
|
||||
|
||||
result["services"][service] = True
|
||||
|
||||
for name, probe in (
|
||||
("database", self._database),
|
||||
("redis", self._redis),
|
||||
("assets", self._assets),
|
||||
):
|
||||
|
||||
ready = self._invoke(
|
||||
name,
|
||||
probe,
|
||||
timeout=self._timeout,
|
||||
)
|
||||
|
||||
require(
|
||||
ready is True,
|
||||
f"Health check failed: {name}",
|
||||
)
|
||||
|
||||
result[name] = True
|
||||
|
||||
self._check_release(expected)
|
||||
|
||||
result["healthy"] = True
|
||||
|
||||
return result
|
||||
|
||||
def verify(self, expected_release):
|
||||
|
||||
require(
|
||||
isinstance(expected_release, str)
|
||||
and re.fullmatch(
|
||||
r"[1-9][0-9]{0,19}",
|
||||
expected_release,
|
||||
) is not None,
|
||||
"Invalid expected release identifier",
|
||||
)
|
||||
|
||||
for attempt in range(
|
||||
1,
|
||||
self._attempts + 1,
|
||||
):
|
||||
|
||||
try:
|
||||
|
||||
return self._verify_once(
|
||||
expected_release,
|
||||
attempt,
|
||||
)
|
||||
|
||||
except HealthError:
|
||||
|
||||
if attempt == self._attempts:
|
||||
raise
|
||||
|
||||
self._sleep(self._retry_delay)
|
||||
|
||||
raise HealthError(
|
||||
"Application health verification failed"
|
||||
)
|
||||
@@ -0,0 +1,323 @@
|
||||
"""Read-only framework inspection and provisioning planning."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from core.configuration import load_config, validate_config
|
||||
from core.compatibility import canonical_hash
|
||||
from core.releases import ReleaseManager
|
||||
from core.retention import plan_retention
|
||||
from core.site_policy import validate_site, validate_registry
|
||||
from core.preflight import site_preflight
|
||||
|
||||
|
||||
class InspectionError(RuntimeError):
|
||||
"""Inspection failed or supplied data is unsafe."""
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
raise InspectionError(message)
|
||||
|
||||
|
||||
def unique_keys(items):
|
||||
result = {}
|
||||
|
||||
for key, value in items:
|
||||
require(
|
||||
key not in result,
|
||||
"Duplicate JSON field",
|
||||
)
|
||||
result[key] = value
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def read_json(path):
|
||||
with Path(path).open("rb") as handle:
|
||||
raw = handle.read(1024 * 1024 + 1)
|
||||
|
||||
require(
|
||||
len(raw) <= 1024 * 1024,
|
||||
"JSON policy exceeds size limit",
|
||||
)
|
||||
|
||||
return json.loads(raw, object_pairs_hook=unique_keys)
|
||||
|
||||
|
||||
def capabilities():
|
||||
return {
|
||||
"format_version": 1,
|
||||
"production_ready": False,
|
||||
"deployment_execution_enabled": False,
|
||||
"migration_execution_enabled": False,
|
||||
"provisioning_execution_enabled": False,
|
||||
"database_restore_enabled": False,
|
||||
"permanent_deletion_enabled": False,
|
||||
"commands": [
|
||||
"validate",
|
||||
"capabilities",
|
||||
"inventory",
|
||||
"retention-plan",
|
||||
"provision-plan",
|
||||
"site-policy",
|
||||
"registry-validate",
|
||||
"preflight",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def inventory_report(app):
|
||||
app = Path(app).absolute()
|
||||
|
||||
require(
|
||||
app.is_dir()
|
||||
and not app.is_symlink()
|
||||
and app.resolve() == app,
|
||||
"Invalid application directory",
|
||||
)
|
||||
|
||||
releases = ReleaseManager(app)
|
||||
|
||||
inventory = releases.inventory()
|
||||
current = releases.current()
|
||||
|
||||
require(
|
||||
current in inventory,
|
||||
"Active release missing from inventory",
|
||||
)
|
||||
|
||||
failed = [
|
||||
release
|
||||
for release in inventory
|
||||
if os.path.lexists(
|
||||
releases.release_path(release) / "BAD_RELEASE"
|
||||
)
|
||||
]
|
||||
|
||||
require(
|
||||
current not in failed,
|
||||
"Active release is marked failed",
|
||||
)
|
||||
|
||||
require(
|
||||
releases.current() == current
|
||||
and releases.inventory() == inventory,
|
||||
"Release inventory changed during inspection",
|
||||
)
|
||||
|
||||
report = {
|
||||
"format_version": 1,
|
||||
"status": "INSPECTED",
|
||||
"application_path": str(app),
|
||||
"current": current,
|
||||
"inventory": inventory,
|
||||
"failed": failed,
|
||||
"transaction_protections_verified": False,
|
||||
"runtime_verified": False,
|
||||
"execution_permitted": False,
|
||||
}
|
||||
|
||||
report["fingerprint"] = canonical_hash(report)
|
||||
|
||||
return report
|
||||
|
||||
|
||||
def provisioning_plan(config):
|
||||
config = validate_config(config)
|
||||
policy = validate_site(config)
|
||||
|
||||
site = config["site"]
|
||||
root = Path(site["root"])
|
||||
database = config["database"]
|
||||
docker = config["docker"]
|
||||
|
||||
result = {
|
||||
"format_version": 1,
|
||||
"status": "PLAN_ONLY",
|
||||
"site": site["identifier"],
|
||||
"domain": site["domain"],
|
||||
"root": str(root),
|
||||
"origin_port": site["origin_port"],
|
||||
"repository": {
|
||||
"url": config["repository"]["url"],
|
||||
"branch": config["repository"]["branch"],
|
||||
},
|
||||
"directories": [
|
||||
str(root),
|
||||
str(root / "app"),
|
||||
str(root / "app/releases"),
|
||||
str(root / "app/shared"),
|
||||
str(root / "deployment"),
|
||||
str(root / "backups"),
|
||||
str(root / "deployment/state"),
|
||||
str(root / "deployment/approvals"),
|
||||
str(root / "deployment/archives"),
|
||||
],
|
||||
"database": {
|
||||
"driver": database["driver"],
|
||||
"container": database["container"],
|
||||
"name": database["name"],
|
||||
"username": database["username"],
|
||||
},
|
||||
"docker": {
|
||||
"project": docker["project"],
|
||||
"services": [
|
||||
docker["php_service"],
|
||||
docker["web_service"],
|
||||
docker["queue_service"],
|
||||
docker["scheduler_service"],
|
||||
],
|
||||
"networks": [
|
||||
docker["backend_network"],
|
||||
docker["proxy_network"],
|
||||
],
|
||||
},
|
||||
"retention": config["retention"],
|
||||
"configuration_fingerprint": canonical_hash(config),
|
||||
"static_policy_verified": True,
|
||||
"site_policy_fingerprint": policy["fingerprint"],
|
||||
"resource_conflicts_checked": False,
|
||||
"filesystem_permissions_verified": False,
|
||||
"secrets_required": True,
|
||||
"database_creation_permitted": False,
|
||||
"execution_permitted": False,
|
||||
}
|
||||
|
||||
result["fingerprint"] = canonical_hash(result)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def parser():
|
||||
result = argparse.ArgumentParser(
|
||||
prog="absdev-deploy",
|
||||
description="ABSDEV deployment framework (inspection only)",
|
||||
)
|
||||
|
||||
commands = result.add_subparsers(
|
||||
dest="command",
|
||||
required=True,
|
||||
)
|
||||
|
||||
validate = commands.add_parser(
|
||||
"validate",
|
||||
help="Validate site configuration",
|
||||
)
|
||||
validate.add_argument("--config", required=True)
|
||||
|
||||
commands.add_parser(
|
||||
"capabilities",
|
||||
help="Show enabled framework capabilities",
|
||||
)
|
||||
|
||||
inventory = commands.add_parser(
|
||||
"inventory",
|
||||
help="Inspect application release inventory",
|
||||
)
|
||||
inventory.add_argument("--app", required=True)
|
||||
|
||||
retention = commands.add_parser(
|
||||
"retention-plan",
|
||||
help="Evaluate a supplied retention policy",
|
||||
)
|
||||
retention.add_argument("--policy", required=True)
|
||||
|
||||
provision = commands.add_parser(
|
||||
"provision-plan",
|
||||
help="Generate a read-only provisioning plan",
|
||||
)
|
||||
provision.add_argument("--config", required=True)
|
||||
|
||||
policy = commands.add_parser(
|
||||
"site-policy",
|
||||
help="Validate static site isolation policy",
|
||||
)
|
||||
policy.add_argument("--config", required=True)
|
||||
|
||||
registry = commands.add_parser(
|
||||
"registry-validate",
|
||||
help="Validate supplied site registry",
|
||||
)
|
||||
registry.add_argument("--registry", required=True)
|
||||
|
||||
preflight = commands.add_parser(
|
||||
"preflight",
|
||||
help="Check prospective site against supplied registry",
|
||||
)
|
||||
preflight.add_argument("--config", required=True)
|
||||
preflight.add_argument("--registry", required=True)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
args = parser().parse_args(argv)
|
||||
|
||||
try:
|
||||
if args.command == "capabilities":
|
||||
report = capabilities()
|
||||
|
||||
elif args.command == "inventory":
|
||||
report = inventory_report(args.app)
|
||||
|
||||
elif args.command == "retention-plan":
|
||||
report = plan_retention(
|
||||
read_json(args.policy)
|
||||
)
|
||||
|
||||
elif args.command == "provision-plan":
|
||||
report = provisioning_plan(
|
||||
load_config(args.config)
|
||||
)
|
||||
|
||||
elif args.command == "site-policy":
|
||||
report = validate_site(
|
||||
load_config(args.config)
|
||||
)
|
||||
|
||||
elif args.command == "registry-validate":
|
||||
report = validate_registry(
|
||||
read_json(args.registry)
|
||||
)
|
||||
|
||||
elif args.command == "preflight":
|
||||
report = site_preflight(
|
||||
load_config(args.config),
|
||||
read_json(args.registry),
|
||||
)
|
||||
|
||||
elif args.command == "validate":
|
||||
load_config(args.config)
|
||||
|
||||
report = {
|
||||
"status": "VALID",
|
||||
"execution_permitted": False,
|
||||
}
|
||||
|
||||
else:
|
||||
raise InspectionError("Unsupported command")
|
||||
|
||||
print(json.dumps(
|
||||
report,
|
||||
indent=2,
|
||||
sort_keys=True,
|
||||
allow_nan=False,
|
||||
))
|
||||
|
||||
return 0
|
||||
|
||||
except Exception as error:
|
||||
# Avoid exposing configuration contents,
|
||||
# credentials or external command output.
|
||||
|
||||
print(
|
||||
f"Inspection failed: {type(error).__name__}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
return 1
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
"""Exclusive filesystem-based deployment locking."""
|
||||
|
||||
import fcntl
|
||||
import os
|
||||
import stat
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class LockError(RuntimeError):
|
||||
"""Deployment lock unavailable or unsafe."""
|
||||
|
||||
|
||||
class DeploymentLock:
|
||||
|
||||
def __init__(self, path):
|
||||
|
||||
self.path = Path(path)
|
||||
self._fd = None
|
||||
|
||||
if not self.path.is_absolute():
|
||||
|
||||
raise LockError(
|
||||
"Deployment lock path must be absolute"
|
||||
)
|
||||
|
||||
if ".." in self.path.parts:
|
||||
|
||||
raise LockError(
|
||||
"Unsafe deployment lock path"
|
||||
)
|
||||
|
||||
@property
|
||||
def acquired(self):
|
||||
|
||||
return self._fd is not None
|
||||
|
||||
def validate_parent(self):
|
||||
|
||||
parent = self.path.parent
|
||||
|
||||
if (
|
||||
not parent.is_dir()
|
||||
or parent.is_symlink()
|
||||
or parent.resolve() != parent
|
||||
):
|
||||
|
||||
raise LockError(
|
||||
"Invalid deployment lock directory"
|
||||
)
|
||||
|
||||
def acquire(self):
|
||||
|
||||
if self.acquired:
|
||||
|
||||
raise LockError(
|
||||
"Deployment lock already acquired"
|
||||
)
|
||||
|
||||
fd = None
|
||||
parent_fd = None
|
||||
|
||||
try:
|
||||
|
||||
self.validate_parent()
|
||||
|
||||
parent_fd = os.open(
|
||||
self.path.parent,
|
||||
os.O_RDONLY
|
||||
| os.O_DIRECTORY
|
||||
| os.O_NOFOLLOW
|
||||
| os.O_CLOEXEC,
|
||||
)
|
||||
|
||||
parent = os.fstat(parent_fd)
|
||||
|
||||
if (
|
||||
parent.st_uid != os.getuid()
|
||||
or stat.S_IMODE(parent.st_mode) & 0o022
|
||||
):
|
||||
|
||||
raise LockError(
|
||||
"Unsafe deployment lock directory permissions"
|
||||
)
|
||||
|
||||
fd = os.open(
|
||||
self.path.name,
|
||||
os.O_RDWR
|
||||
| os.O_CREAT
|
||||
| os.O_NOFOLLOW
|
||||
| os.O_NONBLOCK
|
||||
| os.O_CLOEXEC,
|
||||
0o600,
|
||||
dir_fd=parent_fd,
|
||||
)
|
||||
|
||||
details = os.fstat(fd)
|
||||
|
||||
if (
|
||||
not stat.S_ISREG(details.st_mode)
|
||||
or details.st_uid != os.getuid()
|
||||
or details.st_nlink != 1
|
||||
or stat.S_IMODE(details.st_mode) != 0o600
|
||||
):
|
||||
|
||||
raise LockError(
|
||||
"Unsafe deployment lock file"
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
fcntl.flock(
|
||||
fd,
|
||||
fcntl.LOCK_EX | fcntl.LOCK_NB,
|
||||
)
|
||||
|
||||
except BlockingIOError:
|
||||
|
||||
raise LockError(
|
||||
"Another deployment operation is active"
|
||||
) from None
|
||||
|
||||
# Check that the directory entry still refers
|
||||
# to the locked inode.
|
||||
|
||||
entry = os.stat(
|
||||
self.path.name,
|
||||
dir_fd=parent_fd,
|
||||
follow_symlinks=False,
|
||||
)
|
||||
|
||||
locked = os.fstat(fd)
|
||||
|
||||
if (
|
||||
entry.st_dev != locked.st_dev
|
||||
or entry.st_ino != locked.st_ino
|
||||
or locked.st_nlink != 1
|
||||
or not stat.S_ISREG(entry.st_mode)
|
||||
):
|
||||
|
||||
raise LockError(
|
||||
"Deployment lock identity changed"
|
||||
)
|
||||
|
||||
self._fd = fd
|
||||
fd = None
|
||||
|
||||
return self
|
||||
|
||||
except LockError:
|
||||
|
||||
raise
|
||||
|
||||
except OSError:
|
||||
|
||||
raise LockError(
|
||||
"Unable to acquire deployment lock"
|
||||
) from None
|
||||
|
||||
finally:
|
||||
|
||||
if fd is not None:
|
||||
|
||||
os.close(fd)
|
||||
|
||||
if parent_fd is not None:
|
||||
|
||||
os.close(parent_fd)
|
||||
|
||||
def release(self):
|
||||
|
||||
if self._fd is None:
|
||||
return
|
||||
|
||||
fd = self._fd
|
||||
|
||||
self._fd = None
|
||||
|
||||
try:
|
||||
|
||||
fcntl.flock(
|
||||
fd,
|
||||
fcntl.LOCK_UN,
|
||||
)
|
||||
|
||||
finally:
|
||||
|
||||
os.close(fd)
|
||||
|
||||
def __enter__(self):
|
||||
|
||||
return self.acquire()
|
||||
|
||||
def __exit__(
|
||||
self,
|
||||
exc_type,
|
||||
exc_value,
|
||||
traceback,
|
||||
):
|
||||
|
||||
self.release()
|
||||
|
||||
return False
|
||||
@@ -0,0 +1,350 @@
|
||||
"""Migration coordination using injected trusted operations.
|
||||
|
||||
No direct Docker, SQL, PHP or shell execution.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import os
|
||||
import re
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from core.approval import verify_approval, timestamp
|
||||
from core.rehearsal import approval_context
|
||||
from core.compatibility import canonical_hash
|
||||
from core.locking import DeploymentLock
|
||||
from core.operation_guard import OperationGuard
|
||||
|
||||
|
||||
class MigrationError(RuntimeError):
|
||||
"""Migration failed or requires explicit recovery."""
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
raise MigrationError(message)
|
||||
|
||||
|
||||
def validate_history(history):
|
||||
require(
|
||||
isinstance(history, list)
|
||||
and len(history) <= 100000,
|
||||
"Invalid migration history",
|
||||
)
|
||||
|
||||
for name in history:
|
||||
require(
|
||||
isinstance(name, str)
|
||||
and re.fullmatch(
|
||||
r"[A-Za-z0-9_][A-Za-z0-9_-]{0,254}",
|
||||
name,
|
||||
) is not None,
|
||||
"Invalid migration history entry",
|
||||
)
|
||||
|
||||
require(
|
||||
len(history) == len(set(history)),
|
||||
"Duplicate migration history entries",
|
||||
)
|
||||
|
||||
return list(history)
|
||||
|
||||
|
||||
class MigrationCoordinator:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
store,
|
||||
lock_path,
|
||||
context_probe,
|
||||
contain,
|
||||
containment_probe,
|
||||
backup_probe,
|
||||
history_probe,
|
||||
migration_runner,
|
||||
application_probe,
|
||||
clock,
|
||||
):
|
||||
for callback in (
|
||||
context_probe,
|
||||
contain,
|
||||
containment_probe,
|
||||
backup_probe,
|
||||
history_probe,
|
||||
migration_runner,
|
||||
application_probe,
|
||||
clock,
|
||||
):
|
||||
require(
|
||||
callable(callback),
|
||||
"Missing migration operation adapter",
|
||||
)
|
||||
|
||||
self.store = store
|
||||
self.operation_guard = OperationGuard(store)
|
||||
self.lock_path = Path(lock_path)
|
||||
self.context_probe = context_probe
|
||||
self.contain = contain
|
||||
self.containment_probe = containment_probe
|
||||
self.backup_probe = backup_probe
|
||||
self.history_probe = history_probe
|
||||
self.migration_runner = migration_runner
|
||||
self.application_probe = application_probe
|
||||
self.clock = clock
|
||||
|
||||
def intent_path(self, identifier):
|
||||
return self.store.path(
|
||||
identifier, ".migration-intent.json"
|
||||
)
|
||||
|
||||
def result_path(self, identifier):
|
||||
return self.store.path(
|
||||
identifier, ".migration-result.json"
|
||||
)
|
||||
|
||||
def publish(self, path, data):
|
||||
record = dict(data)
|
||||
record["checksum"] = canonical_hash(record)
|
||||
|
||||
return self.store.publish(path, record)
|
||||
|
||||
def execute(self, identifier, rehearsal, *, confirmation):
|
||||
with DeploymentLock(self.lock_path):
|
||||
return self._execute(
|
||||
identifier, rehearsal, confirmation
|
||||
)
|
||||
|
||||
def _execute(self, identifier, rehearsal, confirmation):
|
||||
operation = "preflight"
|
||||
intent = None
|
||||
containment_started = False
|
||||
migration_started = False
|
||||
|
||||
try:
|
||||
self.operation_guard.require_clear()
|
||||
|
||||
intent_path = self.intent_path(identifier)
|
||||
result_path = self.result_path(identifier)
|
||||
|
||||
for path in (
|
||||
intent_path,
|
||||
result_path,
|
||||
self.store.consumed_path(identifier),
|
||||
):
|
||||
require(
|
||||
not os.path.lexists(path),
|
||||
"Existing execution evidence requires review",
|
||||
)
|
||||
|
||||
rehearsal = copy.deepcopy(rehearsal)
|
||||
base = copy.deepcopy(self.context_probe())
|
||||
current_time = timestamp(self.clock())
|
||||
|
||||
context = approval_context(
|
||||
rehearsal, base, now=current_time
|
||||
)
|
||||
|
||||
approval = self.store.load(identifier)
|
||||
|
||||
verify_approval(
|
||||
approval,
|
||||
context,
|
||||
confirmation=confirmation,
|
||||
now=current_time,
|
||||
)
|
||||
|
||||
require(
|
||||
self.backup_probe() is True,
|
||||
"Backup verification failed",
|
||||
)
|
||||
|
||||
before = validate_history(self.history_probe())
|
||||
pending = tuple(context["pending_migrations"])
|
||||
|
||||
require(
|
||||
not set(before).intersection(pending),
|
||||
"Pending migration already applied",
|
||||
)
|
||||
|
||||
operation = "persist migration intent"
|
||||
|
||||
intent = self.publish(
|
||||
intent_path,
|
||||
{
|
||||
"format_version": 1,
|
||||
"status": "MIGRATION_INTENT",
|
||||
"approval_id": identifier,
|
||||
"approval_checksum": approval["checksum"],
|
||||
"context_fingerprint": canonical_hash(context),
|
||||
"site": context["site"],
|
||||
"release": context["release"],
|
||||
"revision": context["revision"],
|
||||
"database_identity": context["database_identity"],
|
||||
"backup_sha256": context["backup_sha256"],
|
||||
"rehearsal_fingerprint":
|
||||
context["rehearsal_fingerprint"],
|
||||
"history_before": before,
|
||||
"pending_migrations": list(pending),
|
||||
"created_at": current_time.isoformat(),
|
||||
},
|
||||
)
|
||||
|
||||
operation = "establish containment"
|
||||
containment_started = True
|
||||
|
||||
require(
|
||||
self.contain() is True,
|
||||
"Write containment failed",
|
||||
)
|
||||
|
||||
require(
|
||||
self.containment_probe() is True,
|
||||
"Write containment not verified",
|
||||
)
|
||||
|
||||
operation = "revalidate migration context"
|
||||
|
||||
require(
|
||||
self.context_probe() == base,
|
||||
"Migration context changed",
|
||||
)
|
||||
|
||||
require(
|
||||
self.backup_probe() is True,
|
||||
"Backup verification changed",
|
||||
)
|
||||
|
||||
require(
|
||||
validate_history(self.history_probe()) == before,
|
||||
"Migration history changed",
|
||||
)
|
||||
|
||||
require(
|
||||
self.store.load(identifier) == approval,
|
||||
"Stored approval changed",
|
||||
)
|
||||
|
||||
operation = "consume single-use approval"
|
||||
|
||||
consumed = self.store.consume(
|
||||
identifier,
|
||||
base,
|
||||
rehearsal,
|
||||
confirmation=confirmation,
|
||||
now=self.clock(),
|
||||
)
|
||||
|
||||
require(
|
||||
consumed["approval_checksum"] == approval["checksum"],
|
||||
"Consumed approval mismatch",
|
||||
)
|
||||
|
||||
operation = "execute approved migrations"
|
||||
|
||||
require(
|
||||
self.containment_probe() is True,
|
||||
"Write containment lost",
|
||||
)
|
||||
|
||||
migration_started = True
|
||||
result = self.migration_runner(pending)
|
||||
|
||||
require(
|
||||
type(result) is int and result == 0,
|
||||
"Migration command failed",
|
||||
)
|
||||
|
||||
operation = "verify migration history"
|
||||
|
||||
after = validate_history(self.history_probe())
|
||||
|
||||
require(
|
||||
after == before + list(pending),
|
||||
"Migration history differs from approval",
|
||||
)
|
||||
|
||||
require(
|
||||
self.containment_probe() is True,
|
||||
"Containment lost after migration",
|
||||
)
|
||||
|
||||
operation = "verify migrated application"
|
||||
|
||||
require(
|
||||
self.application_probe() is True,
|
||||
"Application verification failed",
|
||||
)
|
||||
|
||||
require(
|
||||
self.containment_probe() is True,
|
||||
"Containment lost during verification",
|
||||
)
|
||||
|
||||
operation = "persist migration result"
|
||||
|
||||
return self.publish(
|
||||
result_path,
|
||||
{
|
||||
"format_version": 1,
|
||||
"status": "MIGRATED",
|
||||
"approval_id": identifier,
|
||||
"intent_checksum": intent["checksum"],
|
||||
"consumption_checksum": consumed["checksum"],
|
||||
"site": context["site"],
|
||||
"release": context["release"],
|
||||
"revision": context["revision"],
|
||||
"database_identity": context["database_identity"],
|
||||
"history_after": after,
|
||||
"applied_migrations": list(pending),
|
||||
"automatic_database_rollback": False,
|
||||
"application_activated": False,
|
||||
"containment_required": True,
|
||||
"completed_at": timestamp(self.clock()).isoformat(),
|
||||
},
|
||||
)
|
||||
|
||||
except Exception:
|
||||
containment_ok = None
|
||||
evidence_ok = None
|
||||
|
||||
if containment_started:
|
||||
try:
|
||||
containment_ok = (
|
||||
self.contain() is True
|
||||
and self.containment_probe() is True
|
||||
)
|
||||
except Exception:
|
||||
containment_ok = False
|
||||
|
||||
if intent is not None:
|
||||
try:
|
||||
if not os.path.lexists(result_path):
|
||||
self.publish(
|
||||
result_path,
|
||||
{
|
||||
"format_version": 1,
|
||||
"status": "FAILED",
|
||||
"approval_id": identifier,
|
||||
"intent_checksum": intent["checksum"],
|
||||
"operation": operation,
|
||||
"migration_may_have_executed":
|
||||
migration_started,
|
||||
"manual_recovery_required": True,
|
||||
"automatic_database_rollback": False,
|
||||
"containment_verified": containment_ok,
|
||||
},
|
||||
)
|
||||
evidence_ok = True
|
||||
else:
|
||||
evidence_ok = False
|
||||
|
||||
except Exception:
|
||||
evidence_ok = False
|
||||
|
||||
raise MigrationError(
|
||||
f"Migration failed during {operation}; "
|
||||
f"containment={containment_ok}; "
|
||||
f"failure_evidence={evidence_ok}; "
|
||||
"explicit inspection required"
|
||||
) from None
|
||||
@@ -0,0 +1,474 @@
|
||||
"""Logical archival of completed migration transactions.
|
||||
|
||||
Original approvals, consumption records and execution
|
||||
evidence are retained permanently.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from core.approval import validate_context
|
||||
from core.compatibility import canonical_hash
|
||||
from core.locking import DeploymentLock
|
||||
|
||||
|
||||
class MigrationArchiveError(RuntimeError):
|
||||
"""Migration archival evidence is unsafe or incomplete."""
|
||||
|
||||
|
||||
SUFFIXES = (
|
||||
".approval.json",
|
||||
".migration-intent.json",
|
||||
".consumed.json",
|
||||
".migration-result.json",
|
||||
".activation-intent.json",
|
||||
".activation-result.json",
|
||||
)
|
||||
|
||||
ARCHIVE_SUFFIX = ".migration-archive.json"
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
|
||||
if not condition:
|
||||
raise MigrationArchiveError(message)
|
||||
|
||||
|
||||
def digest(record):
|
||||
|
||||
return canonical_hash({
|
||||
key: value
|
||||
for key, value in record.items()
|
||||
if key != "checksum"
|
||||
})
|
||||
|
||||
|
||||
def read_record(store, path):
|
||||
|
||||
record = store.read(path)
|
||||
|
||||
require(
|
||||
isinstance(record, dict)
|
||||
and type(record.get("format_version")) is int
|
||||
and record["format_version"] == 1
|
||||
and record.get("checksum") == digest(record),
|
||||
"Invalid migration archival evidence",
|
||||
)
|
||||
|
||||
return record
|
||||
|
||||
|
||||
def read_chain(store, identifier):
|
||||
|
||||
approval = store.load(identifier)
|
||||
|
||||
context = approval["context"]
|
||||
|
||||
validate_context(context)
|
||||
|
||||
records = {
|
||||
suffix: read_record(
|
||||
store,
|
||||
store.path(identifier, suffix),
|
||||
)
|
||||
for suffix in SUFFIXES
|
||||
if suffix != ".approval.json"
|
||||
}
|
||||
|
||||
records[".approval.json"] = approval
|
||||
|
||||
intent = records[".migration-intent.json"]
|
||||
consumed = records[".consumed.json"]
|
||||
migration = records[".migration-result.json"]
|
||||
activation = records[".activation-intent.json"]
|
||||
result = records[".activation-result.json"]
|
||||
|
||||
require(
|
||||
intent["status"] == "MIGRATION_INTENT"
|
||||
and consumed["status"] == "CONSUMED"
|
||||
and migration["status"] == "MIGRATED"
|
||||
and activation["status"] == "ACTIVATION_INTENT"
|
||||
and result["status"] == "VERIFIED",
|
||||
"Migration is not fully completed",
|
||||
)
|
||||
|
||||
for suffix, record in records.items():
|
||||
|
||||
require(
|
||||
record["approval_id"] == identifier,
|
||||
"Approval identity mismatch",
|
||||
)
|
||||
|
||||
if suffix != ".approval.json":
|
||||
|
||||
require(
|
||||
record["site"] == context["site"],
|
||||
"Migration site mismatch",
|
||||
)
|
||||
|
||||
for record in (intent, consumed, migration):
|
||||
|
||||
for field in (
|
||||
"release",
|
||||
"revision",
|
||||
"database_identity",
|
||||
):
|
||||
|
||||
require(
|
||||
record[field] == context[field],
|
||||
"Migration context mismatch",
|
||||
)
|
||||
|
||||
for record in (intent, consumed):
|
||||
|
||||
require(
|
||||
record["approval_checksum"]
|
||||
== approval["checksum"]
|
||||
and record["backup_sha256"]
|
||||
== context["backup_sha256"]
|
||||
and record["rehearsal_fingerprint"]
|
||||
== context["rehearsal_fingerprint"],
|
||||
"Approval evidence mismatch",
|
||||
)
|
||||
|
||||
require(
|
||||
intent["context_fingerprint"]
|
||||
== canonical_hash(context)
|
||||
and migration["intent_checksum"]
|
||||
== intent["checksum"]
|
||||
and migration["consumption_checksum"]
|
||||
== consumed["checksum"]
|
||||
and activation["migration_checksum"]
|
||||
== migration["checksum"]
|
||||
and result["intent_checksum"]
|
||||
== activation["checksum"]
|
||||
and result["plan_fingerprint"]
|
||||
== activation["plan_fingerprint"],
|
||||
"Migration evidence chain mismatch",
|
||||
)
|
||||
|
||||
before = intent["history_before"]
|
||||
pending = context["pending_migrations"]
|
||||
|
||||
require(
|
||||
isinstance(before, list)
|
||||
and all(
|
||||
isinstance(name, str)
|
||||
for name in before
|
||||
)
|
||||
and len(before) == len(set(before))
|
||||
and not set(before).intersection(pending)
|
||||
and intent["pending_migrations"] == pending
|
||||
and migration["applied_migrations"] == pending
|
||||
and migration["history_after"] == before + pending,
|
||||
"Migration history evidence mismatch",
|
||||
)
|
||||
|
||||
require(
|
||||
consumed["migration_executed"] is False
|
||||
and migration["automatic_database_rollback"] is False
|
||||
and migration["application_activated"] is False
|
||||
and migration["containment_required"] is True
|
||||
and activation["target"] == context["release"]
|
||||
and result["active_release"] == context["release"]
|
||||
and result["health_verified"] is True
|
||||
and result["database_restored"] is False
|
||||
and result["migration_reexecuted"] is False,
|
||||
"Invalid migration completion evidence",
|
||||
)
|
||||
|
||||
return records
|
||||
|
||||
|
||||
def archive_path(store, identifier):
|
||||
|
||||
return store.path(
|
||||
identifier,
|
||||
ARCHIVE_SUFFIX,
|
||||
)
|
||||
|
||||
|
||||
def verify_archived_group(store, identifier):
|
||||
|
||||
"""Validate a historical archive without live probes."""
|
||||
|
||||
try:
|
||||
|
||||
record = read_record(
|
||||
store,
|
||||
archive_path(store, identifier),
|
||||
)
|
||||
|
||||
records = read_chain(store, identifier)
|
||||
|
||||
context = records[".approval.json"]["context"]
|
||||
|
||||
require(
|
||||
set(record) == {
|
||||
"format_version",
|
||||
"status",
|
||||
"approval_id",
|
||||
"site",
|
||||
"release",
|
||||
"record_checksums",
|
||||
"plan_fingerprint",
|
||||
"database_restored",
|
||||
"archived_at",
|
||||
"checksum",
|
||||
}
|
||||
and record["status"] == "ARCHIVED"
|
||||
and record["approval_id"] == identifier
|
||||
and record["site"] == context["site"]
|
||||
and record["release"] == context["release"]
|
||||
and record["database_restored"] is False,
|
||||
"Invalid migration archive marker",
|
||||
)
|
||||
|
||||
require(
|
||||
record["record_checksums"] == {
|
||||
suffix: item["checksum"]
|
||||
for suffix, item in records.items()
|
||||
},
|
||||
"Archived migration evidence changed",
|
||||
)
|
||||
|
||||
return {
|
||||
identifier + suffix
|
||||
for suffix in (*SUFFIXES, ARCHIVE_SUFFIX)
|
||||
}
|
||||
|
||||
except MigrationArchiveError:
|
||||
raise
|
||||
|
||||
except Exception:
|
||||
|
||||
raise MigrationArchiveError(
|
||||
"Historical migration archive validation failed"
|
||||
) from None
|
||||
|
||||
|
||||
class MigrationArchive:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
site,
|
||||
store,
|
||||
lock_path,
|
||||
identity_probe,
|
||||
history_probe,
|
||||
provenance_probe,
|
||||
backup_probe,
|
||||
current_probe,
|
||||
health_probe,
|
||||
writes_enabled_probe,
|
||||
):
|
||||
|
||||
self.site = site
|
||||
self.store = store
|
||||
self.lock_path = Path(lock_path)
|
||||
|
||||
callbacks = {
|
||||
"identity_probe": identity_probe,
|
||||
"history_probe": history_probe,
|
||||
"provenance_probe": provenance_probe,
|
||||
"backup_probe": backup_probe,
|
||||
"current_probe": current_probe,
|
||||
"health_probe": health_probe,
|
||||
"writes_enabled_probe": writes_enabled_probe,
|
||||
}
|
||||
|
||||
for name, callback in callbacks.items():
|
||||
|
||||
require(
|
||||
callable(callback),
|
||||
"Missing archival verification adapter",
|
||||
)
|
||||
|
||||
setattr(self, name, callback)
|
||||
|
||||
def path(self, identifier):
|
||||
|
||||
return archive_path(
|
||||
self.store,
|
||||
identifier,
|
||||
)
|
||||
|
||||
def _plan(self, identifier):
|
||||
|
||||
require(
|
||||
not os.path.lexists(
|
||||
self.path(identifier)
|
||||
),
|
||||
"Migration archive already exists",
|
||||
)
|
||||
|
||||
records = read_chain(
|
||||
self.store,
|
||||
identifier,
|
||||
)
|
||||
|
||||
context = records[".approval.json"]["context"]
|
||||
|
||||
migration = records[".migration-result.json"]
|
||||
|
||||
release = context["release"]
|
||||
|
||||
require(
|
||||
context["site"] == self.site,
|
||||
"Migration belongs to another site",
|
||||
)
|
||||
|
||||
require(
|
||||
self.current_probe() == release,
|
||||
"Unexpected active release",
|
||||
)
|
||||
|
||||
require(
|
||||
self.identity_probe()
|
||||
== context["database_identity"]
|
||||
and self.history_probe()
|
||||
== migration["history_after"],
|
||||
"Database state changed",
|
||||
)
|
||||
|
||||
provenance = self.provenance_probe(release)
|
||||
|
||||
require(
|
||||
isinstance(provenance, dict)
|
||||
and provenance.get("revision")
|
||||
== context["revision"]
|
||||
and provenance.get("fingerprint")
|
||||
== context["provenance"],
|
||||
"Release provenance changed",
|
||||
)
|
||||
|
||||
require(
|
||||
self.backup_probe() is True,
|
||||
"Backup verification failed",
|
||||
)
|
||||
|
||||
require(
|
||||
self.writes_enabled_probe() is True,
|
||||
"Application remains contained",
|
||||
)
|
||||
|
||||
health = self.health_probe(release)
|
||||
|
||||
require(
|
||||
isinstance(health, dict)
|
||||
and health.get("healthy") is True
|
||||
and health.get("release") == release,
|
||||
"Application health verification failed",
|
||||
)
|
||||
|
||||
require(
|
||||
self.current_probe() == release
|
||||
and read_chain(
|
||||
self.store,
|
||||
identifier,
|
||||
) == records,
|
||||
"Migration evidence changed during planning",
|
||||
)
|
||||
|
||||
plan = {
|
||||
"format_version": 1,
|
||||
"status": "ARCHIVE_READY",
|
||||
"approval_id": identifier,
|
||||
"site": self.site,
|
||||
"release": release,
|
||||
"record_checksums": {
|
||||
suffix: item["checksum"]
|
||||
for suffix, item in records.items()
|
||||
},
|
||||
"confirmation": (
|
||||
"ARCHIVE-MIGRATION-" + identifier
|
||||
),
|
||||
}
|
||||
|
||||
plan["fingerprint"] = canonical_hash(plan)
|
||||
|
||||
return plan
|
||||
|
||||
def plan(self, identifier):
|
||||
|
||||
with DeploymentLock(self.lock_path):
|
||||
|
||||
try:
|
||||
|
||||
return self._plan(identifier)
|
||||
|
||||
except MigrationArchiveError:
|
||||
raise
|
||||
|
||||
except Exception:
|
||||
|
||||
raise MigrationArchiveError(
|
||||
"Migration archival preflight failed"
|
||||
) from None
|
||||
|
||||
def execute(
|
||||
self,
|
||||
identifier,
|
||||
*,
|
||||
confirmation,
|
||||
fingerprint,
|
||||
):
|
||||
|
||||
with DeploymentLock(self.lock_path):
|
||||
|
||||
with DeploymentLock(
|
||||
self.store.directory / ".approval.lock"
|
||||
):
|
||||
|
||||
try:
|
||||
|
||||
plan = self._plan(identifier)
|
||||
|
||||
require(
|
||||
confirmation == plan["confirmation"]
|
||||
and fingerprint == plan["fingerprint"],
|
||||
"Archive confirmation or fingerprint changed",
|
||||
)
|
||||
|
||||
record = {
|
||||
"format_version": 1,
|
||||
"status": "ARCHIVED",
|
||||
"approval_id": identifier,
|
||||
"site": self.site,
|
||||
"release": plan["release"],
|
||||
"record_checksums": (
|
||||
plan["record_checksums"]
|
||||
),
|
||||
"plan_fingerprint": fingerprint,
|
||||
"database_restored": False,
|
||||
"archived_at": datetime.now(
|
||||
timezone.utc
|
||||
).isoformat(),
|
||||
}
|
||||
|
||||
record["checksum"] = digest(record)
|
||||
|
||||
self.store.publish(
|
||||
self.path(identifier),
|
||||
record,
|
||||
)
|
||||
|
||||
verify_archived_group(
|
||||
self.store,
|
||||
identifier,
|
||||
)
|
||||
|
||||
return record
|
||||
|
||||
except MigrationArchiveError:
|
||||
raise
|
||||
|
||||
except Exception:
|
||||
|
||||
raise MigrationArchiveError(
|
||||
"Migration archival failed; "
|
||||
"inspect preserved evidence"
|
||||
) from None
|
||||
@@ -0,0 +1,521 @@
|
||||
"""Conservative migration recovery and forward activation.
|
||||
|
||||
External operations must be supplied by trusted adapters.
|
||||
No direct database, Docker or shell execution.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from core.approval import validate_context
|
||||
from core.compatibility import canonical_hash
|
||||
from core.locking import DeploymentLock
|
||||
from core.migration import validate_history
|
||||
|
||||
|
||||
class MigrationRecoveryError(RuntimeError):
|
||||
"""Migration recovery is unsafe or incomplete."""
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
|
||||
if not condition:
|
||||
raise MigrationRecoveryError(message)
|
||||
|
||||
|
||||
class MigrationRecovery:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
site,
|
||||
store,
|
||||
lock_path,
|
||||
identity_probe,
|
||||
history_probe,
|
||||
provenance_probe,
|
||||
backup_probe,
|
||||
contain,
|
||||
containment_probe,
|
||||
current_probe,
|
||||
activate,
|
||||
refresh,
|
||||
readiness_probe,
|
||||
release_containment,
|
||||
writes_enabled_probe,
|
||||
health_probe,
|
||||
):
|
||||
|
||||
self.site = site
|
||||
self.store = store
|
||||
self.lock_path = Path(lock_path)
|
||||
|
||||
callbacks = {
|
||||
"identity_probe": identity_probe,
|
||||
"history_probe": history_probe,
|
||||
"provenance_probe": provenance_probe,
|
||||
"backup_probe": backup_probe,
|
||||
"contain": contain,
|
||||
"containment_probe": containment_probe,
|
||||
"current_probe": current_probe,
|
||||
"activate": activate,
|
||||
"refresh": refresh,
|
||||
"readiness_probe": readiness_probe,
|
||||
"release_containment": release_containment,
|
||||
"writes_enabled_probe": writes_enabled_probe,
|
||||
"health_probe": health_probe,
|
||||
}
|
||||
|
||||
for name, callback in callbacks.items():
|
||||
|
||||
require(
|
||||
callable(callback),
|
||||
"Missing recovery adapter",
|
||||
)
|
||||
|
||||
setattr(self, name, callback)
|
||||
|
||||
def intent_path(self, identifier):
|
||||
|
||||
return self.store.path(
|
||||
identifier,
|
||||
".activation-intent.json",
|
||||
)
|
||||
|
||||
def result_path(self, identifier):
|
||||
|
||||
return self.store.path(
|
||||
identifier,
|
||||
".activation-result.json",
|
||||
)
|
||||
|
||||
def read_record(self, path):
|
||||
|
||||
record = self.store.read(path)
|
||||
|
||||
require(
|
||||
isinstance(record, dict)
|
||||
and "checksum" in record
|
||||
and type(record.get("format_version")) is int
|
||||
and record["format_version"] == 1,
|
||||
"Invalid recovery evidence",
|
||||
)
|
||||
|
||||
expected = canonical_hash({
|
||||
key: value
|
||||
for key, value in record.items()
|
||||
if key != "checksum"
|
||||
})
|
||||
|
||||
require(
|
||||
expected == record["checksum"],
|
||||
"Recovery evidence checksum mismatch",
|
||||
)
|
||||
|
||||
return record
|
||||
|
||||
def publish(self, path, record):
|
||||
|
||||
data = dict(record)
|
||||
data["checksum"] = canonical_hash(data)
|
||||
|
||||
return self.store.publish(path, data)
|
||||
|
||||
def inspect(self, identifier):
|
||||
|
||||
with DeploymentLock(self.lock_path):
|
||||
|
||||
try:
|
||||
return self._inspect(identifier)
|
||||
|
||||
except Exception:
|
||||
|
||||
raise MigrationRecoveryError(
|
||||
"Migration recovery verification failed"
|
||||
) from None
|
||||
|
||||
def _inspect(self, identifier):
|
||||
|
||||
approval = self.store.load(identifier)
|
||||
|
||||
context = approval["context"]
|
||||
validate_context(context)
|
||||
|
||||
intent = self.read_record(
|
||||
self.store.path(
|
||||
identifier,
|
||||
".migration-intent.json",
|
||||
)
|
||||
)
|
||||
|
||||
consumed = self.read_record(
|
||||
self.store.consumed_path(identifier)
|
||||
)
|
||||
|
||||
result = self.read_record(
|
||||
self.store.path(
|
||||
identifier,
|
||||
".migration-result.json",
|
||||
)
|
||||
)
|
||||
|
||||
require(
|
||||
intent["status"] == "MIGRATION_INTENT"
|
||||
and consumed["status"] == "CONSUMED"
|
||||
and result["status"] == "MIGRATED",
|
||||
"Successful migration evidence required",
|
||||
)
|
||||
|
||||
for record in (intent, consumed, result):
|
||||
|
||||
require(
|
||||
record["approval_id"] == identifier
|
||||
and record["site"] == self.site
|
||||
and record["site"] == context["site"]
|
||||
and record["release"] == context["release"]
|
||||
and record["revision"] == context["revision"]
|
||||
and record["database_identity"]
|
||||
== context["database_identity"],
|
||||
"Migration evidence identity mismatch",
|
||||
)
|
||||
|
||||
require(
|
||||
intent["approval_checksum"] == approval["checksum"]
|
||||
and consumed["approval_checksum"]
|
||||
== approval["checksum"]
|
||||
and result["intent_checksum"] == intent["checksum"]
|
||||
and result["consumption_checksum"]
|
||||
== consumed["checksum"],
|
||||
"Migration evidence chain mismatch",
|
||||
)
|
||||
|
||||
require(
|
||||
intent["context_fingerprint"]
|
||||
== canonical_hash(context),
|
||||
"Migration context fingerprint mismatch",
|
||||
)
|
||||
|
||||
for field in (
|
||||
"backup_sha256",
|
||||
"rehearsal_fingerprint",
|
||||
):
|
||||
|
||||
require(
|
||||
intent[field] == context[field]
|
||||
and consumed[field] == context[field],
|
||||
"Migration evidence context mismatch",
|
||||
)
|
||||
|
||||
require(
|
||||
result["automatic_database_rollback"] is False
|
||||
and result["application_activated"] is False
|
||||
and result["containment_required"] is True
|
||||
and consumed["migration_executed"] is False,
|
||||
"Unexpected migration state",
|
||||
)
|
||||
|
||||
before = validate_history(
|
||||
intent["history_before"]
|
||||
)
|
||||
|
||||
pending = validate_history(
|
||||
context["pending_migrations"]
|
||||
)
|
||||
|
||||
require(
|
||||
not set(before).intersection(pending)
|
||||
and intent["pending_migrations"] == pending
|
||||
and result["applied_migrations"] == pending
|
||||
and result["history_after"] == before + pending,
|
||||
"Migration history evidence mismatch",
|
||||
)
|
||||
|
||||
require(
|
||||
self.identity_probe()
|
||||
== context["database_identity"],
|
||||
"Database identity changed",
|
||||
)
|
||||
|
||||
require(
|
||||
validate_history(
|
||||
self.history_probe()
|
||||
) == result["history_after"],
|
||||
"Live migration history changed",
|
||||
)
|
||||
|
||||
release = context["release"]
|
||||
|
||||
evidence = self.provenance_probe(release)
|
||||
|
||||
require(
|
||||
isinstance(evidence, dict)
|
||||
and evidence.get("revision")
|
||||
== context["revision"]
|
||||
and evidence.get("fingerprint")
|
||||
== context["provenance"],
|
||||
"Candidate provenance changed",
|
||||
)
|
||||
|
||||
require(
|
||||
self.backup_probe() is True,
|
||||
"Backup integrity could not be verified",
|
||||
)
|
||||
|
||||
current = self.current_probe()
|
||||
|
||||
require(
|
||||
isinstance(current, str)
|
||||
and current.isascii()
|
||||
and current.isdecimal()
|
||||
and not current.startswith("0")
|
||||
and len(current) <= 20,
|
||||
"Invalid active release",
|
||||
)
|
||||
|
||||
for path in (
|
||||
self.intent_path(identifier),
|
||||
self.result_path(identifier),
|
||||
):
|
||||
|
||||
require(
|
||||
not os.path.lexists(path),
|
||||
"Existing activation evidence requires inspection",
|
||||
)
|
||||
|
||||
plan = {
|
||||
"format_version": 1,
|
||||
"status": "FORWARD_ACTIVATION_READY",
|
||||
"site": self.site,
|
||||
"approval_id": identifier,
|
||||
"current": current,
|
||||
"target": release,
|
||||
"revision": context["revision"],
|
||||
"provenance": context["provenance"],
|
||||
"database_identity": context["database_identity"],
|
||||
"backup_sha256": context["backup_sha256"],
|
||||
"history_after": result["history_after"],
|
||||
"migration_checksum": result["checksum"],
|
||||
"approval_checksum": approval["checksum"],
|
||||
"confirmation": "ACTIVATE-" + identifier,
|
||||
"automatic_database_rollback": False,
|
||||
"migration_reexecution_allowed": False,
|
||||
}
|
||||
|
||||
plan["plan_fingerprint"] = canonical_hash(plan)
|
||||
|
||||
return plan
|
||||
|
||||
def execute(
|
||||
self,
|
||||
identifier,
|
||||
*,
|
||||
confirmation,
|
||||
fingerprint,
|
||||
):
|
||||
|
||||
with DeploymentLock(self.lock_path):
|
||||
|
||||
return self._execute(
|
||||
identifier,
|
||||
confirmation,
|
||||
fingerprint,
|
||||
)
|
||||
|
||||
def _execute(
|
||||
self,
|
||||
identifier,
|
||||
confirmation,
|
||||
fingerprint,
|
||||
):
|
||||
|
||||
operation = "preflight"
|
||||
intent = None
|
||||
containment_started = False
|
||||
|
||||
try:
|
||||
|
||||
plan = self._inspect(identifier)
|
||||
|
||||
require(
|
||||
confirmation == plan["confirmation"]
|
||||
and fingerprint == plan["plan_fingerprint"],
|
||||
"Activation confirmation or fingerprint changed",
|
||||
)
|
||||
|
||||
operation = "establish containment"
|
||||
containment_started = True
|
||||
|
||||
require(
|
||||
self.contain() is True
|
||||
and self.containment_probe() is True,
|
||||
"Write containment failed",
|
||||
)
|
||||
|
||||
operation = "revalidate recovery evidence"
|
||||
|
||||
require(
|
||||
self._inspect(identifier) == plan,
|
||||
"Migration recovery plan changed",
|
||||
)
|
||||
|
||||
operation = "persist activation intent"
|
||||
|
||||
intent = self.publish(
|
||||
self.intent_path(identifier),
|
||||
{
|
||||
"format_version": 1,
|
||||
"status": "ACTIVATION_INTENT",
|
||||
"approval_id": identifier,
|
||||
"site": self.site,
|
||||
"target": plan["target"],
|
||||
"plan_fingerprint": fingerprint,
|
||||
"migration_checksum": (
|
||||
plan["migration_checksum"]
|
||||
),
|
||||
"created_at": datetime.now(
|
||||
timezone.utc
|
||||
).isoformat(),
|
||||
},
|
||||
)
|
||||
|
||||
operation = "activate migrated release"
|
||||
|
||||
require(
|
||||
self.containment_probe() is True,
|
||||
"Containment lost before activation",
|
||||
)
|
||||
|
||||
target = plan["target"]
|
||||
|
||||
require(
|
||||
self.activate(target) is True
|
||||
and self.current_probe() == target,
|
||||
"Candidate activation failed",
|
||||
)
|
||||
|
||||
operation = "refresh application"
|
||||
|
||||
require(
|
||||
self.refresh() is True,
|
||||
"Application refresh failed",
|
||||
)
|
||||
|
||||
operation = "verify contained application"
|
||||
|
||||
require(
|
||||
self.readiness_probe() is True
|
||||
and self.containment_probe() is True,
|
||||
"Contained application is not ready",
|
||||
)
|
||||
|
||||
require(
|
||||
self.identity_probe()
|
||||
== plan["database_identity"]
|
||||
and validate_history(
|
||||
self.history_probe()
|
||||
) == plan["history_after"],
|
||||
"Database state changed during activation",
|
||||
)
|
||||
|
||||
evidence = self.provenance_probe(target)
|
||||
|
||||
require(
|
||||
isinstance(evidence, dict)
|
||||
and evidence.get("revision")
|
||||
== plan["revision"]
|
||||
and evidence.get("fingerprint")
|
||||
== plan["provenance"]
|
||||
and self.current_probe() == target,
|
||||
"Candidate changed during activation",
|
||||
)
|
||||
|
||||
operation = "release containment"
|
||||
|
||||
require(
|
||||
self.release_containment() is True
|
||||
and self.writes_enabled_probe() is True,
|
||||
"Application reopening failed",
|
||||
)
|
||||
|
||||
operation = "verify application health"
|
||||
|
||||
report = self.health_probe(target)
|
||||
|
||||
require(
|
||||
isinstance(report, dict)
|
||||
and report.get("healthy") is True
|
||||
and report.get("release") == target
|
||||
and self.current_probe() == target,
|
||||
"Application health verification failed",
|
||||
)
|
||||
|
||||
operation = "persist activation result"
|
||||
|
||||
return self.publish(
|
||||
self.result_path(identifier),
|
||||
{
|
||||
"format_version": 1,
|
||||
"status": "VERIFIED",
|
||||
"approval_id": identifier,
|
||||
"site": self.site,
|
||||
"active_release": target,
|
||||
"intent_checksum": intent["checksum"],
|
||||
"plan_fingerprint": fingerprint,
|
||||
"health_verified": True,
|
||||
"database_restored": False,
|
||||
"migration_reexecuted": False,
|
||||
"completed_at": datetime.now(
|
||||
timezone.utc
|
||||
).isoformat(),
|
||||
},
|
||||
)
|
||||
|
||||
except Exception:
|
||||
|
||||
containment_ok = None
|
||||
|
||||
if containment_started:
|
||||
|
||||
try:
|
||||
|
||||
containment_ok = (
|
||||
self.contain() is True
|
||||
and self.containment_probe() is True
|
||||
)
|
||||
|
||||
except Exception:
|
||||
|
||||
containment_ok = False
|
||||
|
||||
if intent is not None:
|
||||
|
||||
try:
|
||||
|
||||
path = self.result_path(identifier)
|
||||
|
||||
if not os.path.lexists(path):
|
||||
|
||||
self.publish(
|
||||
path,
|
||||
{
|
||||
"format_version": 1,
|
||||
"status": "FAILED",
|
||||
"approval_id": identifier,
|
||||
"intent_checksum": intent["checksum"],
|
||||
"operation": operation,
|
||||
"containment_verified": containment_ok,
|
||||
"manual_recovery_required": True,
|
||||
},
|
||||
)
|
||||
|
||||
except Exception:
|
||||
|
||||
pass
|
||||
|
||||
raise MigrationRecoveryError(
|
||||
f"Forward activation failed during {operation}; "
|
||||
f"containment={containment_ok}; "
|
||||
"explicit inspection required"
|
||||
) from None
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Conservative unfinished-operation protection.
|
||||
|
||||
The approval store must be dedicated to one site.
|
||||
Callers must hold the shared deployment lock.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
from core.migration_archive import (
|
||||
ARCHIVE_SUFFIX,
|
||||
verify_archived_group,
|
||||
)
|
||||
|
||||
|
||||
class OperationBlocked(RuntimeError):
|
||||
"""Existing evidence prevents a new operation."""
|
||||
|
||||
|
||||
class OperationGuard:
|
||||
|
||||
def __init__(self, store):
|
||||
self.store = store
|
||||
|
||||
def inspect(self):
|
||||
blockers = []
|
||||
|
||||
try:
|
||||
self.store.validate_directory()
|
||||
|
||||
entries = list(self.store.directory.iterdir())
|
||||
|
||||
archived_names = set()
|
||||
|
||||
for path in entries:
|
||||
|
||||
name = path.name
|
||||
|
||||
if (
|
||||
name.endswith(ARCHIVE_SUFFIX)
|
||||
and re.fullmatch(
|
||||
r"[a-f0-9]{32}",
|
||||
name[:-len(ARCHIVE_SUFFIX)],
|
||||
) is not None
|
||||
):
|
||||
|
||||
archived_names.update(
|
||||
verify_archived_group(
|
||||
self.store,
|
||||
name[:32],
|
||||
)
|
||||
)
|
||||
|
||||
for path in entries:
|
||||
|
||||
name = path.name
|
||||
|
||||
if name in archived_names:
|
||||
continue
|
||||
|
||||
if name == ".approval.lock":
|
||||
continue
|
||||
|
||||
if name == ".deployment.lock":
|
||||
continue
|
||||
|
||||
if re.fullmatch(
|
||||
r"[a-f0-9]{32}\.approval\.json",
|
||||
name,
|
||||
):
|
||||
|
||||
# An unused approval is not an
|
||||
# unfinished migration.
|
||||
|
||||
self.store.load(name[:32])
|
||||
continue
|
||||
|
||||
blockers.append(name)
|
||||
|
||||
except Exception:
|
||||
|
||||
raise OperationBlocked(
|
||||
"Approval store cannot be safely inspected"
|
||||
) from None
|
||||
|
||||
return {
|
||||
"format_version": 1,
|
||||
"status": "BLOCKED" if blockers else "CLEAR",
|
||||
"blockers": sorted(blockers),
|
||||
"automatic_cleanup": False,
|
||||
}
|
||||
|
||||
def require_clear(self):
|
||||
report = self.inspect()
|
||||
|
||||
if report["status"] != "CLEAR":
|
||||
raise OperationBlocked(
|
||||
"Unfinished migration evidence requires review"
|
||||
)
|
||||
|
||||
return report
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Static preflight for prospective site provisioning.
|
||||
|
||||
No live infrastructure operations are permitted.
|
||||
"""
|
||||
|
||||
from core.configuration import validate_config
|
||||
from core.site_policy import validate_site, validate_registry
|
||||
from core.compatibility import canonical_hash
|
||||
|
||||
|
||||
class PreflightError(RuntimeError):
|
||||
"""Site configuration or preflight is unsafe."""
|
||||
|
||||
|
||||
def site_preflight(config, existing_registry):
|
||||
|
||||
if (
|
||||
not isinstance(existing_registry, list)
|
||||
or len(existing_registry) > 9999
|
||||
):
|
||||
raise PreflightError("Invalid existing site registry")
|
||||
|
||||
try:
|
||||
candidate = validate_config(config)
|
||||
|
||||
policy = validate_site(candidate)
|
||||
|
||||
registry = validate_registry([
|
||||
*existing_registry,
|
||||
candidate,
|
||||
])
|
||||
|
||||
except Exception:
|
||||
|
||||
raise PreflightError(
|
||||
"Static configuration or resource conflict"
|
||||
) from None
|
||||
|
||||
report = {
|
||||
"format_version": 1,
|
||||
"status": "STATIC_PREFLIGHT_PASSED",
|
||||
"site": candidate["site"]["identifier"],
|
||||
"configuration_fingerprint": canonical_hash(candidate),
|
||||
"policy_fingerprint": policy["fingerprint"],
|
||||
"registry_fingerprint": registry["fingerprint"],
|
||||
"site_count": registry["site_count"],
|
||||
"static_policy_verified": True,
|
||||
"registry_conflicts_checked": True,
|
||||
"registry_completeness_verified": False,
|
||||
"runtime_verified": False,
|
||||
"execution_permitted": False,
|
||||
"outstanding_runtime_checks": [
|
||||
"trusted_filesystem_paths",
|
||||
"filesystem_ownership",
|
||||
"live_port_availability",
|
||||
"docker_project_identity",
|
||||
"docker_network_isolation",
|
||||
"database_server_identity",
|
||||
"database_permissions",
|
||||
"repository_authorisation",
|
||||
"secret_availability",
|
||||
"transaction_state_binding",
|
||||
],
|
||||
}
|
||||
|
||||
report["fingerprint"] = canonical_hash(report)
|
||||
|
||||
return report
|
||||
@@ -0,0 +1,284 @@
|
||||
"""Git-backed verification of release-critical files."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class ProvenanceError(RuntimeError):
|
||||
"""Release provenance could not be established."""
|
||||
|
||||
|
||||
DEPENDENCIES = (
|
||||
"composer.json",
|
||||
"composer.lock",
|
||||
"package.json",
|
||||
"package-lock.json",
|
||||
)
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
|
||||
if not condition:
|
||||
raise ProvenanceError(message)
|
||||
|
||||
|
||||
def digest(data):
|
||||
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
class ProvenanceVerifier:
|
||||
|
||||
def __init__(self, repository):
|
||||
|
||||
self.repository = Path(repository).absolute()
|
||||
|
||||
require(
|
||||
self.repository.is_dir()
|
||||
and self.repository.resolve() == self.repository,
|
||||
"Invalid Git repository path",
|
||||
)
|
||||
|
||||
self.git("rev-parse", "--git-dir")
|
||||
|
||||
def git(self, *args):
|
||||
|
||||
try:
|
||||
|
||||
# Prevent inherited Git environment variables
|
||||
# from redirecting commands to another repository.
|
||||
|
||||
environment = {
|
||||
key: value
|
||||
for key, value in os.environ.items()
|
||||
if not key.startswith("GIT_")
|
||||
}
|
||||
|
||||
environment["GIT_TERMINAL_PROMPT"] = "0"
|
||||
environment["GIT_NO_REPLACE_OBJECTS"] = "1"
|
||||
|
||||
return subprocess.check_output(
|
||||
[
|
||||
"git",
|
||||
"-C",
|
||||
str(self.repository),
|
||||
*args,
|
||||
],
|
||||
stdin=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
env=environment,
|
||||
timeout=30,
|
||||
)
|
||||
|
||||
except (
|
||||
OSError,
|
||||
subprocess.SubprocessError,
|
||||
):
|
||||
|
||||
raise ProvenanceError(
|
||||
"Git provenance command failed"
|
||||
) from None
|
||||
|
||||
def safe_file(self, root, relative):
|
||||
|
||||
relative = Path(relative)
|
||||
|
||||
require(
|
||||
not relative.is_absolute()
|
||||
and ".." not in relative.parts,
|
||||
"Unsafe release file path",
|
||||
)
|
||||
|
||||
path = root
|
||||
|
||||
for part in relative.parts:
|
||||
|
||||
path = path / part
|
||||
|
||||
require(
|
||||
not path.is_symlink(),
|
||||
"Symbolic links prohibited in provenance files",
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
details = path.lstat()
|
||||
|
||||
except OSError:
|
||||
|
||||
raise ProvenanceError(
|
||||
f"Missing release file: {relative}"
|
||||
) from None
|
||||
|
||||
require(
|
||||
stat.S_ISREG(details.st_mode),
|
||||
f"Invalid release file: {relative}",
|
||||
)
|
||||
|
||||
require(
|
||||
path.resolve().is_relative_to(root),
|
||||
"Release file escaped its directory",
|
||||
)
|
||||
|
||||
return path
|
||||
|
||||
def migration_inventory(self, root):
|
||||
|
||||
directory = root / "database/migrations"
|
||||
|
||||
require(
|
||||
directory.is_dir()
|
||||
and directory.resolve() == directory,
|
||||
"Invalid migration directory",
|
||||
)
|
||||
|
||||
result = []
|
||||
|
||||
for path in directory.rglob("*"):
|
||||
|
||||
require(
|
||||
not path.is_symlink(),
|
||||
"Symbolic link in migration directory",
|
||||
)
|
||||
|
||||
if path.suffix == ".php":
|
||||
|
||||
require(
|
||||
path.is_file(),
|
||||
"Invalid migration file",
|
||||
)
|
||||
|
||||
result.append(
|
||||
path.relative_to(root).as_posix()
|
||||
)
|
||||
|
||||
return sorted(result)
|
||||
|
||||
def verify(self, release):
|
||||
|
||||
root = Path(release).absolute()
|
||||
|
||||
require(
|
||||
root.is_dir()
|
||||
and root.resolve() == root,
|
||||
"Invalid release directory",
|
||||
)
|
||||
|
||||
revision = self.safe_file(
|
||||
root, "REVISION"
|
||||
).read_text().strip()
|
||||
|
||||
require(
|
||||
re.fullmatch(
|
||||
r"[a-f0-9]{40}", revision
|
||||
) is not None,
|
||||
"Invalid release revision",
|
||||
)
|
||||
|
||||
require(
|
||||
self.git(
|
||||
"cat-file",
|
||||
"-t",
|
||||
revision,
|
||||
).strip() == b"commit",
|
||||
"Release revision is not a Git commit",
|
||||
)
|
||||
|
||||
raw = self.git(
|
||||
"ls-tree",
|
||||
"-r",
|
||||
"-z",
|
||||
revision,
|
||||
)
|
||||
|
||||
entries = {}
|
||||
|
||||
for entry in raw.split(b"\x00"):
|
||||
|
||||
if not entry:
|
||||
continue
|
||||
|
||||
metadata, name = entry.split(b"\t", 1)
|
||||
|
||||
mode, kind, object_id = metadata.decode().split()
|
||||
|
||||
name = name.decode("utf-8")
|
||||
|
||||
entries[name] = {
|
||||
"mode": mode,
|
||||
"kind": kind,
|
||||
"object_id": object_id,
|
||||
}
|
||||
|
||||
migrations = sorted(
|
||||
name for name in entries
|
||||
if name.startswith("database/migrations/")
|
||||
and name.endswith(".php")
|
||||
)
|
||||
|
||||
require(
|
||||
self.migration_inventory(root) == migrations,
|
||||
"Migration inventory differs from Git revision",
|
||||
)
|
||||
|
||||
verified = {}
|
||||
|
||||
for name in (*migrations, *DEPENDENCIES):
|
||||
|
||||
require(
|
||||
name in entries,
|
||||
f"File missing from Git revision: {name}",
|
||||
)
|
||||
|
||||
entry = entries[name]
|
||||
|
||||
require(
|
||||
entry["kind"] == "blob"
|
||||
and entry["mode"] in ("100644", "100755"),
|
||||
f"Unsafe Git file type: {name}",
|
||||
)
|
||||
|
||||
expected = self.git(
|
||||
"cat-file",
|
||||
"blob",
|
||||
entry["object_id"],
|
||||
)
|
||||
|
||||
path = self.safe_file(root, name)
|
||||
|
||||
actual = path.read_bytes()
|
||||
|
||||
require(
|
||||
digest(actual) == digest(expected),
|
||||
f"Release file differs from Git revision: {name}",
|
||||
)
|
||||
|
||||
verified[name] = digest(actual)
|
||||
|
||||
result = {
|
||||
"format_version": 1,
|
||||
"revision": revision,
|
||||
"migrations": {
|
||||
name: verified[name]
|
||||
for name in migrations
|
||||
},
|
||||
"dependencies": {
|
||||
name: verified[name]
|
||||
for name in DEPENDENCIES
|
||||
},
|
||||
}
|
||||
|
||||
canonical = json.dumps(
|
||||
result,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
).encode()
|
||||
|
||||
result["fingerprint"] = digest(canonical)
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,242 @@
|
||||
"""Conservative read-only deployment recovery planning."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from core.backup_evidence import FIELDS
|
||||
from core.compatibility import (
|
||||
canonical_hash,
|
||||
require_compatible,
|
||||
validate_provenance,
|
||||
)
|
||||
from core.locking import DeploymentLock
|
||||
|
||||
|
||||
class RecoveryError(RuntimeError):
|
||||
"""Recovery safety could not be established."""
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
|
||||
if not condition:
|
||||
raise RecoveryError(message)
|
||||
|
||||
|
||||
class RecoveryPlanner:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
site,
|
||||
lock_path,
|
||||
releases,
|
||||
provenance,
|
||||
journal,
|
||||
backup_evidence,
|
||||
backup_verify,
|
||||
runtime_check,
|
||||
):
|
||||
|
||||
self.site = site
|
||||
self.lock_path = Path(lock_path)
|
||||
self.releases = releases
|
||||
self.provenance = provenance
|
||||
self.journal = journal
|
||||
self.backup_evidence = backup_evidence
|
||||
self.backup_verify = backup_verify
|
||||
self.runtime_check = runtime_check
|
||||
|
||||
def inspect(self):
|
||||
|
||||
with DeploymentLock(self.lock_path):
|
||||
|
||||
try:
|
||||
|
||||
return self._inspect()
|
||||
|
||||
except RecoveryError:
|
||||
raise
|
||||
|
||||
except Exception:
|
||||
|
||||
raise RecoveryError(
|
||||
"Recovery verification failed"
|
||||
) from None
|
||||
|
||||
def _inspect(self):
|
||||
|
||||
transaction = self.journal.load()
|
||||
|
||||
result = {
|
||||
"format_version": 1,
|
||||
"site": self.site,
|
||||
"automatic_rollback_allowed": False,
|
||||
"database_restore_allowed": False,
|
||||
"execution_permitted": False,
|
||||
}
|
||||
|
||||
if transaction is None:
|
||||
|
||||
result["status"] = "CLEAR"
|
||||
|
||||
return result
|
||||
|
||||
require(
|
||||
transaction["site"] == self.site,
|
||||
"Transaction belongs to another site",
|
||||
)
|
||||
|
||||
current = self.releases.current()
|
||||
|
||||
previous = transaction["previous"]
|
||||
candidate = transaction["candidate"]
|
||||
|
||||
require(
|
||||
current in (previous, candidate),
|
||||
"Unexpected active release",
|
||||
)
|
||||
|
||||
result.update({
|
||||
"transaction_id": transaction["transaction_id"],
|
||||
"transaction_checksum": transaction["checksum"],
|
||||
"phase": transaction["phase"],
|
||||
"current": current,
|
||||
"previous": previous,
|
||||
"candidate": candidate,
|
||||
"target": None,
|
||||
"confirmation": None,
|
||||
})
|
||||
|
||||
if transaction["phase"] == "VERIFIED":
|
||||
|
||||
require(
|
||||
current == candidate,
|
||||
"Verified transaction has inconsistent active release",
|
||||
)
|
||||
|
||||
result["status"] = "VERIFIED"
|
||||
|
||||
return result
|
||||
|
||||
if current == previous:
|
||||
|
||||
result["status"] = (
|
||||
"PREVIOUS_ACTIVE_REVIEW_REQUIRED"
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
history = {
|
||||
event["phase"]
|
||||
for event in transaction["history"]
|
||||
}
|
||||
|
||||
require(
|
||||
{
|
||||
"BACKED_UP",
|
||||
"QUIESCED",
|
||||
"ACTIVATING",
|
||||
} <= history,
|
||||
"Activation evidence is incomplete",
|
||||
)
|
||||
|
||||
require(
|
||||
transaction["phase"] in (
|
||||
"ACTIVATING",
|
||||
"ACTIVATED",
|
||||
"FAILED",
|
||||
),
|
||||
"Transaction phase does not permit rollback review",
|
||||
)
|
||||
|
||||
old = self.provenance.verify(
|
||||
self.releases.validate(previous)
|
||||
)
|
||||
|
||||
new = self.provenance.verify(
|
||||
self.releases.validate(candidate)
|
||||
)
|
||||
|
||||
validate_provenance(old)
|
||||
validate_provenance(new)
|
||||
|
||||
require(
|
||||
new["revision"] == transaction["revision"]
|
||||
and new["fingerprint"] == transaction["provenance"],
|
||||
"Candidate provenance differs from transaction",
|
||||
)
|
||||
|
||||
require(
|
||||
transaction["previous_revision"] is not None
|
||||
and transaction["previous_provenance"] is not None
|
||||
and old["revision"]
|
||||
== transaction["previous_revision"]
|
||||
and old["fingerprint"]
|
||||
== transaction["previous_provenance"],
|
||||
"Previous release provenance differs from transaction",
|
||||
)
|
||||
|
||||
compatibility = require_compatible(
|
||||
new,
|
||||
old,
|
||||
)
|
||||
|
||||
evidence = self.backup_evidence.load(
|
||||
transaction["transaction_id"]
|
||||
)
|
||||
|
||||
recorded = evidence["backup"]
|
||||
|
||||
manifest = self.backup_verify(
|
||||
recorded["backup_id"]
|
||||
)
|
||||
|
||||
require(
|
||||
isinstance(manifest, dict)
|
||||
and FIELDS <= set(manifest),
|
||||
"Invalid verified backup manifest",
|
||||
)
|
||||
|
||||
verified = {
|
||||
field: manifest[field]
|
||||
for field in FIELDS
|
||||
}
|
||||
|
||||
require(
|
||||
verified == recorded,
|
||||
"Verified backup differs from transaction evidence",
|
||||
)
|
||||
|
||||
require(
|
||||
self.runtime_check() is True,
|
||||
"Database runtime verification failed",
|
||||
)
|
||||
|
||||
require(
|
||||
self.releases.current() == current,
|
||||
"Active release changed during inspection",
|
||||
)
|
||||
|
||||
require(
|
||||
self.journal.load() == transaction,
|
||||
"Transaction changed during inspection",
|
||||
)
|
||||
|
||||
result.update({
|
||||
"status": "ROLLBACK_REVIEW_READY",
|
||||
"target": previous,
|
||||
"backup_id": recorded["backup_id"],
|
||||
"backup_sha256": recorded["sha256"],
|
||||
"backup_evidence_checksum": evidence["checksum"],
|
||||
"previous_provenance": old["fingerprint"],
|
||||
"candidate_provenance": new["fingerprint"],
|
||||
"compatibility_fingerprint": (
|
||||
compatibility["fingerprint"]
|
||||
),
|
||||
"confirmation": (
|
||||
"ROLLBACK-" + transaction["transaction_id"]
|
||||
),
|
||||
})
|
||||
|
||||
result["plan_fingerprint"] = canonical_hash(result)
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,304 @@
|
||||
"""Migration rehearsal evidence validation.
|
||||
|
||||
This module does not create databases, restore backups
|
||||
or execute migrations. It validates supplied evidence.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
from core.approval import (
|
||||
ApprovalError,
|
||||
CONTEXT_FIELDS,
|
||||
validate_context,
|
||||
timestamp,
|
||||
parse_timestamp,
|
||||
)
|
||||
|
||||
from core.compatibility import canonical_hash
|
||||
|
||||
|
||||
class RehearsalError(RuntimeError):
|
||||
"""Invalid or insufficient migration rehearsal evidence."""
|
||||
|
||||
|
||||
BASE_FIELDS = CONTEXT_FIELDS - {
|
||||
"rehearsal_fingerprint",
|
||||
}
|
||||
|
||||
EXECUTION_FIELDS = {
|
||||
"driver",
|
||||
"source_database",
|
||||
"target_database",
|
||||
"target_identity",
|
||||
"applied_migrations",
|
||||
"checks",
|
||||
}
|
||||
|
||||
CHECK_FIELDS = {
|
||||
"isolation_verified",
|
||||
"backup_restored",
|
||||
"migration_succeeded",
|
||||
"migration_history_verified",
|
||||
"application_verified",
|
||||
"cleanup_verified",
|
||||
}
|
||||
|
||||
RECORD_FIELDS = {
|
||||
"format_version",
|
||||
"rehearsal_id",
|
||||
"context",
|
||||
"execution",
|
||||
"completed_at",
|
||||
"fingerprint",
|
||||
}
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
|
||||
if not condition:
|
||||
raise RehearsalError(message)
|
||||
|
||||
|
||||
def matches(value, pattern):
|
||||
|
||||
return (
|
||||
isinstance(value, str)
|
||||
and re.fullmatch(pattern, value) is not None
|
||||
)
|
||||
|
||||
|
||||
def validate_base_context(context):
|
||||
|
||||
require(
|
||||
isinstance(context, dict)
|
||||
and set(context) == BASE_FIELDS,
|
||||
"Invalid rehearsal context",
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
validate_context({
|
||||
**context,
|
||||
"rehearsal_fingerprint": "0" * 64,
|
||||
})
|
||||
|
||||
except ApprovalError:
|
||||
|
||||
raise RehearsalError(
|
||||
"Invalid rehearsal approval context"
|
||||
) from None
|
||||
|
||||
|
||||
def validate_execution(context, execution):
|
||||
|
||||
require(
|
||||
isinstance(execution, dict)
|
||||
and set(execution) == EXECUTION_FIELDS,
|
||||
"Invalid rehearsal execution evidence",
|
||||
)
|
||||
|
||||
require(
|
||||
execution["driver"] in (
|
||||
"mysql",
|
||||
"postgresql",
|
||||
),
|
||||
"Unsupported rehearsal database driver",
|
||||
)
|
||||
|
||||
source = execution["source_database"]
|
||||
target = execution["target_database"]
|
||||
|
||||
require(
|
||||
matches(source, r"[A-Za-z_][A-Za-z0-9_]{0,62}"),
|
||||
"Invalid source database",
|
||||
)
|
||||
|
||||
require(
|
||||
matches(
|
||||
target,
|
||||
r"isolated_restore_[a-z0-9_]{1,45}",
|
||||
),
|
||||
"Invalid isolated database name",
|
||||
)
|
||||
|
||||
require(
|
||||
source.lower() != target.lower(),
|
||||
"Rehearsal must not target the source database",
|
||||
)
|
||||
|
||||
require(
|
||||
matches(
|
||||
execution["target_identity"],
|
||||
r"[a-f0-9]{64}",
|
||||
),
|
||||
"Invalid rehearsal database identity",
|
||||
)
|
||||
|
||||
require(
|
||||
execution["target_identity"]
|
||||
!= context["database_identity"],
|
||||
"Rehearsal database identity matches source",
|
||||
)
|
||||
|
||||
require(
|
||||
isinstance(execution["applied_migrations"], list)
|
||||
and execution["applied_migrations"]
|
||||
== context["pending_migrations"],
|
||||
"Applied migrations differ from approved inventory",
|
||||
)
|
||||
|
||||
checks = execution["checks"]
|
||||
|
||||
require(
|
||||
isinstance(checks, dict)
|
||||
and set(checks) == CHECK_FIELDS,
|
||||
"Incomplete rehearsal verification checks",
|
||||
)
|
||||
|
||||
for name, status in checks.items():
|
||||
|
||||
require(
|
||||
status is True,
|
||||
f"Rehearsal check failed: {name}",
|
||||
)
|
||||
|
||||
|
||||
def fingerprint(record):
|
||||
|
||||
return canonical_hash({
|
||||
key: value
|
||||
for key, value in record.items()
|
||||
if key != "fingerprint"
|
||||
})
|
||||
|
||||
|
||||
def create_rehearsal(
|
||||
context,
|
||||
execution,
|
||||
*,
|
||||
completed_at,
|
||||
):
|
||||
|
||||
validate_base_context(context)
|
||||
|
||||
validate_execution(
|
||||
context,
|
||||
execution,
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
completed = timestamp(completed_at)
|
||||
|
||||
except ApprovalError:
|
||||
|
||||
raise RehearsalError(
|
||||
"Invalid rehearsal completion timestamp"
|
||||
) from None
|
||||
|
||||
record = {
|
||||
"format_version": 1,
|
||||
"rehearsal_id": uuid.uuid4().hex,
|
||||
"context": copy.deepcopy(context),
|
||||
"execution": copy.deepcopy(execution),
|
||||
"completed_at": completed.isoformat(),
|
||||
}
|
||||
|
||||
record["fingerprint"] = fingerprint(record)
|
||||
|
||||
return record
|
||||
|
||||
|
||||
def verify_rehearsal(
|
||||
record,
|
||||
context,
|
||||
*,
|
||||
now,
|
||||
):
|
||||
|
||||
validate_base_context(context)
|
||||
|
||||
require(
|
||||
isinstance(record, dict)
|
||||
and set(record) == RECORD_FIELDS,
|
||||
"Invalid rehearsal record",
|
||||
)
|
||||
|
||||
require(
|
||||
type(record["format_version"]) is int
|
||||
and record["format_version"] == 1,
|
||||
"Unsupported rehearsal format",
|
||||
)
|
||||
|
||||
require(
|
||||
matches(
|
||||
record["rehearsal_id"],
|
||||
r"[a-f0-9]{32}",
|
||||
),
|
||||
"Invalid rehearsal identifier",
|
||||
)
|
||||
|
||||
validate_base_context(record["context"])
|
||||
|
||||
require(
|
||||
record["context"] == context,
|
||||
"Rehearsal context changed",
|
||||
)
|
||||
|
||||
validate_execution(
|
||||
context,
|
||||
record["execution"],
|
||||
)
|
||||
|
||||
require(
|
||||
matches(
|
||||
record["fingerprint"],
|
||||
r"[a-f0-9]{64}",
|
||||
)
|
||||
and fingerprint(record) == record["fingerprint"],
|
||||
"Rehearsal fingerprint mismatch",
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
completed = parse_timestamp(
|
||||
record["completed_at"]
|
||||
)
|
||||
|
||||
current = timestamp(now)
|
||||
|
||||
except ApprovalError:
|
||||
|
||||
raise RehearsalError(
|
||||
"Invalid rehearsal timestamp"
|
||||
) from None
|
||||
|
||||
require(
|
||||
timedelta(0)
|
||||
<= current - completed
|
||||
< timedelta(hours=24),
|
||||
"Rehearsal expired or not yet valid",
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def approval_context(record, context, *, now):
|
||||
|
||||
verify_rehearsal(
|
||||
record,
|
||||
context,
|
||||
now=now,
|
||||
)
|
||||
|
||||
result = copy.deepcopy(context)
|
||||
|
||||
result["rehearsal_fingerprint"] = (
|
||||
record["fingerprint"]
|
||||
)
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,231 @@
|
||||
"""Filesystem release management without service side effects."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class ReleaseError(RuntimeError):
|
||||
"""Invalid or unsafe release operation."""
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
|
||||
if not condition:
|
||||
raise ReleaseError(message)
|
||||
|
||||
|
||||
def valid_number(value):
|
||||
|
||||
return (
|
||||
isinstance(value, str)
|
||||
and re.fullmatch(
|
||||
r"[1-9][0-9]*", value
|
||||
) is not None
|
||||
)
|
||||
|
||||
|
||||
def exists(path):
|
||||
return path.exists() or path.is_symlink()
|
||||
|
||||
|
||||
def regular_file(path):
|
||||
|
||||
try:
|
||||
details = path.lstat()
|
||||
return stat.S_ISREG(details.st_mode)
|
||||
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
class ReleaseManager:
|
||||
|
||||
def __init__(self, app):
|
||||
|
||||
self.app = Path(app).absolute()
|
||||
self.releases = self.app / "releases"
|
||||
|
||||
self.validate_layout()
|
||||
|
||||
def validate_layout(self):
|
||||
|
||||
for path in (self.app, self.releases):
|
||||
|
||||
require(
|
||||
path.is_dir()
|
||||
and not path.is_symlink(),
|
||||
"Invalid application directory layout",
|
||||
)
|
||||
|
||||
def inventory(self):
|
||||
|
||||
self.validate_layout()
|
||||
|
||||
result = []
|
||||
|
||||
for path in self.releases.iterdir():
|
||||
|
||||
require(
|
||||
valid_number(path.name)
|
||||
and path.is_dir()
|
||||
and not path.is_symlink(),
|
||||
"Unexpected release inventory entry",
|
||||
)
|
||||
|
||||
result.append(path.name)
|
||||
|
||||
return sorted(result, key=int)
|
||||
|
||||
def release_path(self, release):
|
||||
|
||||
require(
|
||||
valid_number(release),
|
||||
"Invalid release identifier",
|
||||
)
|
||||
|
||||
self.validate_layout()
|
||||
|
||||
root = self.releases / release
|
||||
|
||||
require(
|
||||
root.is_dir()
|
||||
and not root.is_symlink(),
|
||||
"Release does not exist",
|
||||
)
|
||||
|
||||
return root
|
||||
|
||||
def validate(self, release):
|
||||
|
||||
root = self.release_path(release)
|
||||
|
||||
require(
|
||||
not exists(root / "BAD_RELEASE"),
|
||||
"Release marked as rejected",
|
||||
)
|
||||
|
||||
required = (
|
||||
"vendor/autoload.php",
|
||||
"public/build/manifest.json",
|
||||
"REVISION",
|
||||
)
|
||||
|
||||
for relative in required:
|
||||
|
||||
path = root / relative
|
||||
|
||||
require(
|
||||
regular_file(path)
|
||||
and path.resolve().is_relative_to(
|
||||
root.resolve()
|
||||
),
|
||||
f"Missing or unsafe release file: {relative}",
|
||||
)
|
||||
|
||||
revision = (
|
||||
root / "REVISION"
|
||||
).read_text().strip()
|
||||
|
||||
require(
|
||||
re.fullmatch(
|
||||
r"[a-f0-9]{40}", revision
|
||||
) is not None,
|
||||
"Invalid Git revision",
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
manifest = json.loads(
|
||||
(root / "public/build/manifest.json")
|
||||
.read_text()
|
||||
)
|
||||
|
||||
except (ValueError, OSError) as error:
|
||||
|
||||
raise ReleaseError(
|
||||
"Invalid frontend manifest"
|
||||
) from error
|
||||
|
||||
require(
|
||||
isinstance(manifest, dict),
|
||||
"Invalid frontend manifest structure",
|
||||
)
|
||||
|
||||
return root
|
||||
|
||||
def current(self):
|
||||
|
||||
self.validate_layout()
|
||||
|
||||
link = self.app / "current"
|
||||
|
||||
if not exists(link):
|
||||
return None
|
||||
|
||||
require(
|
||||
link.is_symlink(),
|
||||
"Current release must be a symbolic link",
|
||||
)
|
||||
|
||||
match = re.fullmatch(
|
||||
r"releases/([1-9][0-9]*)",
|
||||
os.readlink(link),
|
||||
)
|
||||
|
||||
require(
|
||||
match is not None,
|
||||
"Invalid current release target",
|
||||
)
|
||||
|
||||
release = match.group(1)
|
||||
|
||||
self.release_path(release)
|
||||
|
||||
return release
|
||||
|
||||
def activate(self, release):
|
||||
|
||||
self.current()
|
||||
self.validate(release)
|
||||
|
||||
link = self.app / "current"
|
||||
|
||||
temporary = self.app / (
|
||||
".activation-" + uuid.uuid4().hex
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
temporary.symlink_to(
|
||||
f"releases/{release}"
|
||||
)
|
||||
|
||||
os.replace(temporary, link)
|
||||
|
||||
fd = os.open(
|
||||
self.app,
|
||||
os.O_RDONLY
|
||||
| os.O_DIRECTORY
|
||||
| os.O_NOFOLLOW,
|
||||
)
|
||||
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
finally:
|
||||
|
||||
if temporary.is_symlink():
|
||||
temporary.unlink()
|
||||
|
||||
require(
|
||||
self.current() == release,
|
||||
"Activation verification failed",
|
||||
)
|
||||
|
||||
return release
|
||||
@@ -0,0 +1,191 @@
|
||||
"""Read-only release retention planning.
|
||||
|
||||
The caller must supply a complete and trustworthy
|
||||
inventory of releases and transaction protections.
|
||||
|
||||
No filesystem modification is performed.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
from core.compatibility import canonical_hash
|
||||
|
||||
|
||||
class RetentionError(RuntimeError):
|
||||
"""Invalid or unsafe release retention policy."""
|
||||
|
||||
|
||||
FIELDS = {
|
||||
"inventory",
|
||||
"current",
|
||||
"keep",
|
||||
"protected",
|
||||
"failed",
|
||||
"unresolved",
|
||||
}
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
raise RetentionError(message)
|
||||
|
||||
|
||||
def validate_release(value):
|
||||
require(
|
||||
isinstance(value, str)
|
||||
and re.fullmatch(
|
||||
r"[1-9][0-9]{0,19}",
|
||||
value,
|
||||
) is not None,
|
||||
"Invalid release identifier",
|
||||
)
|
||||
|
||||
|
||||
def validate_inventory(values):
|
||||
require(
|
||||
isinstance(values, list)
|
||||
and len(values) <= 100000,
|
||||
"Invalid release inventory",
|
||||
)
|
||||
|
||||
for value in values:
|
||||
validate_release(value)
|
||||
|
||||
require(
|
||||
len(values) == len(set(values)),
|
||||
"Duplicate release identifiers",
|
||||
)
|
||||
|
||||
return sorted(values, key=int)
|
||||
|
||||
|
||||
def plan_retention(policy):
|
||||
require(
|
||||
isinstance(policy, dict)
|
||||
and set(policy) == FIELDS,
|
||||
"Invalid retention policy structure",
|
||||
)
|
||||
|
||||
inventory = validate_inventory(
|
||||
policy["inventory"]
|
||||
)
|
||||
|
||||
require(
|
||||
bool(inventory),
|
||||
"Release inventory is empty",
|
||||
)
|
||||
|
||||
current = policy["current"]
|
||||
|
||||
validate_release(current)
|
||||
|
||||
available = set(inventory)
|
||||
|
||||
require(
|
||||
current in available,
|
||||
"Active release missing from inventory",
|
||||
)
|
||||
|
||||
keep = policy["keep"]
|
||||
|
||||
require(
|
||||
type(keep) is int
|
||||
and 2 <= keep <= 1000,
|
||||
"Retention count must be between 2 and 1000",
|
||||
)
|
||||
|
||||
protections = {}
|
||||
|
||||
for field in (
|
||||
"protected",
|
||||
"failed",
|
||||
"unresolved",
|
||||
):
|
||||
values = validate_inventory(
|
||||
policy[field]
|
||||
)
|
||||
|
||||
require(
|
||||
set(values) <= available,
|
||||
f"Unknown release in {field} inventory",
|
||||
)
|
||||
|
||||
protections[field] = values
|
||||
|
||||
failed = set(protections["failed"])
|
||||
|
||||
require(
|
||||
current not in failed,
|
||||
"Active release is marked failed",
|
||||
)
|
||||
|
||||
reasons = {}
|
||||
|
||||
def protect(release, reason):
|
||||
reasons.setdefault(release, set()).add(reason)
|
||||
|
||||
protect(current, "active")
|
||||
|
||||
for release in inventory[-keep:]:
|
||||
protect(release, "recent_release")
|
||||
|
||||
for release in protections["protected"]:
|
||||
protect(release, "explicitly_protected")
|
||||
|
||||
for release in protections["failed"]:
|
||||
protect(release, "failed_release")
|
||||
|
||||
for release in protections["unresolved"]:
|
||||
protect(release, "unresolved_transaction")
|
||||
|
||||
previous = [
|
||||
release
|
||||
for release in inventory
|
||||
if int(release) < int(current)
|
||||
and release not in failed
|
||||
]
|
||||
|
||||
if previous:
|
||||
protect(previous[-1], "previous_available")
|
||||
|
||||
blocked = bool(protections["unresolved"])
|
||||
|
||||
if blocked:
|
||||
for release in inventory:
|
||||
protect(release, "operation_unresolved")
|
||||
|
||||
retained = [
|
||||
release
|
||||
for release in inventory
|
||||
if release in reasons
|
||||
]
|
||||
|
||||
candidates = [
|
||||
release
|
||||
for release in inventory
|
||||
if release not in reasons
|
||||
]
|
||||
|
||||
plan = {
|
||||
"format_version": 1,
|
||||
"status": "BLOCKED" if blocked else "READY",
|
||||
"current": current,
|
||||
"keep": keep,
|
||||
"inventory": inventory,
|
||||
"protected": protections["protected"],
|
||||
"failed": protections["failed"],
|
||||
"unresolved": protections["unresolved"],
|
||||
"retained": retained,
|
||||
"archive_candidates": candidates,
|
||||
"reasons": {
|
||||
release: sorted(reasons[release])
|
||||
for release in retained
|
||||
},
|
||||
"automatic_archival": False,
|
||||
"automatic_deletion": False,
|
||||
"execution_permitted": False,
|
||||
}
|
||||
|
||||
plan["fingerprint"] = canonical_hash(plan)
|
||||
|
||||
return plan
|
||||
@@ -0,0 +1,377 @@
|
||||
"""Explicit application rollback with persistent intent.
|
||||
|
||||
Database restoration is intentionally unsupported.
|
||||
External operations must use trusted service adapters.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
import uuid
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from core.compatibility import canonical_hash
|
||||
from core.locking import DeploymentLock
|
||||
|
||||
|
||||
class RollbackError(RuntimeError):
|
||||
"""Rollback failed or requires explicit inspection."""
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
|
||||
if not condition:
|
||||
raise RollbackError(message)
|
||||
|
||||
|
||||
def now():
|
||||
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
class RollbackExecutor:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
planner,
|
||||
services,
|
||||
health,
|
||||
stopped_check,
|
||||
):
|
||||
|
||||
require(
|
||||
callable(stopped_check),
|
||||
"Worker state verification is required",
|
||||
)
|
||||
|
||||
self.planner = planner
|
||||
self.services = services
|
||||
self.health = health
|
||||
self.stopped_check = stopped_check
|
||||
|
||||
self.directory = planner.journal.directory
|
||||
|
||||
self.validate_directory()
|
||||
|
||||
def validate_directory(self):
|
||||
|
||||
directory = self.directory
|
||||
|
||||
require(
|
||||
directory.is_dir()
|
||||
and not directory.is_symlink()
|
||||
and directory.resolve() == directory,
|
||||
"Invalid rollback evidence directory",
|
||||
)
|
||||
|
||||
details = directory.stat()
|
||||
|
||||
require(
|
||||
details.st_uid == os.getuid()
|
||||
and stat.S_IMODE(details.st_mode) == 0o700,
|
||||
"Unsafe rollback evidence directory permissions",
|
||||
)
|
||||
|
||||
def evidence_path(self, transaction_id, suffix):
|
||||
|
||||
require(
|
||||
isinstance(transaction_id, str)
|
||||
and re.fullmatch(
|
||||
r"[a-f0-9]{32}",
|
||||
transaction_id,
|
||||
) is not None,
|
||||
"Invalid rollback transaction identifier",
|
||||
)
|
||||
|
||||
return self.directory / (
|
||||
transaction_id + suffix
|
||||
)
|
||||
|
||||
def intent_path(self, transaction_id):
|
||||
|
||||
return self.evidence_path(
|
||||
transaction_id,
|
||||
".rollback-intent.json",
|
||||
)
|
||||
|
||||
def result_path(self, transaction_id):
|
||||
|
||||
return self.evidence_path(
|
||||
transaction_id,
|
||||
".rollback-result.json",
|
||||
)
|
||||
|
||||
def publish(self, path, data):
|
||||
|
||||
self.validate_directory()
|
||||
|
||||
require(
|
||||
path.parent == self.directory,
|
||||
"Invalid rollback evidence path",
|
||||
)
|
||||
|
||||
data = dict(data)
|
||||
|
||||
data["checksum"] = canonical_hash(data)
|
||||
|
||||
temporary = self.directory / (
|
||||
".rollback-" + 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.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(
|
||||
json.loads(path.read_text()) == data,
|
||||
"Rollback evidence readback failed",
|
||||
)
|
||||
|
||||
return data
|
||||
|
||||
except OSError:
|
||||
|
||||
raise RollbackError(
|
||||
"Rollback evidence persistence failed"
|
||||
) from None
|
||||
|
||||
finally:
|
||||
|
||||
if fd is not None:
|
||||
os.close(fd)
|
||||
|
||||
if created:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
def execute(self, confirmation, fingerprint):
|
||||
|
||||
with DeploymentLock(self.planner.lock_path):
|
||||
|
||||
return self._execute(
|
||||
confirmation,
|
||||
fingerprint,
|
||||
)
|
||||
|
||||
def _execute(self, confirmation, fingerprint):
|
||||
|
||||
operation = "preflight"
|
||||
quiesce_started = False
|
||||
intent = None
|
||||
result_path = None
|
||||
|
||||
try:
|
||||
|
||||
# The deployment lock is already held.
|
||||
# Do not call inspect(), which reacquires it.
|
||||
|
||||
plan = self.planner._inspect()
|
||||
|
||||
require(
|
||||
plan["status"] == "ROLLBACK_REVIEW_READY",
|
||||
"Transaction is not eligible for rollback",
|
||||
)
|
||||
|
||||
require(
|
||||
isinstance(confirmation, str)
|
||||
and confirmation == plan["confirmation"],
|
||||
"Rollback confirmation mismatch",
|
||||
)
|
||||
|
||||
require(
|
||||
isinstance(fingerprint, str)
|
||||
and fingerprint == plan["plan_fingerprint"],
|
||||
"Rollback plan changed",
|
||||
)
|
||||
|
||||
transaction_id = plan["transaction_id"]
|
||||
|
||||
intent_path = self.intent_path(transaction_id)
|
||||
result_path = self.result_path(transaction_id)
|
||||
|
||||
for path in (intent_path, result_path):
|
||||
|
||||
require(
|
||||
not os.path.lexists(path),
|
||||
"Existing rollback evidence requires review",
|
||||
)
|
||||
|
||||
operation = "persist rollback intent"
|
||||
|
||||
intent = self.publish(
|
||||
intent_path,
|
||||
{
|
||||
"format_version": 1,
|
||||
"status": "ROLLBACK_INTENT",
|
||||
"transaction_id": transaction_id,
|
||||
"site": plan["site"],
|
||||
"source": plan["current"],
|
||||
"target": plan["target"],
|
||||
"transaction_checksum": (
|
||||
plan["transaction_checksum"]
|
||||
),
|
||||
"plan_fingerprint": fingerprint,
|
||||
"backup_id": plan["backup_id"],
|
||||
"backup_sha256": plan["backup_sha256"],
|
||||
"created_at": now(),
|
||||
},
|
||||
)
|
||||
|
||||
operation = "quiesce workers"
|
||||
|
||||
quiesce_started = True
|
||||
|
||||
self.services.quiesce()
|
||||
|
||||
require(
|
||||
self.stopped_check() is True,
|
||||
"Background workers remain active",
|
||||
)
|
||||
|
||||
operation = "revalidate recovery plan"
|
||||
|
||||
require(
|
||||
self.planner._inspect() == plan,
|
||||
"Recovery evidence changed after shutdown",
|
||||
)
|
||||
|
||||
operation = "activate previous release"
|
||||
|
||||
target = plan["target"]
|
||||
|
||||
self.planner.releases.activate(target)
|
||||
|
||||
require(
|
||||
self.planner.releases.current() == target,
|
||||
"Rollback activation verification failed",
|
||||
)
|
||||
|
||||
operation = "refresh application"
|
||||
|
||||
self.services.refresh()
|
||||
|
||||
operation = "restore workers"
|
||||
|
||||
self.services.resume()
|
||||
|
||||
operation = "verify application health"
|
||||
|
||||
health = self.health.verify(target)
|
||||
|
||||
require(
|
||||
isinstance(health, dict)
|
||||
and health.get("healthy") is True
|
||||
and health.get("release") == target,
|
||||
"Rollback health verification failed",
|
||||
)
|
||||
|
||||
require(
|
||||
self.planner.releases.current() == target,
|
||||
"Active release changed during rollback",
|
||||
)
|
||||
|
||||
require(
|
||||
self.planner.journal.load()["checksum"]
|
||||
== plan["transaction_checksum"],
|
||||
"Original transaction changed",
|
||||
)
|
||||
|
||||
operation = "persist rollback result"
|
||||
|
||||
return self.publish(
|
||||
result_path,
|
||||
{
|
||||
"format_version": 1,
|
||||
"status": "ROLLED_BACK",
|
||||
"site": plan["site"],
|
||||
"transaction_id": transaction_id,
|
||||
"intent_checksum": intent["checksum"],
|
||||
"plan_fingerprint": fingerprint,
|
||||
"previous_active_release": (
|
||||
plan["current"]
|
||||
),
|
||||
"active_release": target,
|
||||
"health_verified": True,
|
||||
"database_restored": False,
|
||||
"completed_at": now(),
|
||||
},
|
||||
)
|
||||
|
||||
except Exception:
|
||||
|
||||
containment = None
|
||||
|
||||
if quiesce_started:
|
||||
|
||||
try:
|
||||
|
||||
self.services.quiesce()
|
||||
|
||||
containment = (
|
||||
self.stopped_check() is True
|
||||
)
|
||||
|
||||
except Exception:
|
||||
|
||||
containment = False
|
||||
|
||||
# Preserve the original transaction and intent.
|
||||
# Never automatically activate another release.
|
||||
|
||||
raise RollbackError(
|
||||
f"Rollback failed during {operation}; "
|
||||
f"workers_contained={containment}; "
|
||||
"explicit inspection required"
|
||||
) from None
|
||||
@@ -0,0 +1,457 @@
|
||||
"""Archival of successfully rolled-back transactions.
|
||||
|
||||
Preserve original evidence and quarantine failed candidates.
|
||||
Never restore databases or automatically repeat a rollback.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from core.approval_store import ApprovalStore
|
||||
from core.archive import ArchiveError, require, digest, sync_directory
|
||||
from core.backup_evidence import FIELDS
|
||||
from core.compatibility import (
|
||||
canonical_hash,
|
||||
require_compatible,
|
||||
validate_provenance,
|
||||
)
|
||||
from core.locking import DeploymentLock
|
||||
|
||||
|
||||
class RollbackArchive:
|
||||
|
||||
def __init__(self, *, planner, directory, health_probe):
|
||||
require(
|
||||
callable(health_probe),
|
||||
"Health verification is required",
|
||||
)
|
||||
|
||||
self.planner = planner
|
||||
self.journal = planner.journal
|
||||
self.releases = planner.releases
|
||||
self.health_probe = health_probe
|
||||
|
||||
self.source = ApprovalStore(self.journal.directory)
|
||||
self.destination = ApprovalStore(directory)
|
||||
|
||||
require(
|
||||
self.source.directory != self.destination.directory,
|
||||
"Archive directory must be separate",
|
||||
)
|
||||
|
||||
def path(self, identifier):
|
||||
return self.destination.path(
|
||||
identifier,
|
||||
".rollback-archive.json",
|
||||
)
|
||||
|
||||
def read_record(self, suffix, identifier):
|
||||
record = self.source.read(
|
||||
self.source.path(identifier, suffix)
|
||||
)
|
||||
|
||||
require(
|
||||
isinstance(record, dict)
|
||||
and type(record.get("format_version")) is int
|
||||
and record["format_version"] == 1
|
||||
and record.get("checksum") == digest(record),
|
||||
"Invalid rollback evidence",
|
||||
)
|
||||
|
||||
return record
|
||||
|
||||
def read_chain(self, transaction):
|
||||
identifier = transaction["transaction_id"]
|
||||
|
||||
intent = self.read_record(
|
||||
".rollback-intent.json",
|
||||
identifier,
|
||||
)
|
||||
|
||||
result = self.read_record(
|
||||
".rollback-result.json",
|
||||
identifier,
|
||||
)
|
||||
|
||||
require(
|
||||
transaction["phase"] == "FAILED"
|
||||
and intent["status"] == "ROLLBACK_INTENT"
|
||||
and result["status"] == "ROLLED_BACK",
|
||||
"Completed failed-transaction rollback required",
|
||||
)
|
||||
|
||||
phases = {
|
||||
event["phase"]
|
||||
for event in transaction["history"]
|
||||
}
|
||||
|
||||
require(
|
||||
{"BACKED_UP", "QUIESCED", "ACTIVATING"} <= phases,
|
||||
"Incomplete deployment transaction history",
|
||||
)
|
||||
|
||||
for record in (intent, result):
|
||||
require(
|
||||
record["transaction_id"] == identifier
|
||||
and record["site"] == transaction["site"],
|
||||
"Rollback identity mismatch",
|
||||
)
|
||||
|
||||
require(
|
||||
intent["transaction_checksum"]
|
||||
== transaction["checksum"]
|
||||
and result["intent_checksum"]
|
||||
== intent["checksum"]
|
||||
and result["plan_fingerprint"]
|
||||
== intent["plan_fingerprint"],
|
||||
"Rollback evidence chain mismatch",
|
||||
)
|
||||
|
||||
require(
|
||||
isinstance(intent["plan_fingerprint"], str)
|
||||
and re.fullmatch(
|
||||
r"[a-f0-9]{64}",
|
||||
intent["plan_fingerprint"],
|
||||
) is not None,
|
||||
"Invalid rollback plan fingerprint",
|
||||
)
|
||||
|
||||
require(
|
||||
intent["source"] == transaction["candidate"]
|
||||
and intent["target"] == transaction["previous"]
|
||||
and result["previous_active_release"]
|
||||
== transaction["candidate"]
|
||||
and result["active_release"]
|
||||
== transaction["previous"]
|
||||
and result["health_verified"] is True
|
||||
and result["database_restored"] is False,
|
||||
"Rollback result mismatch",
|
||||
)
|
||||
|
||||
evidence = self.planner.backup_evidence.load(
|
||||
identifier
|
||||
)
|
||||
|
||||
require(
|
||||
evidence["backup"]["backup_id"]
|
||||
== intent["backup_id"]
|
||||
and evidence["backup"]["sha256"]
|
||||
== intent["backup_sha256"],
|
||||
"Rollback backup evidence mismatch",
|
||||
)
|
||||
|
||||
return intent, result, evidence
|
||||
|
||||
def load(self, identifier):
|
||||
try:
|
||||
record = self.destination.read(
|
||||
self.path(identifier)
|
||||
)
|
||||
|
||||
require(
|
||||
isinstance(record, dict)
|
||||
and record.get("status") == "ARCHIVED"
|
||||
and record.get("site") == self.planner.site
|
||||
and record.get("database_restored") is False
|
||||
and record.get("checksum") == digest(record),
|
||||
"Invalid rollback archive",
|
||||
)
|
||||
|
||||
transaction = record["transaction"]
|
||||
|
||||
self.journal.validate(transaction)
|
||||
|
||||
require(
|
||||
transaction["transaction_id"] == identifier
|
||||
and transaction["site"] == self.planner.site,
|
||||
"Archived transaction identity mismatch",
|
||||
)
|
||||
|
||||
intent, result, evidence = self.read_chain(
|
||||
transaction
|
||||
)
|
||||
|
||||
require(
|
||||
record["rollback_intent"] == intent
|
||||
and record["rollback_result"] == result
|
||||
and record["backup_evidence"] == evidence,
|
||||
"Archived evidence mismatch",
|
||||
)
|
||||
|
||||
return record
|
||||
|
||||
except ArchiveError:
|
||||
raise
|
||||
|
||||
except Exception:
|
||||
raise ArchiveError(
|
||||
"Rollback archive validation failed"
|
||||
) from None
|
||||
|
||||
def _plan(self):
|
||||
self.destination.validate_directory()
|
||||
|
||||
transaction = self.journal.load()
|
||||
|
||||
require(
|
||||
transaction is not None
|
||||
and transaction["phase"] == "FAILED"
|
||||
and transaction["site"] == self.planner.site,
|
||||
"Failed deployment transaction required",
|
||||
)
|
||||
|
||||
identifier = transaction["transaction_id"]
|
||||
|
||||
require(
|
||||
not os.path.lexists(self.path(identifier)),
|
||||
"Existing archive requires inspection",
|
||||
)
|
||||
|
||||
intent, result, evidence = self.read_chain(
|
||||
transaction
|
||||
)
|
||||
|
||||
previous = transaction["previous"]
|
||||
candidate = transaction["candidate"]
|
||||
|
||||
require(
|
||||
self.releases.current() == previous,
|
||||
"Previous release is not active",
|
||||
)
|
||||
|
||||
old = self.planner.provenance.verify(
|
||||
self.releases.validate(previous)
|
||||
)
|
||||
|
||||
new = self.planner.provenance.verify(
|
||||
self.releases.validate(candidate)
|
||||
)
|
||||
|
||||
validate_provenance(old)
|
||||
validate_provenance(new)
|
||||
|
||||
require(
|
||||
old["revision"] == transaction["previous_revision"]
|
||||
and old["fingerprint"]
|
||||
== transaction["previous_provenance"]
|
||||
and new["revision"] == transaction["revision"]
|
||||
and new["fingerprint"] == transaction["provenance"],
|
||||
"Release provenance changed",
|
||||
)
|
||||
|
||||
require_compatible(new, old)
|
||||
|
||||
backup = evidence["backup"]
|
||||
|
||||
manifest = self.planner.backup_verify(
|
||||
backup["backup_id"]
|
||||
)
|
||||
|
||||
require(
|
||||
isinstance(manifest, dict)
|
||||
and FIELDS <= set(manifest)
|
||||
and {
|
||||
field: manifest[field]
|
||||
for field in FIELDS
|
||||
} == backup,
|
||||
"Backup verification failed",
|
||||
)
|
||||
|
||||
require(
|
||||
self.planner.runtime_check() is True,
|
||||
"Database runtime verification failed",
|
||||
)
|
||||
|
||||
health = self.health_probe(previous)
|
||||
|
||||
require(
|
||||
isinstance(health, dict)
|
||||
and health.get("healthy") is True
|
||||
and health.get("release") == previous,
|
||||
"Rolled-back application is unhealthy",
|
||||
)
|
||||
|
||||
marker = (
|
||||
self.releases.release_path(candidate)
|
||||
/ "BAD_RELEASE"
|
||||
)
|
||||
|
||||
require(
|
||||
not os.path.lexists(marker),
|
||||
"Existing failed-release marker requires review",
|
||||
)
|
||||
|
||||
require(
|
||||
self.journal.load() == transaction
|
||||
and self.releases.current() == previous
|
||||
and self.read_chain(transaction)
|
||||
== (intent, result, evidence),
|
||||
"Rollback state changed",
|
||||
)
|
||||
|
||||
plan = {
|
||||
"format_version": 1,
|
||||
"status": "ARCHIVE_READY",
|
||||
"site": transaction["site"],
|
||||
"transaction_id": identifier,
|
||||
"transaction_checksum": transaction["checksum"],
|
||||
"intent_checksum": intent["checksum"],
|
||||
"result_checksum": result["checksum"],
|
||||
"backup_evidence_checksum": evidence["checksum"],
|
||||
"active_release": previous,
|
||||
"failed_release": candidate,
|
||||
"confirmation": "ARCHIVE-ROLLBACK-" + identifier,
|
||||
}
|
||||
|
||||
plan["fingerprint"] = canonical_hash(plan)
|
||||
|
||||
return plan
|
||||
|
||||
def plan(self):
|
||||
with DeploymentLock(self.planner.lock_path):
|
||||
try:
|
||||
return self._plan()
|
||||
|
||||
except ArchiveError:
|
||||
raise
|
||||
|
||||
except Exception:
|
||||
raise ArchiveError(
|
||||
"Rollback archival preflight failed"
|
||||
) from None
|
||||
|
||||
def execute(self, *, confirmation, fingerprint):
|
||||
with DeploymentLock(self.planner.lock_path):
|
||||
with DeploymentLock(self.journal.lock_path):
|
||||
try:
|
||||
return self._execute(
|
||||
confirmation,
|
||||
fingerprint,
|
||||
)
|
||||
|
||||
except ArchiveError:
|
||||
raise
|
||||
|
||||
except Exception:
|
||||
raise ArchiveError(
|
||||
"Rollback archival interrupted; "
|
||||
"inspect preserved evidence"
|
||||
) from None
|
||||
|
||||
def _execute(self, confirmation, fingerprint):
|
||||
plan = self._plan()
|
||||
|
||||
require(
|
||||
confirmation == plan["confirmation"]
|
||||
and fingerprint == plan["fingerprint"],
|
||||
"Rollback archival confirmation mismatch",
|
||||
)
|
||||
|
||||
transaction = self.journal.load()
|
||||
identifier = plan["transaction_id"]
|
||||
|
||||
require(
|
||||
transaction["checksum"]
|
||||
== plan["transaction_checksum"],
|
||||
"Transaction changed",
|
||||
)
|
||||
|
||||
intent, result, evidence = self.read_chain(
|
||||
transaction
|
||||
)
|
||||
|
||||
require(
|
||||
intent["checksum"] == plan["intent_checksum"]
|
||||
and result["checksum"] == plan["result_checksum"]
|
||||
and evidence["checksum"]
|
||||
== plan["backup_evidence_checksum"],
|
||||
"Rollback evidence changed",
|
||||
)
|
||||
|
||||
record = {
|
||||
"format_version": 1,
|
||||
"status": "ARCHIVED",
|
||||
"site": plan["site"],
|
||||
"transaction": transaction,
|
||||
"rollback_intent": intent,
|
||||
"rollback_result": result,
|
||||
"backup_evidence": evidence,
|
||||
"plan_fingerprint": fingerprint,
|
||||
"database_restored": False,
|
||||
"archived_at": datetime.now(
|
||||
timezone.utc
|
||||
).isoformat(),
|
||||
}
|
||||
|
||||
record["checksum"] = digest(record)
|
||||
|
||||
# Preserve all transaction evidence before modifying
|
||||
# the failed release or retiring the active journal.
|
||||
|
||||
self.destination.publish(
|
||||
self.path(identifier),
|
||||
record,
|
||||
)
|
||||
|
||||
require(
|
||||
self.load(identifier) == record,
|
||||
"Archive readback failed",
|
||||
)
|
||||
|
||||
require(
|
||||
self.releases.current()
|
||||
== plan["active_release"]
|
||||
and self.journal.load() == transaction
|
||||
and self.planner.runtime_check() is True,
|
||||
"Runtime state changed before retirement",
|
||||
)
|
||||
|
||||
candidate = self.releases.validate(
|
||||
plan["failed_release"]
|
||||
)
|
||||
|
||||
marker = candidate / "BAD_RELEASE"
|
||||
|
||||
fd = os.open(
|
||||
marker,
|
||||
os.O_WRONLY
|
||||
| os.O_CREAT
|
||||
| os.O_EXCL
|
||||
| os.O_NOFOLLOW
|
||||
| os.O_CLOEXEC,
|
||||
0o600,
|
||||
)
|
||||
|
||||
with os.fdopen(fd, "w") as handle:
|
||||
handle.write(
|
||||
identifier + "\n"
|
||||
+ record["checksum"] + "\n"
|
||||
)
|
||||
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
|
||||
sync_directory(candidate)
|
||||
|
||||
require(
|
||||
self.releases.current()
|
||||
== plan["active_release"]
|
||||
and self.journal.load() == transaction,
|
||||
"Deployment state changed during retirement",
|
||||
)
|
||||
|
||||
# Only retire the journal once the durable archive
|
||||
# and failed-release marker are present.
|
||||
|
||||
self.journal.path.unlink()
|
||||
|
||||
sync_directory(self.journal.directory)
|
||||
|
||||
require(
|
||||
self.journal.load() is None,
|
||||
"Journal retirement failed",
|
||||
)
|
||||
|
||||
return record
|
||||
@@ -0,0 +1,182 @@
|
||||
"""Controlled Docker Compose application lifecycle.
|
||||
|
||||
The command runner must be supplied by the caller.
|
||||
This module does not execute subprocesses directly.
|
||||
"""
|
||||
|
||||
from pathlib import PurePosixPath
|
||||
|
||||
from core.configuration import (
|
||||
ConfigurationError,
|
||||
validate_config,
|
||||
)
|
||||
|
||||
|
||||
class ServiceError(RuntimeError):
|
||||
"""Application service lifecycle operation failed."""
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
|
||||
if not condition:
|
||||
raise ServiceError(message)
|
||||
|
||||
|
||||
class ServiceLifecycle:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config,
|
||||
runner,
|
||||
stop_timeout=90,
|
||||
):
|
||||
|
||||
require(
|
||||
callable(runner),
|
||||
"A command runner is required",
|
||||
)
|
||||
|
||||
require(
|
||||
type(stop_timeout) is int
|
||||
and 1 <= stop_timeout <= 300,
|
||||
"Invalid graceful shutdown timeout",
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
validated = validate_config(config)
|
||||
|
||||
except ConfigurationError:
|
||||
|
||||
raise ServiceError(
|
||||
"Invalid service configuration"
|
||||
) from None
|
||||
|
||||
docker = validated["docker"]
|
||||
|
||||
root = PurePosixPath(
|
||||
validated["site"]["root"]
|
||||
)
|
||||
|
||||
self._prefix = (
|
||||
"docker",
|
||||
"compose",
|
||||
"--project-name",
|
||||
docker["project"],
|
||||
"--project-directory",
|
||||
str(root),
|
||||
"--file",
|
||||
str(root / "compose.yaml"),
|
||||
)
|
||||
|
||||
self._php = docker["php_service"]
|
||||
self._web = docker["web_service"]
|
||||
self._queue = docker["queue_service"]
|
||||
self._scheduler = docker["scheduler_service"]
|
||||
|
||||
self._runner = runner
|
||||
self._stop_timeout = stop_timeout
|
||||
|
||||
def _execute(self, operation, args, timeout):
|
||||
|
||||
command = (
|
||||
*self._prefix,
|
||||
*args,
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
result = self._runner(
|
||||
command,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
except Exception:
|
||||
|
||||
raise ServiceError(
|
||||
f"Service operation failed: {operation}"
|
||||
) from None
|
||||
|
||||
require(
|
||||
type(result) is int and result == 0,
|
||||
f"Service operation failed: {operation}",
|
||||
)
|
||||
|
||||
def quiesce(self):
|
||||
|
||||
self._execute(
|
||||
"quiesce workers",
|
||||
(
|
||||
"stop",
|
||||
"--timeout",
|
||||
str(self._stop_timeout),
|
||||
self._queue,
|
||||
self._scheduler,
|
||||
),
|
||||
timeout=self._stop_timeout + 30,
|
||||
)
|
||||
|
||||
def restart_php(self):
|
||||
|
||||
self._execute(
|
||||
"restart PHP",
|
||||
(
|
||||
"restart",
|
||||
"--timeout",
|
||||
str(self._stop_timeout),
|
||||
self._php,
|
||||
),
|
||||
timeout=self._stop_timeout + 30,
|
||||
)
|
||||
|
||||
def validate_nginx(self):
|
||||
|
||||
self._execute(
|
||||
"validate nginx",
|
||||
(
|
||||
"exec",
|
||||
"-T",
|
||||
"--interactive=false",
|
||||
self._web,
|
||||
"nginx",
|
||||
"-t",
|
||||
),
|
||||
timeout=30,
|
||||
)
|
||||
|
||||
def reload_nginx(self):
|
||||
|
||||
self.validate_nginx()
|
||||
|
||||
self._execute(
|
||||
"reload nginx",
|
||||
(
|
||||
"exec",
|
||||
"-T",
|
||||
"--interactive=false",
|
||||
self._web,
|
||||
"nginx",
|
||||
"-s",
|
||||
"reload",
|
||||
),
|
||||
timeout=30,
|
||||
)
|
||||
|
||||
def refresh(self):
|
||||
|
||||
self.restart_php()
|
||||
self.reload_nginx()
|
||||
|
||||
def resume(self):
|
||||
|
||||
self._execute(
|
||||
"resume workers",
|
||||
(
|
||||
"up",
|
||||
"-d",
|
||||
"--no-deps",
|
||||
self._queue,
|
||||
self._scheduler,
|
||||
),
|
||||
timeout=120,
|
||||
)
|
||||
@@ -0,0 +1,186 @@
|
||||
"""Static ABSDEV site isolation and registry validation.
|
||||
|
||||
This module does not inspect or modify live infrastructure.
|
||||
"""
|
||||
|
||||
from core.configuration import validate_config
|
||||
from core.compatibility import canonical_hash
|
||||
|
||||
|
||||
class SitePolicyError(RuntimeError):
|
||||
"""Unsafe site configuration or resource conflict."""
|
||||
|
||||
|
||||
SITE_BASE = "/opt/laravel-sites"
|
||||
|
||||
RESERVED_USERS = {
|
||||
"root",
|
||||
"postgres",
|
||||
"mysql",
|
||||
"admin",
|
||||
"administrator",
|
||||
"mariadb.sys",
|
||||
"mysql.sys",
|
||||
"mysql.session",
|
||||
"mysql.infoschema",
|
||||
}
|
||||
|
||||
RESERVED_DATABASES = {
|
||||
"mysql",
|
||||
"postgres",
|
||||
"template0",
|
||||
"template1",
|
||||
"information_schema",
|
||||
"performance_schema",
|
||||
"sys",
|
||||
}
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
raise SitePolicyError(message)
|
||||
|
||||
|
||||
def validated(config):
|
||||
try:
|
||||
return validate_config(config)
|
||||
except Exception:
|
||||
raise SitePolicyError(
|
||||
"Invalid site configuration"
|
||||
) from None
|
||||
|
||||
|
||||
def validate_site(config):
|
||||
config = validated(config)
|
||||
|
||||
site = config["site"]
|
||||
docker = config["docker"]
|
||||
database = config["database"]
|
||||
|
||||
identifier = site["identifier"]
|
||||
|
||||
require(
|
||||
site["root"] == SITE_BASE + "/" + identifier,
|
||||
"Site root must match the trusted site directory",
|
||||
)
|
||||
|
||||
require(
|
||||
docker["project"] == "site-" + identifier,
|
||||
"Docker project must match site identity",
|
||||
)
|
||||
|
||||
require(
|
||||
1024 <= site["origin_port"] <= 65535,
|
||||
"Privileged or invalid origin port",
|
||||
)
|
||||
|
||||
require(
|
||||
database["username"].lower() not in RESERVED_USERS,
|
||||
"Reserved database username",
|
||||
)
|
||||
|
||||
require(
|
||||
database["name"].lower() not in RESERVED_DATABASES,
|
||||
"Reserved database name",
|
||||
)
|
||||
|
||||
services = [
|
||||
docker["php_service"],
|
||||
docker["web_service"],
|
||||
docker["queue_service"],
|
||||
docker["scheduler_service"],
|
||||
]
|
||||
|
||||
require(
|
||||
len(set(services)) == len(services),
|
||||
"Application service names must be distinct",
|
||||
)
|
||||
|
||||
require(
|
||||
docker["backend_network"] != docker["proxy_network"],
|
||||
"Backend and proxy networks must be distinct",
|
||||
)
|
||||
|
||||
result = {
|
||||
"format_version": 1,
|
||||
"status": "VALID",
|
||||
"site": identifier,
|
||||
"configuration_fingerprint": canonical_hash(config),
|
||||
"static_policy_verified": True,
|
||||
"runtime_verified": False,
|
||||
"execution_permitted": False,
|
||||
}
|
||||
|
||||
result["fingerprint"] = canonical_hash(result)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def validate_registry(configurations):
|
||||
require(
|
||||
isinstance(configurations, list)
|
||||
and 1 <= len(configurations) <= 10000,
|
||||
"Invalid site registry",
|
||||
)
|
||||
|
||||
resources = {
|
||||
"identifier": set(),
|
||||
"domain": set(),
|
||||
"root": set(),
|
||||
"origin_port": set(),
|
||||
"docker_project": set(),
|
||||
"database": set(),
|
||||
"database_username": set(),
|
||||
}
|
||||
|
||||
reports = []
|
||||
|
||||
for item in configurations:
|
||||
config = validated(item)
|
||||
|
||||
report = validate_site(config)
|
||||
|
||||
site = config["site"]
|
||||
docker = config["docker"]
|
||||
database = config["database"]
|
||||
|
||||
# Conservatively reject duplicate database names
|
||||
# and users across the registry, even when the
|
||||
# database containers differ.
|
||||
|
||||
keys = {
|
||||
"identifier": site["identifier"],
|
||||
"domain": site["domain"].lower(),
|
||||
"root": site["root"],
|
||||
"origin_port": site["origin_port"],
|
||||
"docker_project": docker["project"].lower(),
|
||||
"database": database["name"].lower(),
|
||||
"database_username": database["username"].lower(),
|
||||
}
|
||||
|
||||
for category, value in keys.items():
|
||||
require(
|
||||
value not in resources[category],
|
||||
f"Duplicate site resource: {category}",
|
||||
)
|
||||
|
||||
resources[category].add(value)
|
||||
|
||||
reports.append(report)
|
||||
|
||||
result = {
|
||||
"format_version": 1,
|
||||
"status": "VALID",
|
||||
"site_count": len(reports),
|
||||
"sites": sorted(
|
||||
reports,
|
||||
key=lambda item: item["site"],
|
||||
),
|
||||
"registry_conflicts_checked": True,
|
||||
"runtime_verified": False,
|
||||
"execution_permitted": False,
|
||||
}
|
||||
|
||||
result["fingerprint"] = canonical_hash(result)
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,491 @@
|
||||
"""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)
|
||||
Reference in New Issue
Block a user