Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fec0778bfd | ||
|
|
b0495d80f1 | ||
|
|
5d3ea0d536 | ||
|
|
89418ea21a | ||
|
|
2719378f67 |
+26
-6
@@ -22,7 +22,8 @@ from core.approval import (
|
||||
ApprovalError,
|
||||
)
|
||||
|
||||
from core.rehearsal import approval_context
|
||||
from core.rehearsal import BASE_FIELDS, RehearsalError
|
||||
from core.trusted_rehearsal import TrustedRehearsal
|
||||
from core.compatibility import canonical_hash
|
||||
from core.locking import DeploymentLock
|
||||
from core.operator_approval import OperatorApprovalPolicy
|
||||
@@ -58,9 +59,10 @@ class ApprovalStore:
|
||||
|
||||
MAX_BYTES = 4 * 1024 * 1024
|
||||
|
||||
def __init__(self, directory, *, operator_policy=None):
|
||||
def __init__(self, directory, *, operator_policy=None, trusted_rehearsal=None):
|
||||
|
||||
self.operator_policy = operator_policy
|
||||
self.trusted_rehearsal = trusted_rehearsal
|
||||
self.directory = Path(directory).absolute()
|
||||
self.validate_directory()
|
||||
|
||||
@@ -307,9 +309,14 @@ class ApprovalStore:
|
||||
return record
|
||||
|
||||
def require_operator_policy(self):
|
||||
require(isinstance(self.operator_policy, OperatorApprovalPolicy),
|
||||
require(callable(self.operator_policy), "Trusted migration operator policy loader required")
|
||||
try:
|
||||
policy = self.operator_policy()
|
||||
except Exception:
|
||||
raise ApprovalStoreError("Unable to verify current migration operator authority") from None
|
||||
require(isinstance(policy, OperatorApprovalPolicy),
|
||||
"Trusted migration operator policy required")
|
||||
return self.operator_policy
|
||||
return policy
|
||||
|
||||
def verify_execution(self, approval, context, *, confirmation, now):
|
||||
verify_approval(approval, context, confirmation=confirmation, now=now)
|
||||
@@ -318,11 +325,20 @@ class ApprovalStore:
|
||||
except ApprovalError as error:
|
||||
raise ApprovalStoreError(str(error)) from error
|
||||
|
||||
def rehearsal_context(self, rehearsal, base_context, *, now):
|
||||
require(isinstance(self.trusted_rehearsal, TrustedRehearsal),
|
||||
"Trusted rehearsal verifier required")
|
||||
try:
|
||||
return self.trusted_rehearsal.approval_context(rehearsal, base_context, now=now)
|
||||
except RehearsalError as error:
|
||||
raise ApprovalStoreError(str(error)) from error
|
||||
|
||||
def save(
|
||||
self,
|
||||
approval,
|
||||
context,
|
||||
*,
|
||||
rehearsal=None,
|
||||
confirmation,
|
||||
now,
|
||||
):
|
||||
@@ -360,7 +376,11 @@ class ApprovalStore:
|
||||
)
|
||||
|
||||
try:
|
||||
record = self.require_operator_policy().issue(record, now)
|
||||
policy = self.require_operator_policy()
|
||||
base = {name: context[name] for name in BASE_FIELDS}
|
||||
require(self.rehearsal_context(rehearsal, base, now=now) == context,
|
||||
"Approval does not bind the trusted rehearsal")
|
||||
record = policy.issue(record, now)
|
||||
except ApprovalError as error:
|
||||
raise ApprovalStoreError(str(error)) from error
|
||||
|
||||
@@ -399,7 +419,7 @@ class ApprovalStore:
|
||||
|
||||
try:
|
||||
|
||||
context = approval_context(
|
||||
context = self.rehearsal_context(
|
||||
rehearsal,
|
||||
base_context,
|
||||
now=now,
|
||||
|
||||
+19
-11
@@ -56,6 +56,18 @@ def provenance_fingerprint(data):
|
||||
})
|
||||
|
||||
|
||||
def is_laravel_migration_path(value):
|
||||
"""Match files Laravel discovers in supported registered directories."""
|
||||
path = PurePosixPath(value)
|
||||
parts = path.parts
|
||||
application = len(parts) == 3 and parts[:2] == ("database", "migrations")
|
||||
module = (
|
||||
len(parts) == 5 and parts[0].lower() == "modules"
|
||||
and tuple(part.lower() for part in parts[2:4]) == ("database", "migrations")
|
||||
)
|
||||
return (application or module) and "_" in path.stem and path.suffix == ".php"
|
||||
|
||||
|
||||
def validate_migration_path(value, *, modular=False):
|
||||
|
||||
require(
|
||||
@@ -70,17 +82,8 @@ def validate_migration_path(value, *, modular=False):
|
||||
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 (is_laravel_migration_path(value) if modular
|
||||
else path.parts[:2] == ("database", "migrations"))
|
||||
and path.suffix == ".php"
|
||||
and all(
|
||||
re.fullmatch(
|
||||
@@ -119,9 +122,14 @@ def validate_provenance(data):
|
||||
"Invalid dependency inventory",
|
||||
)
|
||||
|
||||
basenames = set()
|
||||
for name, digest in data["migrations"].items():
|
||||
|
||||
validate_migration_path(name, modular=version == 2)
|
||||
if version == 2:
|
||||
basename = PurePosixPath(name).stem
|
||||
require(basename not in basenames, "Duplicate migration basename")
|
||||
basenames.add(basename)
|
||||
|
||||
require(
|
||||
valid_hash(digest, 64),
|
||||
|
||||
@@ -10,7 +10,7 @@ from core.transactions import TransactionJournal
|
||||
|
||||
|
||||
class SiteOperations:
|
||||
def __init__(self, root, *, operator_policy=None):
|
||||
def __init__(self, root, *, operator_policy=None, trusted_rehearsal=None):
|
||||
root = Path(root)
|
||||
if root.resolve() != root:
|
||||
raise ValueError("Site runtime directory must be canonical")
|
||||
@@ -21,7 +21,8 @@ class SiteOperations:
|
||||
self.lock_path = state / ".deployment.lock"
|
||||
self.journal = TransactionJournal(state)
|
||||
self.backup_evidence = BackupEvidence(state)
|
||||
self.approvals = ApprovalStore(approvals, operator_policy=operator_policy)
|
||||
self.approvals = ApprovalStore(approvals, operator_policy=operator_policy,
|
||||
trusted_rehearsal=trusted_rehearsal)
|
||||
self.journal.bind_migration_guard(self.approvals)
|
||||
self.guard = OperationGuard(self.approvals)
|
||||
|
||||
|
||||
@@ -5,7 +5,9 @@ import os
|
||||
import stat
|
||||
from pathlib import Path
|
||||
|
||||
from core.compatibility import canonical_hash, provenance_fingerprint, validate_provenance
|
||||
from core.compatibility import (
|
||||
canonical_hash, is_laravel_migration_path, provenance_fingerprint, validate_provenance,
|
||||
)
|
||||
from core.provenance import ProvenanceVerifier, require
|
||||
|
||||
|
||||
@@ -58,13 +60,10 @@ class CompleteProvenance(ProvenanceVerifier):
|
||||
expected = {**tracked, **self.generated, "REVISION": marker}
|
||||
require(inventory(release) == expected,
|
||||
"Full release tree differs from authorised source or generated artifacts")
|
||||
for name, (digest, _) in tracked.items():
|
||||
parts = Path(name).parts
|
||||
if (len(parts) >= 5 and name.endswith(".php") and
|
||||
(parts[0], parts[2], parts[3]) in (
|
||||
("Modules", "Database", "Migrations"), ("modules", "database", "migrations")
|
||||
)):
|
||||
evidence["migrations"][name] = digest
|
||||
evidence["migrations"] = {
|
||||
name: digest for name, (digest, _) in tracked.items()
|
||||
if is_laravel_migration_path(name)
|
||||
}
|
||||
evidence.update(format_version=2, source_tree=canonical_hash(expected))
|
||||
evidence["fingerprint"] = provenance_fingerprint(evidence)
|
||||
validate_provenance(evidence)
|
||||
|
||||
+1
-2
@@ -10,7 +10,6 @@ import re
|
||||
from pathlib import Path
|
||||
|
||||
from core.approval import timestamp
|
||||
from core.rehearsal import approval_context
|
||||
from core.compatibility import canonical_hash
|
||||
from core.locking import DeploymentLock
|
||||
from core.operation_guard import OperationGuard
|
||||
@@ -161,7 +160,7 @@ class MigrationCoordinator:
|
||||
base = copy.deepcopy(self.context_probe())
|
||||
current_time = timestamp(self.clock())
|
||||
|
||||
context = approval_context(
|
||||
context = self.store.rehearsal_context(
|
||||
rehearsal, base, now=current_time
|
||||
)
|
||||
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
"""Local operator identity and scoped migration approval policy."""
|
||||
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from os import geteuid
|
||||
from pathlib import Path
|
||||
|
||||
from core.approval import (
|
||||
ApprovalError,
|
||||
@@ -82,3 +86,46 @@ class OperatorApprovalPolicy:
|
||||
def verify_execution(self, approval, now):
|
||||
self.verify_seal(approval)
|
||||
self.authorise(approval, "execute", now)
|
||||
|
||||
|
||||
class FileOperatorAuthority:
|
||||
"""Load a fresh, atomic authority snapshot from a trusted local provisioner."""
|
||||
|
||||
MAX_BYTES = 65536
|
||||
|
||||
def __init__(self, path, *, group):
|
||||
self.path = Path(path)
|
||||
self.group = group
|
||||
require(self.path.is_absolute() and self.path.parent.resolve() == self.path.parent
|
||||
and type(group) is int and group > 0, "Invalid operator authority binding")
|
||||
|
||||
def __call__(self):
|
||||
# The parent and its ancestors are trusted, and the final entry cannot
|
||||
# be replaced by the reader or resolved through a symbolic link.
|
||||
directory = os.open(self.path.parent, os.O_RDONLY | os.O_DIRECTORY
|
||||
| os.O_NOFOLLOW | os.O_CLOEXEC)
|
||||
try:
|
||||
info = os.fstat(directory)
|
||||
require(info.st_uid == 0 and info.st_gid == self.group
|
||||
and stat.S_IMODE(info.st_mode) == 0o750,
|
||||
"Unsafe operator authority directory")
|
||||
descriptor = os.open(self.path.name, os.O_RDONLY | os.O_NOFOLLOW
|
||||
| os.O_NONBLOCK | os.O_CLOEXEC, dir_fd=directory)
|
||||
with os.fdopen(descriptor, "rb") as stream:
|
||||
info = os.fstat(stream.fileno())
|
||||
require(stat.S_ISREG(info.st_mode) and info.st_uid == 0
|
||||
and info.st_gid == self.group and info.st_nlink == 1
|
||||
and stat.S_IMODE(info.st_mode) == 0o440,
|
||||
"Unsafe operator authority file")
|
||||
data = stream.read(self.MAX_BYTES + 1)
|
||||
finally:
|
||||
os.close(directory)
|
||||
require(0 < len(data) <= self.MAX_BYTES, "Invalid operator authority size")
|
||||
snapshot = json.loads(data)
|
||||
require(isinstance(snapshot, dict) and set(snapshot) == {"grants", "sealing_key"}
|
||||
and isinstance(snapshot["grants"], list), "Invalid operator authority snapshot")
|
||||
grants = [
|
||||
OperatorGrant(**dict(grant, expires_at=datetime.fromisoformat(grant["expires_at"])))
|
||||
for grant in snapshot["grants"]
|
||||
]
|
||||
return OperatorApprovalPolicy(grants, sealing_key=bytes.fromhex(snapshot["sealing_key"]))
|
||||
|
||||
+21
-2
@@ -4,6 +4,7 @@ The command runner must be supplied by the caller.
|
||||
This module does not execute subprocesses directly.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import tempfile
|
||||
@@ -37,6 +38,7 @@ class ServiceLifecycle:
|
||||
stop_timeout=90,
|
||||
*,
|
||||
site_secrets=None,
|
||||
topology_runner=None,
|
||||
):
|
||||
|
||||
require(
|
||||
@@ -86,6 +88,8 @@ class ServiceLifecycle:
|
||||
self._queue = docker["queue_service"]
|
||||
self._scheduler = docker["scheduler_service"]
|
||||
|
||||
self._backend_network = docker["backend_network"]
|
||||
self._topology_runner = topology_runner
|
||||
self._runner = runner
|
||||
self._stop_timeout = stop_timeout
|
||||
|
||||
@@ -114,6 +118,18 @@ class ServiceLifecycle:
|
||||
f"Service operation failed: {operation}",
|
||||
)
|
||||
|
||||
def _require_project_backend(self):
|
||||
require(callable(self._topology_runner), "Trusted Compose topology runner required")
|
||||
command = (*self._prefix, "config", "--format", "json")
|
||||
try:
|
||||
model = json.loads(self._topology_runner(command, timeout=30))
|
||||
backend = model["networks"][self._backend_network]
|
||||
except Exception:
|
||||
raise ServiceError("Unable to verify Compose backend network") from None
|
||||
require(isinstance(backend, dict), "Invalid Compose backend network")
|
||||
require(backend.get("external", False) is False,
|
||||
"External Compose backend networks are prohibited")
|
||||
|
||||
def quiesce(self):
|
||||
|
||||
self._execute(
|
||||
@@ -130,6 +146,7 @@ class ServiceLifecycle:
|
||||
|
||||
def restart_php(self):
|
||||
|
||||
self._require_project_backend()
|
||||
self._execute(
|
||||
"restart PHP",
|
||||
(
|
||||
@@ -181,6 +198,7 @@ class ServiceLifecycle:
|
||||
|
||||
def resume(self):
|
||||
|
||||
self._require_project_backend()
|
||||
self._execute(
|
||||
"resume workers",
|
||||
(
|
||||
@@ -203,8 +221,9 @@ class ContainedServiceLifecycle(ServiceLifecycle):
|
||||
"""
|
||||
|
||||
def __init__(self, config, runner, *, gate_directory, ingress_sealed,
|
||||
worker_running, stop_timeout=90, site_secrets=None):
|
||||
super().__init__(config, runner, stop_timeout, site_secrets=site_secrets)
|
||||
worker_running, stop_timeout=90, site_secrets=None, topology_runner=None):
|
||||
super().__init__(config, runner, stop_timeout, site_secrets=site_secrets,
|
||||
topology_runner=topology_runner)
|
||||
require(callable(ingress_sealed) and callable(worker_running),
|
||||
"Containment probes are required")
|
||||
self._gate_directory = Path(gate_directory)
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Bind rehearsal results to a configured runner and an independent trust key."""
|
||||
|
||||
import copy
|
||||
import hmac
|
||||
|
||||
from core.rehearsal import (
|
||||
RECORD_FIELDS, approval_context, create_rehearsal, matches, require,
|
||||
validate_base_context,
|
||||
)
|
||||
|
||||
|
||||
class TrustedRehearsal:
|
||||
def __init__(self, runner_id, runner, *, key, clock):
|
||||
require(matches(runner_id, r"[a-zA-Z0-9_.-]{1,128}"), "Invalid rehearsal runner identity")
|
||||
require(callable(runner) and callable(clock), "Trusted rehearsal runner and clock required")
|
||||
require(isinstance(key, bytes) and len(key) >= 32, "Invalid rehearsal trust key")
|
||||
self.runner_id = runner_id
|
||||
self._runner = runner
|
||||
self._key = key
|
||||
self._clock = clock
|
||||
|
||||
def _seal(self, fingerprint):
|
||||
payload = f"absdev:trusted-rehearsal:v1:{self.runner_id}:{fingerprint}".encode("ascii")
|
||||
return hmac.digest(self._key, payload, "sha256").hex()
|
||||
|
||||
def run(self, context):
|
||||
context = copy.deepcopy(context)
|
||||
validate_base_context(context)
|
||||
execution = self._runner(copy.deepcopy(context))
|
||||
record = create_rehearsal(context, execution, completed_at=self._clock())
|
||||
return dict(record, runner_id=self.runner_id, runner_seal=self._seal(record["fingerprint"]))
|
||||
|
||||
def approval_context(self, evidence, context, *, now):
|
||||
require(isinstance(evidence, dict)
|
||||
and set(evidence) == RECORD_FIELDS | {"runner_id", "runner_seal"},
|
||||
"Trusted rehearsal evidence required")
|
||||
require(evidence["runner_id"] == self.runner_id
|
||||
and matches(evidence["runner_seal"], r"[a-f0-9]{64}"),
|
||||
"Invalid rehearsal runner attestation")
|
||||
record = {name: evidence[name] for name in RECORD_FIELDS}
|
||||
approved = approval_context(record, context, now=now)
|
||||
require(hmac.compare_digest(evidence["runner_seal"], self._seal(record["fingerprint"])),
|
||||
"Untrusted rehearsal runner attestation")
|
||||
return approved
|
||||
@@ -1,8 +1,8 @@
|
||||
# Local migration operator authorisation
|
||||
|
||||
The supported development composition accepts an `OperatorApprovalPolicy`
|
||||
through `SiteOperations(operator_policy=...)`. Configure the policy in trusted
|
||||
runtime code with a one-to-one mapping from dedicated OS accounts to operator
|
||||
The supported development composition accepts a policy loader through
|
||||
`SiteOperations(operator_policy=...)`. The loader must return a fresh
|
||||
`OperatorApprovalPolicy` on each call. Configure the policy in trusted runtime code with a one-to-one mapping from dedicated OS accounts to operator
|
||||
principals. The policy authenticates the process's effective UID. The operator's
|
||||
login or service launcher must authenticate access to that account. A shared
|
||||
service account cannot provide individual operator identity.
|
||||
@@ -24,7 +24,20 @@ for audit. Unsealed recovery evidence requires manual review. Recovery evidence
|
||||
verification requires access to the sealing key used for issuance.
|
||||
|
||||
The runtime process, its code, policy, key, clock and state directory are trusted.
|
||||
The policy is constructed from a configuration snapshot. Reload it before
|
||||
further execution when grants are revoked or changed. The approved account
|
||||
|
||||
Use `FileOperatorAuthority(path, group=...)` for a local authority source. Place
|
||||
the root-owned mode 0440 JSON file in a root-owned mode 0750 directory whose
|
||||
group matches the configured reader group, under administrator-controlled
|
||||
ancestors. The JSON object contains `sealing_key` as hex and `grants` as a list
|
||||
of objects with `uid`, `principal`, `operation`, `site`, `revision` and
|
||||
`expires_at` (timezone-aware ISO 8601). Atomically replace the whole file when
|
||||
removing grants or changing the key. The runtime reopens it for each authority
|
||||
check, including consumption under the approval lock. Missing, unreadable,
|
||||
unsafe or malformed state denies the operation. Key rotation invalidates
|
||||
outstanding approvals and puts evidence sealed with the retired key into
|
||||
manual review. Revocation is evaluated at the next authority read and cannot
|
||||
recall an operation that already passed its final consumption check.
|
||||
|
||||
The approved account
|
||||
must never be exposed as a shared application or arbitrary command identity.
|
||||
The inspection CLI remains disabled for production execution.
|
||||
|
||||
@@ -34,3 +34,11 @@ result record the activation and health outcome independently of reopening.
|
||||
|
||||
These controls are available to the trusted runtime composition. The
|
||||
operational production CLI remains disabled.
|
||||
|
||||
Pass a trusted `topology_runner(command, *, timeout)` that returns stdout
|
||||
from a successful Compose command as JSON bytes or text and raises on failure.
|
||||
The runtime resolves the exact project and Compose files with
|
||||
`config --format json` before starting workers or restarting PHP. Missing,
|
||||
unverifiable, or external configured backend networks deny those operations.
|
||||
Keep Compose inputs under trusted control across validation and execution.
|
||||
Stopping workers remains available if topology validation fails.
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# Trusted rehearsal evidence
|
||||
|
||||
Configure `TrustedRehearsal(runner_id, runner, key=..., clock=...)` in trusted
|
||||
runtime code and supply it to `SiteOperations(trusted_rehearsal=...)`.
|
||||
Use a separately managed random key of at least 32 bytes and a stable runner
|
||||
identifier. Only trusted runtime processes may have access to this key.
|
||||
This is a symmetric attestation shared by the runner and approval runtime.
|
||||
Keep it separate from the operator approval sealing key.
|
||||
|
||||
The configured runner receives a copy of the exact rehearsal context. It must
|
||||
verify the candidate inventory, restore the verified backup into an isolated
|
||||
database, run the approved migrations, observe migration history and application
|
||||
checks, and clean up before returning execution evidence. The runner and clock
|
||||
come from trusted composition, and callers cannot supply either per rehearsal.
|
||||
|
||||
Call `run(context)` to obtain evidence, then derive the approval context with
|
||||
`approval_context(evidence, context, now=...)` and pass the same evidence as
|
||||
`rehearsal` when saving the approval and attempting execution. The approval
|
||||
store and migration coordinator independently verify the attestation. The
|
||||
underlying structural rehearsal format remains readable for audit. Unsigned
|
||||
historical evidence must be rerun under the trusted adapter before it can
|
||||
authorise a migration.
|
||||
|
||||
The configured runner and protected key provisioning are deployment inputs.
|
||||
Production execution remains disabled.
|
||||
@@ -1,5 +0,0 @@
|
||||
# ABSDEV-CI live password cutover
|
||||
|
||||
Tested revision 1c3df42a68d75b825993f9e5b9a774e5eeacff4b with disposable MySQL and PostgreSQL containers. The harness mounted the site credential directory defined by the supported Compose override. FileSecretBackend delivered both the initial and replacement credential files. The framework adapters ran fresh connections under the designated non-root UID through CommandRunner.
|
||||
|
||||
Each live server rejected the old password after rotation. The new backend credential restored authentication without recreating the container. Re-delivering the retired file still failed, and restoring the new file succeeded again. The test used synthetic passwords and did not exercise sessions already connected during rotation. All 16 qualification checks and 898 framework tests passed. Disposable containers, volumes and temporary secret state were removed. Production capabilities remained disabled.
|
||||
@@ -1,8 +0,0 @@
|
||||
934a04b5d6ec9aa62cb991fb2f57256c439bac4b2ac110cabd524ad456e59491 ./capabilities-after.json
|
||||
934a04b5d6ec9aa62cb991fb2f57256c439bac4b2ac110cabd524ad456e59491 ./capabilities-before.json
|
||||
6873e42595287787b29f4f3a9fc45523fc77b51a096d24ac2d19a37d0277569a ./checks.jsonl
|
||||
d66fc3ce71f6170433ef3c49fdc432ebaf16344af391f4dca1fa9a66961993f6 ./framework-ci.txt
|
||||
77d1f72cb16529f15b54cd5be83178b26157f1cfa1b79997378ab9a6ce1f2f81 ./scope.txt
|
||||
9bd7362c763e4cc05f530c8958a646d7a4d0302a41a2b73b8ad5df2c3e274b92 probe.py
|
||||
dc7d2c5009290b0c19b5c350c660330a7facb996e7d3b7fede1eb0f5f8dbf2b2 run.sh
|
||||
d7db8a2f86b9ee00f198c9e2b526f9f5acaae1c4550f5988d824b6d95bb3dc07 README.md
|
||||
@@ -1,16 +0,0 @@
|
||||
{"engine": "framework", "result": "PASS", "check": "approved child receives fixed PATH and locale only"}
|
||||
{"engine": "mysql", "result": "PASS", "check": "disposable database has no external network or published ports and only the read-only site credential bind"}
|
||||
{"engine": "mysql", "result": "PASS", "check": "missing credential file rejects authentication without publishing output"}
|
||||
{"engine": "mysql", "result": "PASS", "check": "adapter authenticates as the designated UID with backend-delivered file; unrelated UID cannot read it"}
|
||||
{"engine": "mysql", "result": "PASS", "check": "server explicitly rejects the old credential after password rotation"}
|
||||
{"engine": "mysql", "result": "PASS", "check": "new backend credential atomically delivered to the existing container authenticates"}
|
||||
{"engine": "mysql", "result": "PASS", "check": "re-delivering the retired credential still fails server authentication"}
|
||||
{"engine": "mysql", "result": "PASS", "check": "re-delivering the new credential works in the original running container"}
|
||||
{"engine": "pgsql", "result": "PASS", "check": "disposable database has no external network or published ports and only the read-only site credential bind"}
|
||||
{"engine": "pgsql", "result": "PASS", "check": "missing credential file rejects authentication without publishing output"}
|
||||
{"engine": "pgsql", "result": "PASS", "check": "adapter authenticates as the designated UID with backend-delivered file; unrelated UID cannot read it"}
|
||||
{"engine": "pgsql", "result": "PASS", "check": "server explicitly rejects the old credential after password rotation"}
|
||||
{"engine": "pgsql", "result": "PASS", "check": "new backend credential atomically delivered to the existing container authenticates"}
|
||||
{"engine": "pgsql", "result": "PASS", "check": "re-delivering the retired credential still fails server authentication"}
|
||||
{"engine": "pgsql", "result": "PASS", "check": "re-delivering the new credential works in the original running container"}
|
||||
{"engine": "framework", "result": "PASS", "check": "all disposable containers and their anonymous volumes removed"}
|
||||
@@ -1,204 +0,0 @@
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import subprocess
|
||||
import tempfile
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from core.database import get_adapter
|
||||
from core.execution import CommandRunner, ExecutionError
|
||||
from core.secret_backend import FileSecretBackend
|
||||
from core.site_secrets import SiteSecrets
|
||||
|
||||
IMAGES = {
|
||||
"mysql": "sha256:8c233bad33d520a7aae1c1e619c3a9775f4a1ba2d463d692fada04ec7f40be00",
|
||||
"pgsql": "sha256:e742a2668255221388004f3a42b6150a2103f5054ab3a4a93ae9e4f01e551c35",
|
||||
}
|
||||
KEY_PATHS = {"mysql": "/run/secrets/absdev-client.cnf", "pgsql": "/run/secrets/absdev-pgpass"}
|
||||
containers = []
|
||||
event_count = 0
|
||||
|
||||
def docker(*args, input_data=None):
|
||||
return subprocess.run(("docker", *args), input=input_data, capture_output=True,
|
||||
text=True, timeout=120)
|
||||
|
||||
def good(*args, input_data=None):
|
||||
result = docker(*args, input_data=input_data)
|
||||
if result.returncode:
|
||||
raise RuntimeError(f"Docker {args[0]} failed with status {result.returncode}")
|
||||
return result.stdout.strip()
|
||||
|
||||
def record(engine, check):
|
||||
global event_count
|
||||
event_count += 1
|
||||
print(json.dumps(dict(engine=engine, result="PASS", check=check)), flush=True)
|
||||
|
||||
def start(engine, name, mount):
|
||||
variable = "MYSQL_ROOT_PASSWORD" if engine == "mysql" else "POSTGRES_PASSWORD"
|
||||
environment = Path.cwd().parent / (name + ".env")
|
||||
environment.write_text(variable + "=" + secrets.token_hex(24) + "\n")
|
||||
environment.chmod(0o600)
|
||||
with environment.open("a") as handle:
|
||||
if engine == "pgsql":
|
||||
handle.write("POSTGRES_INITDB_ARGS=--auth-host=scram-sha-256\n")
|
||||
try:
|
||||
cid = good("create", "--pull", "never", "--name", name, "--network", "none",
|
||||
"--security-opt", "no-new-privileges", "--cap-drop", "NET_RAW",
|
||||
"--memory", "1g", "--pids-limit", "256", "--env-file", str(environment),
|
||||
"--mount", f"type=bind,source={mount},target=/run/secrets,readonly",
|
||||
IMAGES[engine])
|
||||
finally:
|
||||
environment.unlink()
|
||||
containers.append(cid)
|
||||
good("start", cid)
|
||||
details = json.loads(good("inspect", "--format", "{{json .HostConfig}}", cid))
|
||||
assert details["NetworkMode"] == "none" and not details["Privileged"]
|
||||
assert not details["PortBindings"]
|
||||
live_mounts = json.loads(good("inspect", "--format", "{{json .Mounts}}", cid))
|
||||
binds = [item for item in live_mounts if item["Type"] == "bind"]
|
||||
assert len(binds) == 1 and binds[0]["Destination"] == "/run/secrets"
|
||||
assert binds[0]["Source"] == str(mount) and not binds[0]["RW"]
|
||||
record(engine, "disposable database has no external network or published ports and only the read-only site credential bind")
|
||||
return name, cid
|
||||
|
||||
def admin(engine, cid, sql):
|
||||
if engine == "mysql":
|
||||
return docker("exec", "-i", cid, "sh", "-c",
|
||||
'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" exec mysql --no-defaults -uroot --batch',
|
||||
input_data=sql)
|
||||
return docker("exec", "-i", "--user", "postgres", cid, "psql", "-X", "-U", "postgres",
|
||||
"-d", "postgres", "-v", "ON_ERROR_STOP=1", input_data=sql)
|
||||
|
||||
def ready(engine, cid):
|
||||
for _ in range(90):
|
||||
if engine == "pgsql":
|
||||
status = docker("exec", cid, "pg_isready", "-h", "127.0.0.1", "-U", "postgres")
|
||||
if status.returncode:
|
||||
time.sleep(1)
|
||||
continue
|
||||
else:
|
||||
status = docker("exec", cid, "sh", "-c",
|
||||
'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" mysql --no-defaults --protocol=TCP -h127.0.0.1 -uroot -e "SELECT 1"')
|
||||
if status.returncode:
|
||||
time.sleep(1)
|
||||
continue
|
||||
if admin(engine, cid, "SELECT 1;").returncode == 0:
|
||||
return
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"{engine} did not become ready")
|
||||
|
||||
def publish(engine, backend, delivery, password):
|
||||
filename = Path(KEY_PATHS[engine]).name
|
||||
data = ("[client]\npassword=" + password + "\n" if engine == "mysql"
|
||||
else "127.0.0.1:5432:fixture:fixture:" + password + "\n")
|
||||
area = backend.directory / backend.site
|
||||
with tempfile.NamedTemporaryFile(dir=area, delete=False) as stream:
|
||||
stream.write(data.encode())
|
||||
stream.flush()
|
||||
os.fchown(stream.fileno(), 0, backend.group)
|
||||
os.fchmod(stream.fileno(), 0o440)
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(stream.name, area / filename)
|
||||
backend.deliver(delivery, "database", filename)
|
||||
|
||||
def check_command(runner, command, success):
|
||||
output = io.BytesIO()
|
||||
try:
|
||||
runner(command, output)
|
||||
except ExecutionError:
|
||||
assert not success and not output.getvalue()
|
||||
else:
|
||||
assert success and output.getvalue().strip() == b"1"
|
||||
|
||||
def qualify(engine):
|
||||
name = "absdev-cutover-" + engine + "-" + secrets.token_hex(5)
|
||||
root = Path.cwd().parent / name
|
||||
root.mkdir(mode=0o700)
|
||||
backend_root = root / "backend"
|
||||
backend_root.mkdir()
|
||||
backend_root.chmod(0o711)
|
||||
area = backend_root / name
|
||||
area.mkdir()
|
||||
uid = 11001 if engine == "mysql" else 11002
|
||||
os.chown(area, 0, uid)
|
||||
area.chmod(0o750)
|
||||
delivery_root = root / "delivery"
|
||||
delivery_root.mkdir(mode=0o700)
|
||||
config = json.loads(Path("config/site.example.json").read_text())
|
||||
config["site"].update(identifier=name, root=str(root))
|
||||
config["docker"]["project"] = name
|
||||
config["database"].update(driver=engine, container=name, host="127.0.0.1",
|
||||
port=3306 if engine == "mysql" else 5432,
|
||||
name="fixture", username="fixture")
|
||||
backend = FileSecretBackend(backend_root, name, uid)
|
||||
delivery = SiteSecrets(config, delivery_root, {"database": uid})
|
||||
override = json.loads(delivery.compose_file(config).read_text())
|
||||
mount = override["services"]["database"]["volumes"][0]
|
||||
assert mount["target"] == "/run/secrets" and mount["read_only"]
|
||||
_, cid = start(engine, name, Path(mount["source"]))
|
||||
ready(engine, cid)
|
||||
original, rotated = secrets.token_hex(24), secrets.token_hex(24)
|
||||
if engine == "mysql":
|
||||
setup = ("CREATE DATABASE fixture; "
|
||||
f"CREATE USER 'fixture'@'127.0.0.1' IDENTIFIED BY '{original}'; "
|
||||
"GRANT SELECT ON fixture.* TO 'fixture'@'127.0.0.1';")
|
||||
change = f"ALTER USER 'fixture'@'127.0.0.1' IDENTIFIED BY '{rotated}';"
|
||||
else:
|
||||
setup = f"CREATE ROLE fixture LOGIN PASSWORD '{original}';\nCREATE DATABASE fixture OWNER fixture;"
|
||||
change = f"ALTER ROLE fixture PASSWORD '{rotated}';"
|
||||
assert admin(engine, cid, setup).returncode == 0, f"{engine} fixture setup failed"
|
||||
original_command = get_adapter(config).ping_command()
|
||||
assert original_command[:3] == ["docker", "exec", name]
|
||||
command = ["docker", "exec", "--user", f"{uid}:{uid}", cid, *original_command[3:]]
|
||||
assert not any(value in arg for arg in command for value in (original, rotated))
|
||||
runner = CommandRunner([command], timeout=15)
|
||||
check_command(runner, command, False)
|
||||
record(engine, "missing credential file rejects authentication without publishing output")
|
||||
publish(engine, backend, delivery, original)
|
||||
path = KEY_PATHS[engine]
|
||||
assert docker("exec", "--user", "65534:65534", cid, "cat", path).returncode != 0
|
||||
check_command(runner, command, True)
|
||||
record(engine, "adapter authenticates as the designated UID with backend-delivered file; unrelated UID cannot read it")
|
||||
assert admin(engine, cid, change).returncode == 0, f"{engine} password rotation failed"
|
||||
check_command(runner, command, False)
|
||||
denied = docker(*command[1:])
|
||||
expected_error = "Access denied" if engine == "mysql" else "password authentication failed"
|
||||
assert denied.returncode and expected_error in denied.stderr and not denied.stdout
|
||||
record(engine, "server explicitly rejects the old credential after password rotation")
|
||||
publish(engine, backend, delivery, rotated)
|
||||
check_command(runner, command, True)
|
||||
record(engine, "new backend credential atomically delivered to the existing container authenticates")
|
||||
publish(engine, backend, delivery, original)
|
||||
check_command(runner, command, False)
|
||||
record(engine, "re-delivering the retired credential still fails server authentication")
|
||||
publish(engine, backend, delivery, rotated)
|
||||
check_command(runner, command, True)
|
||||
assert good("inspect", "--format", "{{.State.Running}}", cid) == "true"
|
||||
record(engine, "re-delivering the new credential works in the original running container")
|
||||
|
||||
try:
|
||||
os.environ.update(PATH="/untrusted", ABSDEV_TEST_SECRET="synthetic", DOCKER_HOST="synthetic",
|
||||
PGPASSWORD="synthetic", MYSQL_PWD="synthetic")
|
||||
argv = [sys.executable, "-I", "-c", "import json, os; print(json.dumps(dict(os.environ)))"]
|
||||
output = io.BytesIO()
|
||||
CommandRunner([argv])(argv, output)
|
||||
assert json.loads(output.getvalue()) == {"PATH": os.defpath, "LC_ALL": "C"}
|
||||
record("framework", "approved child receives fixed PATH and locale only")
|
||||
# The qualification controller needs its own trusted Docker environment.
|
||||
for name in ("ABSDEV_TEST_SECRET", "DOCKER_HOST", "PGPASSWORD", "MYSQL_PWD"):
|
||||
os.environ.pop(name)
|
||||
os.environ["PATH"] = os.defpath
|
||||
for engine in IMAGES:
|
||||
qualify(engine)
|
||||
finally:
|
||||
cleanup_failed = False
|
||||
for cid in reversed(containers):
|
||||
command = docker("rm", "-fv", cid)
|
||||
if command.returncode:
|
||||
cleanup_failed = True
|
||||
if cleanup_failed:
|
||||
raise RuntimeError("Disposable container cleanup failed")
|
||||
record("framework", "all disposable containers and their anonymous volumes removed")
|
||||
@@ -1,2 +0,0 @@
|
||||
host=absdev-ci
|
||||
revision=1c3df42a68d75b825993f9e5b9a774e5eeacff4b
|
||||
@@ -0,0 +1,8 @@
|
||||
934a04b5d6ec9aa62cb991fb2f57256c439bac4b2ac110cabd524ad456e59491 ./capabilities-after.json
|
||||
934a04b5d6ec9aa62cb991fb2f57256c439bac4b2ac110cabd524ad456e59491 ./capabilities-before.json
|
||||
5ea47740256cc6cd2cb3a9a224c836388ecc07128e3811042065553606a6857c ./framework-ci.txt
|
||||
19158d14d7f207e6bcdbd5ff2a4031479585840a901104c019948f7d5c22541b ./rehearsal-attestation.json
|
||||
d67e476d883681d5f54c62e67468ebcb2ff23fb0732a69d0001560b7ea1cd00c ./scope.txt
|
||||
e62a74b5def068d3eaf560f0b9ac107ef74e4b780b400023714f7616b96e3ef7 run.sh
|
||||
3f2caca8724625e8f852a9c85ae96d7c0661e4eee6e27ead8e7f3e105b8bc5f8 probe.py
|
||||
65047c5a7a9c5900b5c6fd13b6c0f6c72eba7508fe87127220a689465e91c028 rehearsal.php
|
||||
+3
-3
@@ -2,12 +2,12 @@
|
||||
Python 3.14.4
|
||||
|
||||
=== PYTHON SYNTAX VALIDATION ===
|
||||
PASS: 88 Python sources compiled
|
||||
PASS: 89 Python sources compiled
|
||||
|
||||
=== COMPLETE UNIT REGRESSION SUITE ===
|
||||
..................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
|
||||
..........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
|
||||
----------------------------------------------------------------------
|
||||
Ran 898 tests in 18.573s
|
||||
Ran 906 tests in 18.019s
|
||||
|
||||
OK
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
sys.path.insert(0, str(Path("tests/unit").resolve()))
|
||||
from test_provenance import ProvenanceTests
|
||||
from core.dev3.provenance import CompleteProvenance
|
||||
from core.rehearsal import RehearsalError, create_rehearsal
|
||||
from core.trusted_rehearsal import TrustedRehearsal
|
||||
from core.approval import issue_approval
|
||||
from core.approval_store import ApprovalStore, ApprovalStoreError
|
||||
from core.operator_approval import OperatorApprovalPolicy, OperatorGrant
|
||||
from datetime import timedelta
|
||||
|
||||
PG = "sha256:e742a2668255221388004f3a42b6150a2103f5054ab3a4a93ae9e4f01e551c35"
|
||||
PHP = "sha256:cac70f6c4aa761a1c04c6813c03a7678b9a5c061cc67a413a12736253e7128ee"
|
||||
DEPS = "/var/tmp/absdev-dev3-ci.8yBxcV/public-fixture"
|
||||
DIRS = ["database/migrations", "Modules/Orders/Database/Migrations",
|
||||
"modules/products/database/migrations", "Modules/Billing/database/Migrations"]
|
||||
PATHS = [
|
||||
DIRS[0] + "/0001_create_users.php", DIRS[0] + "/0002_create_orders.php",
|
||||
DIRS[1] + "/0003_add_order.php", DIRS[2] + "/0004_add_product.php",
|
||||
DIRS[3] + "/0005_add_billing.php",
|
||||
]
|
||||
source, target = "rehearsal_source", "isolated_restore_laravel"
|
||||
fixture = ProvenanceTests()
|
||||
cid = None
|
||||
|
||||
def run(*args, data=None, check=True):
|
||||
return subprocess.run(args, input=data, capture_output=True, check=check, timeout=90)
|
||||
|
||||
def pg(*args, data=None, check=True):
|
||||
return run("docker", "exec", "-i", "--user", "postgres", cid, *args, data=data, check=check)
|
||||
|
||||
def sql(database, query):
|
||||
return pg("psql", "-XqAt", "-v", "ON_ERROR_STOP=1", "-d", database, data=query.encode()).stdout.strip()
|
||||
|
||||
try:
|
||||
fixture.setUp()
|
||||
for index, name in enumerate(PATHS, 1):
|
||||
body = r"""<?php
|
||||
return new class extends \Illuminate\Database\Migrations\Migration {
|
||||
public function up(): void {
|
||||
\Illuminate\Database\Capsule\Manager::connection()
|
||||
->table('rehearsal_items')->insert(['id' => INDEX, 'label' => 'migration-INDEX']);
|
||||
}
|
||||
};
|
||||
""".replace("INDEX", str(index))
|
||||
for root in (fixture.repository, fixture.release):
|
||||
path = root / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(body)
|
||||
fixture.git("add", ".")
|
||||
fixture.git("commit", "-qm", "Add disposable migrations")
|
||||
revision = fixture.git("rev-parse", "HEAD").strip()
|
||||
(fixture.release / "REVISION").write_text(revision + "\n")
|
||||
provenance = CompleteProvenance(fixture.repository, [revision], {}).verify(fixture.release)
|
||||
pending = sorted(Path(p).stem for p in provenance["migrations"])
|
||||
state = fixture.root
|
||||
secret = secrets.token_hex(32)
|
||||
env = state / "pg.env"
|
||||
env.write_text(f"POSTGRES_PASSWORD={secret}\nPOSTGRES_INITDB_ARGS=--auth-host=scram-sha-256\n")
|
||||
env.chmod(0o600)
|
||||
cid = run("docker", "create", "--pull", "never", "--network", "none",
|
||||
"--security-opt", "no-new-privileges", "--memory", "1g",
|
||||
"--env-file", str(env), PG).stdout.decode().strip()
|
||||
run("docker", "start", cid)
|
||||
info = json.loads(run("docker", "inspect", "--format", "{{json .HostConfig}}", cid).stdout)
|
||||
assert info["NetworkMode"] == "none" and not info["Privileged"] and not info["PortBindings"]
|
||||
for _ in range(60):
|
||||
if pg("pg_isready", "-h", "127.0.0.1", check=False).returncode == 0:
|
||||
break
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise RuntimeError("Disposable PostgreSQL did not become ready")
|
||||
sql("postgres", f"CREATE DATABASE {source}; CREATE DATABASE {target};")
|
||||
sql(source, "CREATE TABLE rehearsal_items(id integer PRIMARY KEY, label text); "
|
||||
"INSERT INTO rehearsal_items VALUES(0,'backup-sentinel');")
|
||||
backup = pg("pg_dump", "--format=custom", source).stdout
|
||||
assert backup.startswith(b"PGDMP")
|
||||
identity = lambda db: hashlib.sha256((cid + ":" + db).encode()).hexdigest()
|
||||
context = dict(site="rehearsal-lab", release="2", revision=revision,
|
||||
provenance=provenance["fingerprint"], compatibility="a"*64,
|
||||
database_identity=identity(source), backup_sha256=hashlib.sha256(backup).hexdigest(),
|
||||
pending_migrations=pending)
|
||||
observed = {}
|
||||
|
||||
def runner(request):
|
||||
global cid
|
||||
assert request == context
|
||||
pg("pg_restore", "--exit-on-error", "-d", target, data=backup)
|
||||
assert sql(target, "SELECT label FROM rehearsal_items;") == b"backup-sentinel"
|
||||
credential = state / "credential.json"
|
||||
credential.write_text(json.dumps({"driver": "pgsql", "host": "127.0.0.1", "port": 5432,
|
||||
"database": target, "username": "postgres", "password": secret}))
|
||||
credential.chmod(0o600)
|
||||
result = run(
|
||||
"docker", "run", "--rm", "--pull", "never", "--network", f"container:{cid}",
|
||||
"--read-only", "--cap-drop", "ALL", "--cap-add", "DAC_OVERRIDE",
|
||||
"--security-opt", "no-new-privileges",
|
||||
"-v", f"{DEPS}:/deps:ro", "-v", f"{fixture.release}:/release:ro",
|
||||
"-v", f"{credential}:/credential.json:ro",
|
||||
"-v", f"{Path('rehearsal.php').resolve()}:/rehearsal.php:ro",
|
||||
"--entrypoint", "php", PHP, "/rehearsal.php", *DIRS, check=False,
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError((result.stdout + result.stderr).decode(errors="replace").replace(secret, "[redacted]")[:2000])
|
||||
outcome = json.loads(result.stdout)
|
||||
assert sorted(outcome["inventory"].values()) == sorted(provenance["migrations"])
|
||||
assert outcome["history"] == pending and outcome["database"] == target
|
||||
assert outcome["restored_and_migrated_rows"] == ["backup-sentinel"] + [f"migration-{n}" for n in range(1, 6)]
|
||||
assert sql(source, "SELECT label FROM rehearsal_items;") == b"backup-sentinel"
|
||||
assert sql(source, "SELECT to_regclass('public.migrations') IS NULL;") == b"t"
|
||||
execution = dict(driver="postgresql", source_database=source, target_database=target,
|
||||
target_identity=identity(target), applied_migrations=outcome["history"],
|
||||
checks=dict.fromkeys(("isolation_verified", "backup_restored", "migration_succeeded",
|
||||
"migration_history_verified", "application_verified",
|
||||
"cleanup_verified"), True))
|
||||
run("docker", "rm", "-fv", cid)
|
||||
cid = None
|
||||
observed["outcome"] = outcome
|
||||
return execution
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
trusted = TrustedRehearsal("absdev-ci-laravel", runner, key=secrets.token_bytes(32), clock=lambda: now)
|
||||
record = trusted.run(context)
|
||||
outcome = observed["outcome"]
|
||||
approved_context = trusted.approval_context(record, context, now=now)
|
||||
grants = [OperatorGrant(10001, "fixture-operator", action, context["site"], revision,
|
||||
now + timedelta(hours=1)) for action in ("issue", "execute")]
|
||||
policy = OperatorApprovalPolicy(grants, sealing_key=secrets.token_bytes(32))
|
||||
area = state / "approvals"
|
||||
area.mkdir(mode=0o700)
|
||||
store = ApprovalStore(area, operator_policy=lambda: policy, trusted_rehearsal=trusted)
|
||||
draft = issue_approval(approved_context, approver="fixture-operator", now=now)
|
||||
choices = dict(confirmation=draft["confirmation"], now=now)
|
||||
unsigned = {k: v for k, v in record.items() if k not in ("runner_id", "runner_seal")}
|
||||
forged = dict(record, runner_seal="0"*64)
|
||||
with patch("core.operator_approval.geteuid", return_value=10001):
|
||||
for untrusted in (unsigned, forged):
|
||||
try:
|
||||
store.save(draft, approved_context, rehearsal=untrusted, **choices)
|
||||
except ApprovalStoreError:
|
||||
assert not store.approval_path(draft["approval_id"]).exists()
|
||||
else:
|
||||
raise AssertionError("Untrusted rehearsal accepted at issuance")
|
||||
store.save(draft, approved_context, rehearsal=record, **choices)
|
||||
for untrusted in (unsigned, forged):
|
||||
try:
|
||||
store.consume(draft["approval_id"], context, untrusted, **choices)
|
||||
except ApprovalStoreError:
|
||||
assert not store.consumed_path(draft["approval_id"]).exists()
|
||||
else:
|
||||
raise AssertionError("Untrusted rehearsal accepted at consumption")
|
||||
receipt = store.consume(draft["approval_id"], context, record, **choices)
|
||||
assert receipt["rehearsal_fingerprint"] == record["fingerprint"]
|
||||
assert receipt["migration_executed"] is False
|
||||
wrong = copy.deepcopy(record["execution"])
|
||||
wrong["applied_migrations"].pop()
|
||||
try:
|
||||
create_rehearsal(context, wrong, completed_at=now)
|
||||
except RehearsalError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("Incomplete migration evidence was accepted")
|
||||
print(json.dumps({"laravel": outcome, "framework_inventory": sorted(provenance["migrations"]),
|
||||
"same_paths_and_applied_names": True, "incomplete_history_rejected": True,
|
||||
"source_unchanged": True, "disposable_database_removed": True,
|
||||
"trusted_runner": record["runner_id"],
|
||||
"unsigned_and_forged_evidence_rejected_at_issuance_and_consumption": True,
|
||||
"trusted_rehearsal_approved_and_consumed": True,
|
||||
"operator_scope": "Synthetic effective UID for approval integration",
|
||||
"rehearsal_fingerprint": record["fingerprint"]}, indent=2))
|
||||
finally:
|
||||
if cid:
|
||||
run("docker", "rm", "-fv", cid)
|
||||
fixture.doCleanups()
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"laravel": {
|
||||
"laravel_version": "v13.44.1",
|
||||
"database": "isolated_restore_laravel",
|
||||
"inventory": {
|
||||
"0001_create_users": "database/migrations/0001_create_users.php",
|
||||
"0002_create_orders": "database/migrations/0002_create_orders.php",
|
||||
"0003_add_order": "Modules/Orders/Database/Migrations/0003_add_order.php",
|
||||
"0004_add_product": "modules/products/database/migrations/0004_add_product.php",
|
||||
"0005_add_billing": "Modules/Billing/database/Migrations/0005_add_billing.php"
|
||||
},
|
||||
"history": [
|
||||
"0001_create_users",
|
||||
"0002_create_orders",
|
||||
"0003_add_order",
|
||||
"0004_add_product",
|
||||
"0005_add_billing"
|
||||
],
|
||||
"restored_and_migrated_rows": [
|
||||
"backup-sentinel",
|
||||
"migration-1",
|
||||
"migration-2",
|
||||
"migration-3",
|
||||
"migration-4",
|
||||
"migration-5"
|
||||
]
|
||||
},
|
||||
"framework_inventory": [
|
||||
"Modules/Billing/database/Migrations/0005_add_billing.php",
|
||||
"Modules/Orders/Database/Migrations/0003_add_order.php",
|
||||
"database/migrations/0001_create_users.php",
|
||||
"database/migrations/0002_create_orders.php",
|
||||
"modules/products/database/migrations/0004_add_product.php"
|
||||
],
|
||||
"same_paths_and_applied_names": true,
|
||||
"incomplete_history_rejected": true,
|
||||
"source_unchanged": true,
|
||||
"disposable_database_removed": true,
|
||||
"trusted_runner": "absdev-ci-laravel",
|
||||
"unsigned_and_forged_evidence_rejected_at_issuance_and_consumption": true,
|
||||
"trusted_rehearsal_approved_and_consumed": true,
|
||||
"operator_scope": "Synthetic effective UID for approval integration",
|
||||
"rehearsal_fingerprint": "696706cb2e4527ac36629a633f10869588719b241f27f171568759e8ba9edd76"
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
require '/deps/vendor/autoload.php';
|
||||
|
||||
use Illuminate\Database\Capsule\Manager;
|
||||
use Illuminate\Database\Migrations\DatabaseMigrationRepository;
|
||||
use Illuminate\Database\Migrations\Migrator;
|
||||
use Illuminate\Filesystem\Filesystem;
|
||||
|
||||
$config = json_decode(file_get_contents('/credential.json'), true, flags: JSON_THROW_ON_ERROR);
|
||||
$capsule = new Manager();
|
||||
$capsule->addConnection($config);
|
||||
$capsule->setAsGlobal();
|
||||
$resolver = $capsule->getDatabaseManager();
|
||||
$repository = new DatabaseMigrationRepository($resolver, 'migrations');
|
||||
$repository->createRepository();
|
||||
$migrator = new Migrator($repository, $resolver, new Filesystem());
|
||||
$paths = array_map(fn ($dir) => '/release/'.$dir, array_slice($argv, 1));
|
||||
$files = $migrator->getMigrationFiles($paths);
|
||||
$migrator->run($paths);
|
||||
$db = $capsule->getConnection();
|
||||
$checks = $db->table('rehearsal_items')->orderBy('id')->pluck('label')->all();
|
||||
$files = array_map(fn ($file) => substr($file, strlen('/release/')), $files);
|
||||
echo json_encode([
|
||||
'laravel_version' => Composer\InstalledVersions::getPrettyVersion('laravel/framework'),
|
||||
'database' => $db->selectOne('SELECT current_database() AS name')->name,
|
||||
'inventory' => $files,
|
||||
'history' => $repository->getRan(),
|
||||
'restored_and_migrated_rows' => $checks,
|
||||
], JSON_THROW_ON_ERROR);
|
||||
+3
-3
@@ -1,17 +1,17 @@
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
test "$(hostname -s | tr A-Z a-z)" = absdev-ci
|
||||
stage=$(mktemp -d /var/tmp/absdev-db-cutover.XXXXXX)
|
||||
stage=$(mktemp -d /var/tmp/absdev-rehearsal-trust.XXXXXX)
|
||||
trap 'rm -rf -- "$stage"' EXIT
|
||||
mkdir "$stage/source" "$stage/evidence" "$stage/tmp"
|
||||
tar -xm -f - -C "$stage/source"
|
||||
cd "$stage/source"
|
||||
export TMPDIR="$stage/tmp"
|
||||
out="$stage/evidence"
|
||||
printf 'host=%s\nrevision=1c3df42a68d75b825993f9e5b9a774e5eeacff4b\n' "$(hostname -s)" > "$out/scope.txt"
|
||||
printf 'host=%s\nrevision=b0495d80f15848ad87783c143c77be44344132cf\n' "$(hostname -s)" > "$out/scope.txt"
|
||||
python3 -B bin/absdev-deploy capabilities > "$out/capabilities-before.json"
|
||||
python3 -B -c 'import json,sys; d=json.load(open(sys.argv[1])); f=[v for k,v in d.items() if k.endswith("_enabled") or k=="production_ready"]; assert len(f)==6 and all(v is False for v in f)' "$out/capabilities-before.json"
|
||||
python3 -B probe.py > "$out/checks.jsonl" || { cat "$out/checks.jsonl" >&2; exit 1; }
|
||||
python3 -B probe.py > "$out/rehearsal-attestation.json" || { cat "$out/rehearsal-attestation.json" >&2; exit 1; }
|
||||
bash scripts/ci-check.sh > "$out/framework-ci.txt" 2>&1 || { tail -80 "$out/framework-ci.txt" >&2; exit 1; }
|
||||
python3 -B bin/absdev-deploy capabilities > "$out/capabilities-after.json"
|
||||
cmp "$out/capabilities-before.json" "$out/capabilities-after.json"
|
||||
@@ -0,0 +1,2 @@
|
||||
host=absdev-ci
|
||||
revision=b0495d80f15848ad87783c143c77be44344132cf
|
||||
@@ -14,7 +14,8 @@ from core.approval import approval_checksum, issue_approval
|
||||
from core.approval_store import ApprovalStore, ApprovalStoreError
|
||||
from core.operator_approval import OperatorApprovalPolicy, OperatorGrant
|
||||
from core.locking import DeploymentLock, LockError
|
||||
from core.rehearsal import create_rehearsal, approval_context
|
||||
from core.rehearsal import create_rehearsal, fingerprint
|
||||
from core.trusted_rehearsal import TrustedRehearsal
|
||||
|
||||
|
||||
class ApprovalStoreTests(unittest.TestCase):
|
||||
@@ -62,16 +63,13 @@ class ApprovalStoreTests(unittest.TestCase):
|
||||
},
|
||||
}
|
||||
|
||||
self.rehearsal = create_rehearsal(
|
||||
self.base,
|
||||
self.execution,
|
||||
completed_at=self.now,
|
||||
self.trusted_rehearsal = TrustedRehearsal(
|
||||
"fixture-runner", lambda _context: self.execution,
|
||||
key=os.urandom(32), clock=lambda: self.now,
|
||||
)
|
||||
|
||||
self.context = approval_context(
|
||||
self.rehearsal,
|
||||
self.base,
|
||||
now=self.now,
|
||||
self.rehearsal = self.trusted_rehearsal.run(self.base)
|
||||
self.context = self.trusted_rehearsal.approval_context(
|
||||
self.rehearsal, self.base, now=self.now,
|
||||
)
|
||||
|
||||
self.approval = issue_approval(
|
||||
@@ -96,13 +94,15 @@ class ApprovalStoreTests(unittest.TestCase):
|
||||
for operation in ("issue", "execute")
|
||||
]
|
||||
self.policy = OperatorApprovalPolicy(self.grants, sealing_key=self.key)
|
||||
self.store = ApprovalStore(self.root, operator_policy=self.policy)
|
||||
self.store = ApprovalStore(self.root, operator_policy=lambda: self.policy,
|
||||
trusted_rehearsal=self.trusted_rehearsal)
|
||||
|
||||
def save(self):
|
||||
|
||||
return self.store.save(
|
||||
self.approval,
|
||||
self.context,
|
||||
rehearsal=self.rehearsal,
|
||||
confirmation=self.approval["confirmation"],
|
||||
now=self.now,
|
||||
)
|
||||
@@ -171,7 +171,8 @@ class ApprovalStoreTests(unittest.TestCase):
|
||||
self.save()
|
||||
self.consume()
|
||||
|
||||
self.store = ApprovalStore(self.root, operator_policy=self.policy)
|
||||
self.store = ApprovalStore(self.root, operator_policy=lambda: self.policy,
|
||||
trusted_rehearsal=self.trusted_rehearsal)
|
||||
|
||||
with self.assertRaisesRegex(ApprovalStoreError, "already consumed"):
|
||||
self.consume()
|
||||
@@ -216,6 +217,7 @@ class ApprovalStoreTests(unittest.TestCase):
|
||||
self.store.save(
|
||||
self.approval,
|
||||
self.context,
|
||||
rehearsal=self.rehearsal,
|
||||
confirmation=self.approval["confirmation"],
|
||||
now=self.now + timedelta(hours=20),
|
||||
)
|
||||
@@ -476,6 +478,7 @@ class ApprovalStoreTests(unittest.TestCase):
|
||||
self.store.save(
|
||||
self.approval,
|
||||
self.context,
|
||||
rehearsal=self.rehearsal,
|
||||
confirmation=self.approval["confirmation"],
|
||||
now=self.now + timedelta(hours=25),
|
||||
)
|
||||
@@ -483,13 +486,13 @@ class ApprovalStoreTests(unittest.TestCase):
|
||||
|
||||
def test_missing_policy_denies_issuance(self):
|
||||
self.store = ApprovalStore(self.root)
|
||||
with self.assertRaisesRegex(ApprovalStoreError, "policy required"):
|
||||
with self.assertRaisesRegex(ApprovalStoreError, "policy loader required"):
|
||||
self.save()
|
||||
self.assertFalse(self.store.approval_path(self.identifier).exists())
|
||||
|
||||
def test_unrecognised_os_identity_denies_issuance(self):
|
||||
other_account = [replace(grant, uid=self.uid + 1) for grant in self.grants]
|
||||
self.store.operator_policy = OperatorApprovalPolicy(other_account, sealing_key=self.key)
|
||||
self.policy = OperatorApprovalPolicy(other_account, sealing_key=self.key)
|
||||
with self.assertRaisesRegex(ApprovalStoreError, "not authorised"):
|
||||
self.save()
|
||||
self.assertFalse(self.store.approval_path(self.identifier).exists())
|
||||
@@ -502,7 +505,7 @@ class ApprovalStoreTests(unittest.TestCase):
|
||||
replace(execute, principal="other-operator"),
|
||||
replace(execute, expires_at=self.now)):
|
||||
with self.subTest(grant=grant):
|
||||
self.store.operator_policy = OperatorApprovalPolicy([grant], sealing_key=self.key)
|
||||
self.policy = OperatorApprovalPolicy([grant], sealing_key=self.key)
|
||||
with self.assertRaises(ApprovalStoreError):
|
||||
self.consume()
|
||||
self.assertFalse(self.store.consumed_path(self.identifier).exists())
|
||||
@@ -522,5 +525,52 @@ class ApprovalStoreTests(unittest.TestCase):
|
||||
self.consume()
|
||||
self.assertFalse(self.store.consumed_path(self.identifier).exists())
|
||||
|
||||
|
||||
def test_static_authority_is_rejected(self):
|
||||
self.store.operator_policy = self.policy
|
||||
with self.assertRaisesRegex(ApprovalStoreError, "policy loader required"):
|
||||
self.save()
|
||||
|
||||
def test_unavailable_authority_fails_closed_after_issuance(self):
|
||||
self.save()
|
||||
with patch.object(self.store, "operator_policy", side_effect=OSError("unavailable")):
|
||||
with self.assertRaises(ApprovalStoreError):
|
||||
self.consume()
|
||||
self.assertFalse(self.store.consumed_path(self.identifier).exists())
|
||||
|
||||
def test_running_store_rejects_retired_sealing_key(self):
|
||||
self.save()
|
||||
self.policy = OperatorApprovalPolicy(self.grants, sealing_key=os.urandom(32))
|
||||
with self.assertRaises(ApprovalStoreError):
|
||||
self.consume()
|
||||
self.assertFalse(self.store.consumed_path(self.identifier).exists())
|
||||
|
||||
|
||||
def test_unsigned_rehearsal_cannot_authorise_issuance_or_consumption(self):
|
||||
signed = self.rehearsal
|
||||
self.rehearsal = {name: value for name, value in signed.items()
|
||||
if name not in ("runner_id", "runner_seal")}
|
||||
with self.assertRaisesRegex(ApprovalStoreError, "Trusted rehearsal evidence required"):
|
||||
self.save()
|
||||
self.assertFalse(self.store.approval_path(self.identifier).exists())
|
||||
self.rehearsal = signed
|
||||
self.save()
|
||||
self.rehearsal = create_rehearsal(self.base, self.execution, completed_at=self.now)
|
||||
with self.assertRaises(ApprovalStoreError):
|
||||
self.consume()
|
||||
self.assertFalse(self.store.consumed_path(self.identifier).exists())
|
||||
|
||||
def test_recomputed_fingerprint_does_not_authorise_forgery(self):
|
||||
self.rehearsal["rehearsal_id"] = "f" * 32
|
||||
unsigned = {name: value for name, value in self.rehearsal.items()
|
||||
if name not in ("runner_id", "runner_seal")}
|
||||
self.rehearsal["fingerprint"] = fingerprint(unsigned)
|
||||
self.context["rehearsal_fingerprint"] = self.rehearsal["fingerprint"]
|
||||
self.approval = issue_approval(self.context, approver="operator", now=self.now)
|
||||
with self.assertRaisesRegex(ApprovalStoreError, "Untrusted rehearsal runner"):
|
||||
self.save()
|
||||
self.assertFalse(self.store.approval_path(self.approval["approval_id"]).exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -24,6 +24,9 @@ class ContainedServiceTests(unittest.TestCase):
|
||||
self.config, self.run_command, gate_directory=self.directory,
|
||||
ingress_sealed=lambda: self.gate.is_file() and self.probe_ok,
|
||||
worker_running=lambda _name: self.running,
|
||||
topology_runner=lambda _command, **_options: json.dumps({
|
||||
"networks": {self.config["docker"]["backend_network"]: {"internal": True}},
|
||||
}),
|
||||
)
|
||||
|
||||
def run_command(self, args, *, timeout):
|
||||
|
||||
@@ -20,3 +20,21 @@ class InventoryTests(unittest.TestCase):
|
||||
(root / "link").symlink_to(script)
|
||||
with self.assertRaises(ProvenanceError):
|
||||
inventory(root)
|
||||
|
||||
|
||||
class LaravelMigrationPathTests(unittest.TestCase):
|
||||
def test_inventory_matches_registered_directory_globs(self):
|
||||
from core.compatibility import is_laravel_migration_path
|
||||
|
||||
for path in (
|
||||
"Modules/Billing/database/Migrations/0001_add_invoice.php",
|
||||
"modules/Orders/Database/migrations/0002_add_order.php",
|
||||
"database/migrations/0003_add_user.php",
|
||||
):
|
||||
self.assertTrue(is_laravel_migration_path(path), path)
|
||||
for path in (
|
||||
"Modules/Billing/database/Migrations/nested/0001_add_invoice.php",
|
||||
"database/migrations/README.php",
|
||||
"database/migrations/nested/0003_add_user.php",
|
||||
):
|
||||
self.assertFalse(is_laravel_migration_path(path), path)
|
||||
|
||||
@@ -17,7 +17,8 @@ class MigrationTests(unittest.TestCase):
|
||||
self.fixture = test_approval_store.ApprovalStoreTests()
|
||||
self.addCleanup(self.fixture.doCleanups)
|
||||
self.fixture.setUp()
|
||||
self.ops = SiteOperations(self.fixture.root, operator_policy=self.fixture.policy)
|
||||
self.ops = SiteOperations(self.fixture.root, operator_policy=lambda: self.fixture.policy,
|
||||
trusted_rehearsal=self.fixture.trusted_rehearsal)
|
||||
self.fixture.store = self.ops.approvals
|
||||
self.fixture.save()
|
||||
|
||||
@@ -367,7 +368,7 @@ class MigrationTests(unittest.TestCase):
|
||||
def test_missing_execution_authority_blocks_before_containment(self):
|
||||
from core.operator_approval import OperatorApprovalPolicy
|
||||
|
||||
self.fixture.store.operator_policy = OperatorApprovalPolicy(
|
||||
self.fixture.policy = OperatorApprovalPolicy(
|
||||
self.fixture.grants[:1], sealing_key=self.fixture.key,
|
||||
)
|
||||
with self.assertRaises(MigrationError):
|
||||
|
||||
@@ -19,10 +19,14 @@ class ServiceTests(unittest.TestCase):
|
||||
)
|
||||
|
||||
self.runner = Mock(return_value=0)
|
||||
self.topology = Mock(return_value=json.dumps({
|
||||
"networks": {self.config["docker"]["backend_network"]: {"internal": True}},
|
||||
}))
|
||||
|
||||
self.manager = ServiceLifecycle(
|
||||
self.config,
|
||||
self.runner,
|
||||
topology_runner=self.topology,
|
||||
)
|
||||
|
||||
self.prefix = [
|
||||
@@ -74,6 +78,26 @@ class ServiceTests(unittest.TestCase):
|
||||
],
|
||||
)
|
||||
|
||||
def test_external_backend_blocks_start_and_restart(self):
|
||||
self.topology.return_value = json.dumps({
|
||||
"networks": {self.config["docker"]["backend_network"]: {"external": True}},
|
||||
})
|
||||
for operation in (self.manager.resume, self.manager.restart_php):
|
||||
with self.assertRaisesRegex(ServiceError, "External Compose backend"):
|
||||
operation()
|
||||
self.runner.assert_not_called()
|
||||
self.topology.assert_called_with(
|
||||
(*self.prefix, "config", "--format", "json"), timeout=30,
|
||||
)
|
||||
|
||||
def test_unverifiable_backend_fails_closed(self):
|
||||
for model in ("invalid json", '{"networks": {}}', '{"networks": null}'):
|
||||
with self.subTest(model=model):
|
||||
self.topology.return_value = model
|
||||
with self.assertRaisesRegex(ServiceError, "Unable to verify"):
|
||||
self.manager.resume()
|
||||
self.runner.assert_not_called()
|
||||
|
||||
def test_validate_nginx(self):
|
||||
|
||||
self.manager.validate_nginx()
|
||||
@@ -148,6 +172,7 @@ class ServiceTests(unittest.TestCase):
|
||||
manager = ServiceLifecycle(
|
||||
self.config,
|
||||
self.runner,
|
||||
topology_runner=self.topology,
|
||||
)
|
||||
|
||||
manager.restart_php()
|
||||
@@ -164,6 +189,7 @@ class ServiceTests(unittest.TestCase):
|
||||
manager = ServiceLifecycle(
|
||||
self.config,
|
||||
self.runner,
|
||||
topology_runner=self.topology,
|
||||
)
|
||||
|
||||
manager.validate_nginx()
|
||||
@@ -181,6 +207,7 @@ class ServiceTests(unittest.TestCase):
|
||||
manager = ServiceLifecycle(
|
||||
self.config,
|
||||
self.runner,
|
||||
topology_runner=self.topology,
|
||||
)
|
||||
|
||||
manager.quiesce()
|
||||
|
||||
Reference in New Issue
Block a user