Files
absdev-deployment/core/compatibility.py
T

223 lines
5.3 KiB
Python

"""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, *, modular=False):
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")
or (
modular and len(path.parts) >= 5 and (
(path.parts[0] == "Modules"
and path.parts[2:4] == ("Database", "Migrations"))
or (path.parts[0] == "modules"
and path.parts[2:4] == ("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):
fields = {"format_version", "revision", "migrations", "dependencies", "fingerprint"}
require(isinstance(data, dict), "Invalid provenance evidence structure")
version = data.get("format_version")
require(type(version) is int and version in (1, 2), "Unsupported provenance format")
if version == 2:
fields.add("source_tree")
require(valid_hash(data.get("source_tree"), 64), "Invalid source tree checksum")
require(set(data) == fields, "Invalid provenance evidence structure")
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, modular=version == 2)
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