Compare commits

...
Author SHA1 Message Date
Mark Gregory fec0778bfd Record ABSDEV-CI trusted rehearsal attestation qualification 2026-11-30 07:58:18 +00:00
Mark Gregory b0495d80f1 Require trusted runner attestation for migration rehearsals
ABSDEV Framework CI / framework-ci (push) Successful in 20s
2026-11-29 15:10:15 +00:00
Mark Gregory 5d3ea0d536 Match Laravel modular migration discovery and reject basename collisions
ABSDEV Framework CI / framework-ci (push) Successful in 23s
2026-11-29 14:11:07 +00:00
19 changed files with 612 additions and 40 deletions
+19 -4
View File
@@ -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()
@@ -323,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,
):
@@ -365,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
@@ -404,7 +419,7 @@ class ApprovalStore:
try:
context = approval_context(
context = self.rehearsal_context(
rehearsal,
base_context,
now=now,
+19 -11
View File
@@ -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),
+3 -2
View File
@@ -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)
+7 -8
View File
@@ -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
View File
@@ -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
)
+44
View File
@@ -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
+25
View File
@@ -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.
@@ -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
@@ -0,0 +1,19 @@
{
"commands": [
"validate",
"capabilities",
"inventory",
"retention-plan",
"provision-plan",
"site-policy",
"registry-validate",
"preflight"
],
"database_restore_enabled": false,
"deployment_execution_enabled": false,
"format_version": 1,
"migration_execution_enabled": false,
"permanent_deletion_enabled": false,
"production_ready": false,
"provisioning_execution_enabled": false
}
@@ -0,0 +1,19 @@
{
"commands": [
"validate",
"capabilities",
"inventory",
"retention-plan",
"provision-plan",
"site-policy",
"registry-validate",
"preflight"
],
"database_restore_enabled": false,
"deployment_execution_enabled": false,
"format_version": 1,
"migration_execution_enabled": false,
"permanent_deletion_enabled": false,
"production_ready": false,
"provisioning_execution_enabled": false
}
@@ -0,0 +1,108 @@
=== ABSDEV FRAMEWORK CI ===
Python 3.14.4
=== PYTHON SYNTAX VALIDATION ===
PASS: 89 Python sources compiled
=== COMPLETE UNIT REGRESSION SUITE ===
..........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
----------------------------------------------------------------------
Ran 906 tests in 18.019s
OK
=== VERIFY PRODUCTION CAPABILITY RESTRICTIONS ===
PASS: production_ready=false
PASS: deployment_execution_enabled=false
PASS: migration_execution_enabled=false
PASS: provisioning_execution_enabled=false
PASS: database_restore_enabled=false
PASS: permanent_deletion_enabled=false
PASS: Unsupported command rejected: deploy
PASS: Unsupported command rejected: migrate
PASS: Unsupported command rejected: rollback
PASS: Unsupported command rejected: restore
PASS: Unsupported command rejected: provision
PASS: Unsupported command rejected: delete
=== EXAMPLE CONFIGURATION ===
PASS: Configuration valid
Site: example-absdev-net
Domain: example.absdev.net
Database: mysql
Schema: 1
No deployment performed
{
"configuration_fingerprint": "8067fa8477a7d50cbcc42b585961bcd4dbce5407fc7e4bffcfb3e07af529e483",
"execution_permitted": false,
"fingerprint": "d271a3a3ed2cbda032f905558fe9ada653c380c74306fc714ebc594483a63042",
"format_version": 1,
"runtime_verified": false,
"site": "example-absdev-net",
"static_policy_verified": true,
"status": "VALID"
}
{
"configuration_fingerprint": "8067fa8477a7d50cbcc42b585961bcd4dbce5407fc7e4bffcfb3e07af529e483",
"database": {
"container": "platform-mysql",
"driver": "mysql",
"name": "example_db",
"username": "example_app"
},
"database_creation_permitted": false,
"directories": [
"/opt/laravel-sites/example-absdev-net",
"/opt/laravel-sites/example-absdev-net/app",
"/opt/laravel-sites/example-absdev-net/app/releases",
"/opt/laravel-sites/example-absdev-net/app/shared",
"/opt/laravel-sites/example-absdev-net/deployment",
"/opt/laravel-sites/example-absdev-net/backups",
"/opt/laravel-sites/example-absdev-net/deployment/state",
"/opt/laravel-sites/example-absdev-net/deployment/approvals",
"/opt/laravel-sites/example-absdev-net/deployment/archives"
],
"docker": {
"networks": [
"laravel_backend",
"laravel_proxy"
],
"project": "site-example-absdev-net",
"services": [
"php",
"web",
"queue",
"scheduler"
]
},
"domain": "example.absdev.net",
"execution_permitted": false,
"filesystem_permissions_verified": false,
"fingerprint": "d8432e17dc1b91ce4712ab656c14c0b5a0957c54700b027b22444dc3a4c19feb",
"format_version": 1,
"origin_port": 8199,
"repository": {
"branch": "main",
"url": "[email protected]:example/application.git"
},
"resource_conflicts_checked": false,
"retention": {
"automatic_deletion": false,
"keep_releases": 5
},
"root": "/opt/laravel-sites/example-absdev-net",
"secrets_required": true,
"site": "example-absdev-net",
"site_policy_fingerprint": "d271a3a3ed2cbda032f905558fe9ada653c380c74306fc714ebc594483a63042",
"static_policy_verified": true,
"status": "PLAN_ONLY"
}
=== REFERENCE INTEGRITY ===
SKIP: Private reference excluded from checkout
========================================
PASS: FRAMEWORK CI
UNIT TESTS AND STATIC VALIDATION ONLY
DATABASE INTEGRATION NOT EXECUTED
========================================
@@ -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);
@@ -0,0 +1,19 @@
set -euo pipefail
umask 077
test "$(hostname -s | tr A-Z a-z)" = absdev-ci
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=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/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"
(cd "$out" && sha256sum ./* > SHA256SUMS)
tar -czf - -C "$out" .
@@ -0,0 +1,2 @@
host=absdev-ci
revision=b0495d80f15848ad87783c143c77be44344132cf
+41 -12
View File
@@ -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=lambda: 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=lambda: 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),
)
@@ -543,5 +546,31 @@ class ApprovalStoreTests(unittest.TestCase):
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()
+18
View File
@@ -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)
+2 -1
View File
@@ -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=lambda: 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()