Initial ABSDEV deployment framework development preview
ABSDEV Framework CI / framework-validation (push) Canceled after 0s

This commit is contained in:
2026-11-26 11:35:28 +00:00
commit d6e2317016
76 changed files with 20260 additions and 0 deletions
+343
View File
@@ -0,0 +1,343 @@
import copy
import unittest
from datetime import datetime, timedelta, timezone
from core.approval import (
ApprovalError,
issue_approval,
verify_approval,
)
class ApprovalTests(unittest.TestCase):
def setUp(self):
self.now = datetime(
2026, 11, 26, 10, 0,
tzinfo=timezone.utc,
)
self.context = {
"site": "example-absdev-net",
"release": "2",
"revision": "a" * 40,
"provenance": "b" * 64,
"compatibility": "c" * 64,
"database_identity": "d" * 64,
"backup_sha256": "e" * 64,
"rehearsal_fingerprint": "f" * 64,
"pending_migrations": [
"2026_11_26_100000_create_products",
],
}
def issue(self, **options):
return issue_approval(
self.context,
approver="operator",
now=self.now,
**options,
)
def verify(self, approval=None, now=None):
if approval is None:
approval = self.issue()
if now is None:
now = self.now
return verify_approval(
approval,
self.context,
confirmation=approval["confirmation"],
now=now,
)
def test_valid_approval(self):
self.assertTrue(self.verify())
def test_approval_identifier(self):
self.assertRegex(
self.issue()["approval_id"],
r"^[a-f0-9]{32}$",
)
def test_unique_approval_identifier(self):
self.assertNotEqual(
self.issue()["approval_id"],
self.issue()["approval_id"],
)
def test_default_expiry(self):
approval = self.issue()
self.assertEqual(
datetime.fromisoformat(approval["expires_at"]),
self.now + timedelta(hours=24),
)
def test_custom_expiry(self):
approval = self.issue(ttl_hours=2)
self.assertEqual(
datetime.fromisoformat(approval["expires_at"]),
self.now + timedelta(hours=2),
)
def test_expired_approval_rejected(self):
approval = self.issue()
with self.assertRaises(ApprovalError):
self.verify(
approval,
self.now + timedelta(hours=25),
)
def test_exact_expiry_rejected(self):
approval = self.issue()
with self.assertRaises(ApprovalError):
self.verify(
approval,
self.now + timedelta(hours=24),
)
def test_future_approval_rejected(self):
approval = self.issue()
with self.assertRaises(ApprovalError):
self.verify(
approval,
self.now - timedelta(seconds=1),
)
def test_invalid_ttl_rejected(self):
for value in (0, -1, 25, True, "24"):
with self.subTest(value=value):
with self.assertRaises(ApprovalError):
self.issue(ttl_hours=value)
def test_naive_timestamp_rejected(self):
with self.assertRaises(ApprovalError):
issue_approval(
self.context,
approver="operator",
now=self.now.replace(tzinfo=None),
)
def test_changed_site_rejected(self):
approval = self.issue()
self.context["site"] = "different-site"
with self.assertRaises(ApprovalError):
self.verify(approval)
def test_changed_release_rejected(self):
approval = self.issue()
self.context["release"] = "3"
with self.assertRaises(ApprovalError):
self.verify(approval)
def test_changed_revision_rejected(self):
approval = self.issue()
self.context["revision"] = "0" * 40
with self.assertRaises(ApprovalError):
self.verify(approval)
def test_changed_provenance_rejected(self):
approval = self.issue()
self.context["provenance"] = "0" * 64
with self.assertRaises(ApprovalError):
self.verify(approval)
def test_changed_compatibility_rejected(self):
approval = self.issue()
self.context["compatibility"] = "0" * 64
with self.assertRaises(ApprovalError):
self.verify(approval)
def test_changed_database_identity_rejected(self):
approval = self.issue()
self.context["database_identity"] = "0" * 64
with self.assertRaises(ApprovalError):
self.verify(approval)
def test_changed_backup_rejected(self):
approval = self.issue()
self.context["backup_sha256"] = "0" * 64
with self.assertRaises(ApprovalError):
self.verify(approval)
def test_changed_rehearsal_rejected(self):
approval = self.issue()
self.context["rehearsal_fingerprint"] = "0" * 64
with self.assertRaises(ApprovalError):
self.verify(approval)
def test_changed_pending_migrations_rejected(self):
approval = self.issue()
self.context["pending_migrations"].append(
"2026_11_26_110000_create_orders"
)
with self.assertRaises(ApprovalError):
self.verify(approval)
def test_empty_pending_migrations_rejected(self):
self.context["pending_migrations"] = []
with self.assertRaises(ApprovalError):
self.issue()
def test_duplicate_migrations_rejected(self):
self.context["pending_migrations"] *= 2
with self.assertRaises(ApprovalError):
self.issue()
def test_unsafe_migration_name_rejected(self):
self.context["pending_migrations"] = [
"../outside"
]
with self.assertRaises(ApprovalError):
self.issue()
def test_invalid_release_rejected(self):
self.context["release"] = "../outside"
with self.assertRaises(ApprovalError):
self.issue()
def test_invalid_hash_rejected(self):
self.context["backup_sha256"] = "invalid"
with self.assertRaises(ApprovalError):
self.issue()
def test_missing_context_rejected(self):
del self.context["rehearsal_fingerprint"]
with self.assertRaises(ApprovalError):
self.issue()
def test_unknown_context_field_rejected(self):
self.context["unexpected"] = True
with self.assertRaises(ApprovalError):
self.issue()
def test_invalid_confirmation_rejected(self):
approval = self.issue()
with self.assertRaises(ApprovalError):
verify_approval(
approval,
self.context,
confirmation="INVALID",
now=self.now,
)
def test_modified_approval_rejected(self):
approval = self.issue()
approval["approver"] = "different-operator"
with self.assertRaises(ApprovalError):
self.verify(approval)
def test_invalid_approver_rejected(self):
with self.assertRaises(ApprovalError):
issue_approval(
self.context,
approver="",
now=self.now,
)
def test_context_not_mutated(self):
before = copy.deepcopy(self.context)
self.issue()
self.assertEqual(self.context, before)
def test_approval_context_is_independent(self):
approval = self.issue()
self.context["pending_migrations"].clear()
self.assertEqual(
len(approval["context"]["pending_migrations"]),
1,
)
def test_invalid_approval_structure_rejected(self):
approval = self.issue()
approval["unexpected"] = True
with self.assertRaises(ApprovalError):
self.verify(approval)
def test_confirmation_binds_approval_identity(self):
approval = self.issue()
self.assertEqual(
approval["confirmation"],
"MIGRATE-" + approval["approval_id"],
)
if __name__ == "__main__":
unittest.main()
+466
View File
@@ -0,0 +1,466 @@
import copy
import json
import os
import stat
import tempfile
import unittest
from datetime import datetime, timedelta, timezone
from pathlib import Path
from unittest.mock import patch
from core.approval import issue_approval
from core.approval_store import ApprovalStore, ApprovalStoreError
from core.locking import DeploymentLock, LockError
from core.rehearsal import create_rehearsal, approval_context
class ApprovalStoreTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.store = ApprovalStore(self.root)
self.now = datetime(
2026, 11, 26, 10, 0,
tzinfo=timezone.utc,
)
self.base = {
"site": "example-absdev-net",
"release": "2",
"revision": "a" * 40,
"provenance": "b" * 64,
"compatibility": "c" * 64,
"database_identity": "d" * 64,
"backup_sha256": "e" * 64,
"pending_migrations": [
"2026_11_26_100000_create_products",
],
}
self.execution = {
"driver": "mysql",
"source_database": "example_db",
"target_database": "isolated_restore_fixture",
"target_identity": "f" * 64,
"applied_migrations": list(
self.base["pending_migrations"]
),
"checks": {
"isolation_verified": True,
"backup_restored": True,
"migration_succeeded": True,
"migration_history_verified": True,
"application_verified": True,
"cleanup_verified": True,
},
}
self.rehearsal = create_rehearsal(
self.base,
self.execution,
completed_at=self.now,
)
self.context = approval_context(
self.rehearsal,
self.base,
now=self.now,
)
self.approval = issue_approval(
self.context,
approver="operator",
now=self.now,
)
self.identifier = self.approval["approval_id"]
def save(self):
return self.store.save(
self.approval,
self.context,
confirmation=self.approval["confirmation"],
now=self.now,
)
def consume(self, now=None, confirmation=None):
return self.store.consume(
self.identifier,
self.base,
self.rehearsal,
confirmation=(
self.approval["confirmation"]
if confirmation is None
else confirmation
),
now=self.now if now is None else now,
)
def test_save_approval(self):
self.assertEqual(self.save(), self.approval)
def test_persistent_approval(self):
self.save()
self.assertEqual(
ApprovalStore(self.root).load(self.identifier),
self.approval,
)
def test_duplicate_approval_rejected(self):
self.save()
with self.assertRaises(ApprovalStoreError):
self.save()
def test_missing_approval_rejected(self):
with self.assertRaises(ApprovalStoreError):
self.store.load(self.identifier)
def test_successful_consumption(self):
self.save()
result = self.consume()
self.assertEqual(
result["status"],
"CONSUMED",
)
def test_repeated_consumption_rejected(self):
self.save()
self.consume()
with self.assertRaises(ApprovalStoreError):
self.consume()
def test_consumption_survives_new_instance(self):
self.save()
self.consume()
self.store = ApprovalStore(self.root)
with self.assertRaises(ApprovalStoreError):
self.consume()
def test_wrong_confirmation_rejected(self):
self.save()
with self.assertRaises(ApprovalStoreError):
self.consume(confirmation="INVALID")
def test_wrong_confirmation_does_not_consume(self):
self.save()
with self.assertRaises(ApprovalStoreError):
self.consume(confirmation="INVALID")
self.assertFalse(
self.store.consumed_path(self.identifier).exists()
)
def test_expired_approval_rejected(self):
self.save()
with self.assertRaises(ApprovalStoreError):
self.consume(
now=self.now + timedelta(hours=24)
)
def test_expired_rehearsal_rejected(self):
self.approval = issue_approval(
self.context,
approver="operator",
now=self.now + timedelta(hours=20),
)
self.identifier = self.approval["approval_id"]
self.store.save(
self.approval,
self.context,
confirmation=self.approval["confirmation"],
now=self.now + timedelta(hours=20),
)
with self.assertRaises(ApprovalStoreError):
self.consume(
now=self.now + timedelta(hours=25)
)
def test_changed_context_rejected(self):
self.save()
self.base["backup_sha256"] = "0" * 64
with self.assertRaises(ApprovalStoreError):
self.consume()
def test_modified_rehearsal_rejected(self):
self.save()
self.rehearsal["execution"]["checks"][
"isolation_verified"
] = False
with self.assertRaises(ApprovalStoreError):
self.consume()
def test_modified_approval_rejected(self):
self.save()
path = self.store.approval_path(self.identifier)
record = json.loads(path.read_text())
record["approver"] = "different-operator"
path.write_text(json.dumps(record))
with self.assertRaises(ApprovalStoreError):
self.consume()
def test_corrupt_approval_rejected(self):
self.save()
self.store.approval_path(
self.identifier
).write_text("{invalid")
with self.assertRaises(ApprovalStoreError):
self.consume()
def test_duplicate_json_keys_rejected(self):
self.save()
self.store.approval_path(
self.identifier
).write_text('{"a":1,"a":2}')
with self.assertRaises(ApprovalStoreError):
self.store.load(self.identifier)
def test_approval_permissions(self):
self.save()
self.assertEqual(
stat.S_IMODE(
self.store.approval_path(
self.identifier
).stat().st_mode
),
0o600,
)
def test_consumption_permissions(self):
self.save()
self.consume()
self.assertEqual(
stat.S_IMODE(
self.store.consumed_path(
self.identifier
).stat().st_mode
),
0o600,
)
def test_invalid_identifier_rejected(self):
with self.assertRaises(ApprovalStoreError):
self.store.load("../outside")
def test_symlink_approval_rejected(self):
target = self.root / "external"
target.write_text("{}")
self.store.approval_path(
self.identifier
).symlink_to(target)
with self.assertRaises(ApprovalStoreError):
self.store.load(self.identifier)
def test_hardlinked_approval_rejected(self):
self.save()
os.link(
self.store.approval_path(self.identifier),
self.root / "duplicate",
)
with self.assertRaises(ApprovalStoreError):
self.store.load(self.identifier)
def test_insecure_approval_permissions(self):
self.save()
self.store.approval_path(
self.identifier
).chmod(0o644)
with self.assertRaises(ApprovalStoreError):
self.store.load(self.identifier)
def test_insecure_directory_rejected(self):
self.root.chmod(0o755)
with self.assertRaises(ApprovalStoreError):
ApprovalStore(self.root)
def test_existing_consumption_marker_blocks_execution(self):
self.save()
self.store.consumed_path(
self.identifier
).touch(mode=0o600)
with self.assertRaises(ApprovalStoreError):
self.consume()
def test_dangling_consumption_symlink_blocks_execution(self):
self.save()
self.store.consumed_path(
self.identifier
).symlink_to(self.root / "missing")
with self.assertRaises(ApprovalStoreError):
self.consume()
def test_concurrent_consumer_rejected(self):
self.save()
with DeploymentLock(
self.root / ".approval.lock"
):
with self.assertRaises(LockError):
self.consume()
def test_original_approval_preserved(self):
self.save()
self.consume()
self.assertEqual(
self.store.load(self.identifier),
self.approval,
)
def test_consumption_bound_to_approval(self):
self.save()
result = self.consume()
self.assertEqual(
result["approval_checksum"],
self.approval["checksum"],
)
def test_consumption_bound_to_rehearsal(self):
self.save()
result = self.consume()
self.assertEqual(
result["rehearsal_fingerprint"],
self.rehearsal["fingerprint"],
)
def test_publication_failure_blocks_consumption(self):
self.save()
with patch(
"core.approval_store.os.link",
side_effect=OSError("write failure"),
):
with self.assertRaises(ApprovalStoreError):
self.consume()
self.assertFalse(
self.store.consumed_path(self.identifier).exists()
)
def test_no_temporary_files_remaining(self):
self.save()
self.consume()
self.assertFalse(
list(self.root.glob(".approval-tmp-*"))
)
def test_input_not_mutated(self):
original = copy.deepcopy(self.approval)
self.save()
self.consume()
self.assertEqual(self.approval, original)
def test_consumption_record_persisted(self):
self.save()
result = self.consume()
self.assertEqual(
json.loads(
self.store.consumed_path(
self.identifier
).read_text()
),
result,
)
def test_expired_approval_cannot_be_saved(self):
with self.assertRaises(ApprovalStoreError):
self.store.save(
self.approval,
self.context,
confirmation=self.approval["confirmation"],
now=self.now + timedelta(hours=25),
)
if __name__ == "__main__":
unittest.main()
+313
View File
@@ -0,0 +1,313 @@
import json
import stat
import unittest
from unittest.mock import Mock, patch
import test_deployment
from core.archive import TransactionArchive, ArchiveError
from core.deployment import DeploymentError
from core.locking import DeploymentLock, LockError
class ArchiveTests(unittest.TestCase):
def setUp(self):
self.fixture = test_deployment.DeploymentTests()
self.addCleanup(self.fixture.doCleanups)
self.fixture.setUp()
self.root = self.fixture.root
self.journal = self.fixture.journal
self.transaction = self.fixture.deploy()
self.directory = self.root / "archives"
self.directory.mkdir(mode=0o700)
self.backup_verify = Mock(
return_value=dict(self.fixture.manifest)
)
self.health = Mock(
return_value={
"healthy": True,
"release": "2",
}
)
self.archive = TransactionArchive(
site="example-absdev-net",
directory=self.directory,
lock_path=self.root / ".deployment.lock",
journal=self.journal,
releases=self.fixture.releases,
provenance=self.fixture.provenance,
backup_evidence=self.fixture.evidence,
backup_verify=self.backup_verify,
health_probe=self.health,
)
def execute(self):
plan = self.archive.plan()
return self.archive.execute(
confirmation=plan["confirmation"],
fingerprint=plan["fingerprint"],
)
def test_valid_archive_plan(self):
self.assertEqual(
self.archive.plan()["status"],
"ARCHIVE_READY",
)
def test_plan_is_read_only(self):
before = self.journal.load()
self.archive.plan()
self.assertEqual(self.journal.load(), before)
self.assertEqual(list(self.directory.iterdir()), [])
def test_successful_archive(self):
result = self.execute()
self.assertEqual(result["status"], "ARCHIVED")
self.assertIsNone(self.journal.load())
def test_original_transaction_preserved(self):
result = self.execute()
self.assertEqual(
result["transaction"],
self.transaction,
)
def test_backup_evidence_preserved(self):
result = self.execute()
self.assertEqual(
result["backup_evidence"]["backup"],
self.fixture.manifest,
)
self.assertTrue(
self.fixture.evidence.path(
self.transaction["transaction_id"]
).exists()
)
def test_archive_persisted(self):
result = self.execute()
self.assertEqual(
self.archive.load(
self.transaction["transaction_id"]
),
result,
)
def test_archive_permissions(self):
self.execute()
path = self.archive.path(
self.transaction["transaction_id"]
)
self.assertEqual(
stat.S_IMODE(path.stat().st_mode),
0o600,
)
def test_wrong_confirmation_rejected(self):
plan = self.archive.plan()
with self.assertRaises(ArchiveError):
self.archive.execute(
confirmation="INVALID",
fingerprint=plan["fingerprint"],
)
self.assertIsNotNone(self.journal.load())
def test_wrong_fingerprint_rejected(self):
plan = self.archive.plan()
with self.assertRaises(ArchiveError):
self.archive.execute(
confirmation=plan["confirmation"],
fingerprint="0" * 64,
)
def test_wrong_active_release_rejected(self):
self.fixture.releases.activate("1")
with self.assertRaises(ArchiveError):
self.archive.plan()
def test_unhealthy_application_rejected(self):
self.health.return_value["healthy"] = False
with self.assertRaises(ArchiveError):
self.archive.plan()
def test_wrong_health_release_rejected(self):
self.health.return_value["release"] = "1"
with self.assertRaises(ArchiveError):
self.archive.plan()
def test_missing_backup_evidence_rejected(self):
self.fixture.evidence.path(
self.transaction["transaction_id"]
).unlink()
with self.assertRaises(ArchiveError):
self.archive.plan()
def test_changed_backup_rejected(self):
self.backup_verify.return_value["sha256"] = "0" * 64
with self.assertRaises(ArchiveError):
self.archive.plan()
def test_changed_release_provenance_rejected(self):
self.fixture.new["fingerprint"] = "0" * 64
with self.assertRaises(ArchiveError):
self.archive.plan()
def test_concurrent_operation_rejected(self):
with DeploymentLock(
self.root / ".deployment.lock"
):
with self.assertRaises(LockError):
self.archive.plan()
def test_publication_failure_preserves_journal(self):
plan = self.archive.plan()
with patch(
"core.archive.os.link",
side_effect=OSError("publication failed"),
):
with self.assertRaises(ArchiveError):
self.archive.execute(
confirmation=plan["confirmation"],
fingerprint=plan["fingerprint"],
)
self.assertEqual(
self.journal.load(),
self.transaction,
)
def test_existing_archive_rejected(self):
self.archive.path(
self.transaction["transaction_id"]
).touch(mode=0o600)
with self.assertRaises(ArchiveError):
self.execute()
self.assertIsNotNone(self.journal.load())
def test_corrupted_archive_rejected(self):
self.execute()
self.archive.path(
self.transaction["transaction_id"]
).write_text("{invalid")
with self.assertRaises(ArchiveError):
self.archive.load(
self.transaction["transaction_id"]
)
def test_modified_archive_rejected(self):
self.execute()
path = self.archive.path(
self.transaction["transaction_id"]
)
data = json.loads(path.read_text())
data["transaction"]["candidate"] = "99"
path.write_text(json.dumps(data))
with self.assertRaises(ArchiveError):
self.archive.load(
self.transaction["transaction_id"]
)
def test_invalid_archive_identifier_rejected(self):
with self.assertRaises(ArchiveError):
self.archive.load("../outside")
def test_insecure_directory_rejected(self):
self.directory.chmod(0o777)
with self.assertRaises(ArchiveError):
self.archive.plan()
def test_missing_transaction_rejected(self):
self.execute()
with self.assertRaises(ArchiveError):
self.archive.plan()
def test_wrong_site_rejected(self):
self.archive.site = "different-site"
with self.assertRaises(ArchiveError):
self.archive.plan()
def test_no_database_restoration(self):
result = self.execute()
self.assertFalse(result["database_restored"])
def test_all_release_directories_preserved(self):
self.execute()
self.assertEqual(
self.fixture.releases.inventory(),
["1", "2"],
)
def test_failed_transaction_not_archived(self):
self.journal.path.unlink()
tx = self.journal.create(
"example-absdev-net",
"1",
"2",
"b" * 40,
self.fixture.new["fingerprint"],
)
self.journal.transition(
tx["transaction_id"],
"PREPARED",
"FAILED",
)
with self.assertRaises(ArchiveError):
self.archive.plan()
def test_new_deployment_no_longer_blocked_by_journal(self):
self.execute()
self.assertIsNone(self.journal.load())
self.fixture.controller.operation_guard.require_clear()
self.assertEqual(
self.fixture.releases.current(),
"2",
)
if __name__ == "__main__":
unittest.main()
+399
View File
@@ -0,0 +1,399 @@
import json
import os
import tempfile
import unittest
from pathlib import Path
from core.database import get_adapter
from core.backup import (
BackupError,
BackupEngine,
)
class BackupEngineTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name) / "backups"
self.root.mkdir(mode=0o700)
self.config = json.loads(
Path("config/site.example.json").read_text()
)
self.adapter = get_adapter(self.config)
self.payload = b"-- SQL backup fixture\nSELECT 1;\n"
self.commands = []
self.engine = BackupEngine(
self.adapter,
self.root,
self.runner,
)
def runner(self, command, output):
self.commands.append(command)
if command == self.adapter.identity_command():
output.write(
b"example_db\texample_app@%\t"
b"11111111-2222-3333-4444-555555555555\n"
)
elif command == self.adapter.backup_command():
output.write(self.payload)
else:
raise AssertionError("Unexpected command")
def create(self):
return self.engine.create()
def test_mysql_backup_created(self):
path = self.create()
self.assertTrue(path.is_dir())
self.assertTrue((path / "database.sql").is_file())
def test_backup_contents_preserved(self):
path = self.create()
self.assertEqual(
(path / "database.sql").read_bytes(),
self.payload,
)
def test_backup_checksum_verified(self):
path = self.create()
result = self.engine.verify(path)
self.assertEqual(
result["bytes"],
len(self.payload),
)
def test_manifest_created(self):
path = self.create()
self.assertTrue(
(path / "manifest.json").is_file()
)
def test_manifest_database_identity(self):
result = self.engine.verify(self.create())
self.assertEqual(
result["database"],
"example_db",
)
self.assertEqual(
result["driver"],
"mysql",
)
def test_unique_backup_names(self):
self.assertNotEqual(
self.create(),
self.create(),
)
def test_directory_permissions(self):
path = self.create()
self.assertEqual(
path.stat().st_mode & 0o777,
0o700,
)
def test_backup_permissions(self):
path = self.create()
self.assertEqual(
(path / "database.sql").stat().st_mode
& 0o777,
0o600,
)
def test_manifest_permissions(self):
path = self.create()
self.assertEqual(
(path / "manifest.json").stat().st_mode
& 0o777,
0o600,
)
def test_corrupted_backup_rejected(self):
path = self.create()
(path / "database.sql").write_bytes(b"corrupt")
with self.assertRaises(BackupError):
self.engine.verify(path)
def test_missing_backup_rejected(self):
path = self.create()
(path / "database.sql").unlink()
with self.assertRaises(BackupError):
self.engine.verify(path)
def test_missing_manifest_rejected(self):
path = self.create()
(path / "manifest.json").unlink()
with self.assertRaises(BackupError):
self.engine.verify(path)
def test_empty_backup_rejected(self):
self.payload = b""
with self.assertRaises(BackupError):
self.create()
self.assertEqual(list(self.root.iterdir()), [])
def test_symlink_backup_rejected(self):
path = self.create()
backup = path / "database.sql"
backup.unlink()
backup.symlink_to("/etc/passwd")
with self.assertRaises(BackupError):
self.engine.verify(path)
def test_symlink_manifest_rejected(self):
path = self.create()
manifest = path / "manifest.json"
manifest.unlink()
manifest.symlink_to("/etc/passwd")
with self.assertRaises(BackupError):
self.engine.verify(path)
def test_wrong_database_rejected(self):
def wrong_identity(command, output):
output.write(
b"another_db\texample_app@%\tserver\n"
)
self.engine.runner = wrong_identity
with self.assertRaises(BackupError):
self.create()
self.assertEqual(list(self.root.iterdir()), [])
def test_wrong_account_rejected(self):
def wrong_identity(command, output):
output.write(
b"example_db\troot@localhost\tserver\n"
)
self.engine.runner = wrong_identity
with self.assertRaises(BackupError):
self.create()
def test_runner_failure_cleaned_up(self):
def failing_runner(command, output):
if command == self.adapter.identity_command():
self.runner(command, output)
return
output.write(b"partial output")
raise RuntimeError("Simulated database failure")
self.engine.runner = failing_runner
with self.assertRaises(BackupError):
self.create()
self.assertEqual(list(self.root.iterdir()), [])
def test_insecure_directory_rejected(self):
self.root.chmod(0o777)
with self.assertRaises(BackupError):
self.create()
def test_unexpected_file_rejected(self):
path = self.create()
(path / "unexpected").touch()
with self.assertRaises(BackupError):
self.engine.verify(path)
def test_external_directory_rejected(self):
with self.assertRaises(BackupError):
self.engine.verify(Path(self.temp.name))
def test_hardlinked_backup_rejected(self):
path = self.create()
os.link(
path / "database.sql",
self.root / "external-link",
)
with self.assertRaises(BackupError):
self.engine.verify(path)
def test_manifest_path_traversal_rejected(self):
path = self.create()
manifest = path / "manifest.json"
data = json.loads(manifest.read_text())
data["filename"] = "../../etc/passwd"
manifest.write_text(json.dumps(data))
with self.assertRaises(BackupError):
self.engine.verify(path)
def test_identity_checked_after_backup(self):
self.create()
self.assertEqual(
self.commands,
[
self.adapter.identity_command(),
self.adapter.backup_command(),
self.adapter.identity_command(),
],
)
def test_database_identity_change_rejected(self):
calls = 0
def changing_identity(command, output):
nonlocal calls
if command == self.adapter.identity_command():
calls += 1
output.write(
f"example_db\texample_app@%\t"
f"server-{calls}\n".encode()
)
else:
output.write(self.payload)
self.engine.runner = changing_identity
with self.assertRaises(BackupError):
self.create()
self.assertEqual(list(self.root.iterdir()), [])
def test_postgresql_backup_created(self):
self.config["database"].update({
"driver": "pgsql",
"container": "platform-postgres",
"host": "platform-postgres",
"port": 5432,
})
adapter = get_adapter(self.config)
def runner(command, output):
if command == adapter.identity_command():
output.write(b"example_db|example_app\n")
else:
output.write(b"PGDMP simulated archive")
engine = BackupEngine(
adapter,
self.root,
runner,
)
path = engine.create()
self.assertTrue(
(path / "database.dump").is_file()
)
self.assertEqual(
engine.verify(path)["driver"],
"pgsql",
)
if __name__ == "__main__":
unittest.main()
+328
View File
@@ -0,0 +1,328 @@
import json
import os
import stat
import tempfile
import unittest
from pathlib import Path
from core.backup_evidence import (
BackupEvidence,
EvidenceError,
)
class BackupEvidenceTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.store = BackupEvidence(self.root)
self.transaction = "a" * 32
self.manifest = {
"backup_id": "backup-example",
"driver": "mysql",
"database": "example_db",
"username": "example_app",
"container": "example-mysql",
"identity": "example-server",
"filename": "database.sql",
"sha256": "b" * 64,
"bytes": 1024,
}
def create(self):
return self.store.create(
self.transaction,
self.manifest,
)
def test_create_evidence(self):
result = self.create()
self.assertEqual(
result["transaction_id"],
self.transaction,
)
def test_evidence_persisted(self):
original = self.create()
self.assertEqual(
self.store.load(self.transaction),
original,
)
def test_checksum_preserved(self):
self.assertEqual(
self.create()["backup"]["sha256"],
"b" * 64,
)
def test_database_identity_preserved(self):
self.assertEqual(
self.create()["backup"]["identity"],
"example-server",
)
def test_backup_identifier_preserved(self):
self.assertEqual(
self.create()["backup"]["backup_id"],
"backup-example",
)
def test_duplicate_evidence_rejected(self):
self.create()
with self.assertRaises(EvidenceError):
self.create()
def test_missing_evidence_rejected(self):
with self.assertRaises(EvidenceError):
self.store.load(self.transaction)
def test_invalid_transaction_rejected(self):
with self.assertRaises(EvidenceError):
self.store.create(
"../outside",
self.manifest,
)
def test_invalid_checksum_rejected(self):
self.manifest["sha256"] = "invalid"
with self.assertRaises(EvidenceError):
self.create()
def test_zero_size_rejected(self):
self.manifest["bytes"] = 0
with self.assertRaises(EvidenceError):
self.create()
def test_boolean_size_rejected(self):
self.manifest["bytes"] = True
with self.assertRaises(EvidenceError):
self.create()
def test_unknown_driver_rejected(self):
self.manifest["driver"] = "unknown"
with self.assertRaises(EvidenceError):
self.create()
def test_postgresql_supported(self):
self.manifest["driver"] = "postgresql"
self.manifest["filename"] = "database.dump"
result = self.create()
self.assertEqual(
result["backup"]["driver"],
"postgresql",
)
def test_wrong_extension_rejected(self):
self.manifest["filename"] = "database.dump"
with self.assertRaises(EvidenceError):
self.create()
def test_unsafe_filename_rejected(self):
self.manifest["filename"] = "../database.sql"
with self.assertRaises(EvidenceError):
self.create()
def test_missing_manifest_field_rejected(self):
del self.manifest["database"]
with self.assertRaises(EvidenceError):
self.create()
def test_empty_identity_rejected(self):
self.manifest["identity"] = ""
with self.assertRaises(EvidenceError):
self.create()
def test_permissions(self):
self.create()
path = self.store.path(self.transaction)
self.assertEqual(
stat.S_IMODE(path.stat().st_mode),
0o600,
)
def test_symlink_rejected(self):
target = self.root / "external"
target.write_text("{}")
self.store.path(
self.transaction
).symlink_to(target)
with self.assertRaises(EvidenceError):
self.store.load(self.transaction)
def test_hardlink_rejected(self):
self.create()
os.link(
self.store.path(self.transaction),
self.root / "duplicate",
)
with self.assertRaises(EvidenceError):
self.store.load(self.transaction)
def test_corrupted_evidence_rejected(self):
self.create()
self.store.path(
self.transaction
).write_text("{invalid")
with self.assertRaises(EvidenceError):
self.store.load(self.transaction)
def test_modified_checksum_rejected(self):
self.create()
path = self.store.path(self.transaction)
data = json.loads(path.read_text())
data["backup"]["sha256"] = "0" * 64
path.write_text(json.dumps(data))
with self.assertRaises(EvidenceError):
self.store.load(self.transaction)
def test_wrong_transaction_binding_rejected(self):
self.create()
source = self.store.path(self.transaction)
target = self.store.path("c" * 32)
target.write_bytes(source.read_bytes())
target.chmod(0o600)
with self.assertRaises(EvidenceError):
self.store.load("c" * 32)
def test_insecure_permissions_rejected(self):
self.create()
self.store.path(
self.transaction
).chmod(0o644)
with self.assertRaises(EvidenceError):
self.store.load(self.transaction)
def test_insecure_directory_rejected(self):
self.root.chmod(0o777)
with self.assertRaises(EvidenceError):
BackupEvidence(self.root)
def test_duplicate_json_keys_rejected(self):
self.create()
self.store.path(
self.transaction
).write_text(
'{"format_version":1,"format_version":2}'
)
with self.assertRaises(EvidenceError):
self.store.load(self.transaction)
def test_manifest_not_mutated(self):
before = dict(self.manifest)
self.create()
self.assertEqual(self.manifest, before)
def test_independent_transactions(self):
self.create()
self.store.create(
"c" * 32,
self.manifest,
)
self.assertEqual(
self.store.load("c" * 32)["transaction_id"],
"c" * 32,
)
def test_symlink_backup_identifier_rejected(self):
self.manifest["backup_id"] = "../outside"
with self.assertRaises(EvidenceError):
self.create()
def test_unknown_manifest_fields_not_copied(self):
self.manifest["password"] = "private-secret"
result = self.create()
self.assertNotIn(
"password",
result["backup"],
)
self.assertNotIn(
"private-secret",
self.store.path(
self.transaction
).read_text(),
)
if __name__ == "__main__":
unittest.main()
+118
View File
@@ -0,0 +1,118 @@
import json
import subprocess
import sys
import unittest
from pathlib import Path
from core.inspection_cli import capabilities
ROOT = Path(__file__).resolve().parents[2]
class CIPolicyTests(unittest.TestCase):
def test_ci_script_exists(self):
self.assertTrue(
(ROOT / "scripts/ci-check.sh").is_file()
)
def test_workflow_exists(self):
self.assertTrue(
(
ROOT / ".gitea/workflows/framework-ci.yaml"
).is_file()
)
def test_ci_script_shell_syntax(self):
result = subprocess.run(
[
"bash",
"-n",
str(ROOT / "scripts/ci-check.sh"),
],
capture_output=True,
timeout=10,
)
self.assertEqual(result.returncode, 0)
def test_ci_runs_unit_tests(self):
source = (
ROOT / "scripts/ci-check.sh"
).read_text()
self.assertIn(
"unittest discover -s tests/unit",
source,
)
def test_database_integration_disabled(self):
source = (
ROOT / "scripts/ci-check.sh"
).read_text()
self.assertIn(
"export ABSDEV_INTEGRATION_TESTS=0",
source,
)
def test_workflow_no_deployment_secrets(self):
source = (
ROOT / ".gitea/workflows/framework-ci.yaml"
).read_text()
self.assertNotIn("secrets.", source)
def test_workflow_no_privileged_execution(self):
source = (
ROOT / ".gitea/workflows/framework-ci.yaml"
).read_text()
self.assertNotIn("privileged: true", source)
self.assertNotIn("sudo ", source)
def test_production_deployment_disabled(self):
self.assertFalse(
capabilities()["deployment_execution_enabled"]
)
def test_production_migration_disabled(self):
self.assertFalse(
capabilities()["migration_execution_enabled"]
)
def test_provisioning_disabled(self):
self.assertFalse(
capabilities()["provisioning_execution_enabled"]
)
def test_database_restore_disabled(self):
self.assertFalse(
capabilities()["database_restore_enabled"]
)
def test_permanent_deletion_disabled(self):
self.assertFalse(
capabilities()["permanent_deletion_enabled"]
)
def test_production_ready_remains_false(self):
self.assertFalse(
capabilities()["production_ready"]
)
def test_ci_calls_shared_verification_script(self):
source = (
ROOT / ".gitea/workflows/framework-ci.yaml"
).read_text()
self.assertIn(
"bash scripts/ci-check.sh",
source,
)
if __name__ == "__main__":
unittest.main()
+392
View File
@@ -0,0 +1,392 @@
import copy
import unittest
from core.compatibility import (
CompatibilityError,
compare_migrations,
require_compatible,
provenance_fingerprint,
)
def provenance(revision="a" * 40, migrations=None):
if migrations is None:
migrations = {
"database/migrations/0001_users.php": "a" * 64,
"database/migrations/0002_orders.php": "b" * 64,
}
data = {
"format_version": 1,
"revision": revision,
"migrations": migrations,
"dependencies": {
"composer.json": "c" * 64,
"composer.lock": "d" * 64,
"package.json": "e" * 64,
"package-lock.json": "f" * 64,
},
}
data["fingerprint"] = provenance_fingerprint(data)
return data
class CompatibilityTests(unittest.TestCase):
def setUp(self):
self.previous = provenance()
self.candidate = provenance("b" * 40)
def refresh(self, data):
data["fingerprint"] = provenance_fingerprint(data)
def compare(self):
return compare_migrations(
self.previous,
self.candidate,
)
def test_identical_migrations_compatible(self):
self.assertTrue(
self.compare()["compatible_without_migrations"]
)
def test_same_revision(self):
self.candidate = copy.deepcopy(self.previous)
self.assertTrue(self.compare()["same_revision"])
def test_different_revision(self):
self.assertFalse(self.compare()["same_revision"])
def test_added_migration(self):
name = "database/migrations/0003_products.php"
self.candidate["migrations"][name] = "c" * 64
self.refresh(self.candidate)
result = self.compare()
self.assertEqual(result["added"], [name])
self.assertFalse(
result["compatible_without_migrations"]
)
def test_removed_migration(self):
name = "database/migrations/0002_orders.php"
del self.candidate["migrations"][name]
self.refresh(self.candidate)
result = self.compare()
self.assertEqual(result["removed"], [name])
self.assertFalse(
result["compatible_without_migrations"]
)
def test_modified_migration(self):
name = "database/migrations/0001_users.php"
self.candidate["migrations"][name] = "d" * 64
self.refresh(self.candidate)
result = self.compare()
self.assertEqual(result["modified"], [name])
self.assertFalse(
result["compatible_without_migrations"]
)
def test_renamed_migration(self):
old = "database/migrations/0001_users.php"
new = "database/migrations/0003_users.php"
self.candidate["migrations"][new] = (
self.candidate["migrations"].pop(old)
)
self.refresh(self.candidate)
result = self.compare()
self.assertEqual(result["added"], [new])
self.assertEqual(result["removed"], [old])
self.assertFalse(
result["compatible_without_migrations"]
)
def test_dependency_changes_do_not_change_migrations(self):
self.candidate["dependencies"]["composer.lock"] = (
"1" * 64
)
self.refresh(self.candidate)
self.assertTrue(
self.compare()["compatible_without_migrations"]
)
def test_previous_migration_count(self):
self.assertEqual(
self.compare()["previous_count"],
2,
)
def test_candidate_migration_count(self):
self.assertEqual(
self.compare()["candidate_count"],
2,
)
def test_unchanged_migration_count(self):
self.assertEqual(
self.compare()["unchanged_count"],
2,
)
def test_empty_migrations(self):
self.previous = provenance(migrations={})
self.candidate = provenance(
"b" * 40,
migrations={},
)
self.assertTrue(
self.compare()["compatible_without_migrations"]
)
def test_invalid_fingerprint_rejected(self):
self.candidate["fingerprint"] = "0" * 64
with self.assertRaises(CompatibilityError):
self.compare()
def test_modified_evidence_rejected(self):
self.candidate["migrations"][
"database/migrations/0001_users.php"
] = "0" * 64
with self.assertRaises(CompatibilityError):
self.compare()
def test_missing_revision_rejected(self):
del self.candidate["revision"]
with self.assertRaises(CompatibilityError):
self.compare()
def test_invalid_revision_rejected(self):
self.candidate["revision"] = "invalid"
self.refresh(self.candidate)
with self.assertRaises(CompatibilityError):
self.compare()
def test_invalid_migration_hash_rejected(self):
self.candidate["migrations"][
"database/migrations/0001_users.php"
] = "invalid"
self.refresh(self.candidate)
with self.assertRaises(CompatibilityError):
self.compare()
def test_migration_path_traversal_rejected(self):
self.candidate["migrations"][
"database/migrations/../../outside.php"
] = "a" * 64
self.refresh(self.candidate)
with self.assertRaises(CompatibilityError):
self.compare()
def test_absolute_migration_path_rejected(self):
self.candidate["migrations"][
"/tmp/migration.php"
] = "a" * 64
self.refresh(self.candidate)
with self.assertRaises(CompatibilityError):
self.compare()
def test_missing_dependencies_rejected(self):
del self.candidate["dependencies"]["composer.lock"]
self.refresh(self.candidate)
with self.assertRaises(CompatibilityError):
self.compare()
def test_invalid_dependency_hash_rejected(self):
self.candidate["dependencies"]["composer.json"] = (
"invalid"
)
self.refresh(self.candidate)
with self.assertRaises(CompatibilityError):
self.compare()
def test_unknown_field_rejected(self):
self.candidate["unexpected"] = True
self.refresh(self.candidate)
with self.assertRaises(CompatibilityError):
self.compare()
def test_invalid_format_version_rejected(self):
self.candidate["format_version"] = 2
self.refresh(self.candidate)
with self.assertRaises(CompatibilityError):
self.compare()
def test_boolean_format_version_rejected(self):
self.candidate["format_version"] = True
self.refresh(self.candidate)
with self.assertRaises(CompatibilityError):
self.compare()
def test_require_compatible_success(self):
result = require_compatible(
self.previous,
self.candidate,
)
self.assertTrue(
result["compatible_without_migrations"]
)
def test_require_compatible_rejects_changes(self):
self.candidate["migrations"] = {}
self.refresh(self.candidate)
with self.assertRaises(CompatibilityError):
require_compatible(
self.previous,
self.candidate,
)
def test_deterministic_report(self):
self.assertEqual(
self.compare(),
self.compare(),
)
def test_no_input_mutation(self):
previous = copy.deepcopy(self.previous)
candidate = copy.deepcopy(self.candidate)
self.compare()
self.assertEqual(self.previous, previous)
self.assertEqual(self.candidate, candidate)
def test_report_binds_provenance_fingerprints(self):
result = self.compare()
self.assertEqual(
result["previous_fingerprint"],
self.previous["fingerprint"],
)
self.assertEqual(
result["candidate_fingerprint"],
self.candidate["fingerprint"],
)
def test_same_revision_different_content_rejected(self):
self.candidate["revision"] = self.previous["revision"]
self.candidate["migrations"][
"database/migrations/0001_users.php"
] = "0" * 64
self.refresh(self.candidate)
with self.assertRaises(CompatibilityError):
self.compare()
def test_reverse_comparison_rejects_rollback(self):
self.candidate["migrations"][
"database/migrations/0003_products.php"
] = "a" * 64
self.refresh(self.candidate)
result = compare_migrations(
self.candidate,
self.previous,
)
self.assertFalse(
result["compatible_without_migrations"]
)
def test_invalid_evidence_type_rejected(self):
self.candidate = None
with self.assertRaises(CompatibilityError):
self.compare()
if __name__ == "__main__":
unittest.main()
+282
View File
@@ -0,0 +1,282 @@
import copy
import json
import tempfile
import unittest
from pathlib import Path
from core.configuration import (
ConfigurationError,
validate_config,
load_config,
)
def example():
return {
"schema_version": 1,
"site": {
"identifier": "example-absdev-net",
"domain": "example.absdev.net",
"root": "/opt/laravel-sites/example-absdev-net",
"origin_port": 8199,
},
"repository": {
"url": "[email protected]:example/application.git",
"branch": "main",
},
"database": {
"driver": "mysql",
"container": "platform-mysql",
"host": "platform-mysql",
"port": 3306,
"name": "example_db",
"username": "example_app",
},
"docker": {
"project": "site-example-absdev-net",
"application_path": "/var/www/html",
"php_service": "php",
"web_service": "web",
"queue_service": "queue",
"scheduler_service": "scheduler",
"backend_network": "laravel_backend",
"proxy_network": "laravel_proxy",
},
"retention": {
"keep_releases": 5,
"automatic_deletion": False,
},
"migration": {
"require_approval": True,
"require_rehearsal": True,
"approval_ttl_hours": 24,
},
"backup": {
"required": True,
"verify_checksum": True,
},
"health": {
"endpoints": ["/", "/up", "/login"],
"timeout_seconds": 30,
},
}
class ConfigurationTests(unittest.TestCase):
def invalid(self, section, key, value):
data = example()
data[section][key] = value
with self.assertRaises(ConfigurationError):
validate_config(data)
def test_valid_mysql_configuration(self):
self.assertEqual(
validate_config(example())["database"]["driver"],
"mysql",
)
def test_valid_postgresql_configuration(self):
data = example()
data["database"].update({
"driver": "pgsql",
"port": 5432,
"host": "platform-postgres",
"container": "platform-postgres",
})
self.assertEqual(
validate_config(data)["database"]["driver"],
"pgsql",
)
def test_invalid_site_identifier(self):
self.invalid("site", "identifier", "../other")
def test_invalid_domain(self):
self.invalid("site", "domain", "https://example.net")
def test_invalid_domain_labels(self):
self.invalid("site", "domain", "a..example.net")
def test_invalid_port(self):
self.invalid("site", "origin_port", 65536)
def test_boolean_port_rejected(self):
self.invalid("site", "origin_port", True)
def test_relative_site_path(self):
self.invalid("site", "root", "../example")
def test_parent_path_rejected(self):
self.invalid(
"site", "root",
"/opt/laravel-sites/../example",
)
def test_root_directory_rejected(self):
self.invalid("site", "root", "/")
def test_invalid_database_driver(self):
self.invalid("database", "driver", "unknown")
def test_invalid_database_name(self):
self.invalid("database", "name", "db; DROP DATABASE x")
def test_invalid_database_username(self):
self.invalid("database", "username", "root; command")
def test_invalid_database_port(self):
self.invalid("database", "port", 0)
def test_database_password_rejected(self):
self.invalid("database", "password", "example-secret")
def test_unknown_field_rejected(self):
self.invalid("site", "unexpected", "value")
def test_unknown_section_rejected(self):
data = example()
data["unknown"] = {}
with self.assertRaises(ConfigurationError):
validate_config(data)
def test_missing_section_rejected(self):
data = example()
del data["database"]
with self.assertRaises(ConfigurationError):
validate_config(data)
def test_missing_field_rejected(self):
data = example()
del data["site"]["domain"]
with self.assertRaises(ConfigurationError):
validate_config(data)
def test_invalid_branch(self):
self.invalid("repository", "branch", "main; command")
def test_invalid_branch_component(self):
self.invalid("repository", "branch", "feature/.hidden")
def test_invalid_repository(self):
self.invalid("repository", "url", "file:///etc")
def test_embedded_credentials_rejected(self):
self.invalid(
"repository",
"url",
"https://user:[email protected]/app.git",
)
def test_invalid_service(self):
self.invalid("docker", "php_service", "../php")
def test_duplicate_service_rejected(self):
self.invalid("docker", "web_service", "php")
def test_invalid_network(self):
self.invalid("docker", "backend_network", "net; command")
def test_invalid_retention_count(self):
self.invalid("retention", "keep_releases", 0)
def test_destructive_cleanup_rejected(self):
self.invalid("retention", "automatic_deletion", True)
def test_migration_approval_required(self):
self.invalid("migration", "require_approval", False)
def test_rehearsal_required(self):
self.invalid("migration", "require_rehearsal", False)
def test_invalid_approval_ttl(self):
self.invalid("migration", "approval_ttl_hours", 0)
def test_backup_required(self):
self.invalid("backup", "required", False)
def test_checksum_required(self):
self.invalid("backup", "verify_checksum", False)
def test_invalid_health_endpoint(self):
self.invalid("health", "endpoints", ["https://other.net"])
def test_external_health_endpoint_rejected(self):
self.invalid("health", "endpoints", ["//other.net"])
def test_invalid_timeout(self):
self.invalid("health", "timeout_seconds", 0)
def test_invalid_schema_version(self):
data = example()
data["schema_version"] = 999
with self.assertRaises(ConfigurationError):
validate_config(data)
def test_no_input_mutation(self):
data = example()
original = copy.deepcopy(data)
result = validate_config(data)
result["site"]["domain"] = "changed.invalid"
self.assertEqual(data, original)
def test_load_configuration_file(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "site.json"
path.write_text(json.dumps(example()))
self.assertEqual(
load_config(path)["schema_version"], 1
)
def test_invalid_json_rejected(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "site.json"
path.write_text("{invalid")
with self.assertRaises(ConfigurationError):
load_config(path)
def test_duplicate_json_keys_rejected(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "site.json"
path.write_text(
'{"schema_version":1,"schema_version":2}'
)
with self.assertRaises(ConfigurationError):
load_config(path)
def test_missing_file_rejected(self):
with tempfile.TemporaryDirectory() as directory:
with self.assertRaises(ConfigurationError):
load_config(Path(directory) / "missing.json")
if __name__ == "__main__":
unittest.main()
+363
View File
@@ -0,0 +1,363 @@
import json
import unittest
from pathlib import Path
from core.database import (
DatabaseError,
DatabaseAdapter,
get_adapter,
)
from adapters.mysql.adapter import MySQLAdapter
from adapters.postgresql.adapter import PostgreSQLAdapter
def config(driver="mysql"):
data = json.loads(
Path("config/site.example.json").read_text()
)
if driver == "pgsql":
data["database"].update({
"driver": "pgsql",
"container": "platform-postgres",
"host": "platform-postgres",
"port": 5432,
})
return data
class DatabaseAdapterTests(unittest.TestCase):
def test_mysql_factory(self):
self.assertIsInstance(
get_adapter(config()),
MySQLAdapter,
)
def test_postgresql_factory(self):
self.assertIsInstance(
get_adapter(config("pgsql")),
PostgreSQLAdapter,
)
def test_mysql_common_interface(self):
self.assertIsInstance(
get_adapter(config()),
DatabaseAdapter,
)
def test_postgresql_common_interface(self):
self.assertIsInstance(
get_adapter(config("pgsql")),
DatabaseAdapter,
)
def test_mysql_connectivity(self):
command = get_adapter(config()).ping_command()
self.assertIn("mysql", command)
self.assertIn("SELECT 1", command)
def test_postgresql_connectivity(self):
command = get_adapter(
config("pgsql")
).ping_command()
self.assertIn("psql", command)
self.assertIn("SELECT 1", command)
def test_mysql_backup(self):
command = get_adapter(config()).backup_command()
self.assertIn("mysqldump", command)
self.assertIn("--single-transaction", command)
self.assertIn("--quick", command)
self.assertIn("--no-tablespaces", command)
def test_postgresql_backup(self):
command = get_adapter(
config("pgsql")
).backup_command()
self.assertIn("pg_dump", command)
self.assertIn("--format=custom", command)
self.assertIn("--no-owner", command)
self.assertIn("--no-privileges", command)
def test_mysql_container_identity(self):
command = get_adapter(config()).backup_command()
self.assertEqual(
command[:3],
["docker", "exec", "platform-mysql"],
)
def test_postgresql_container_identity(self):
command = get_adapter(
config("pgsql")
).backup_command()
self.assertEqual(
command[:3],
["docker", "exec", "platform-postgres"],
)
def test_mysql_version(self):
self.assertIn(
"SELECT VERSION()",
get_adapter(config()).version_command(),
)
def test_postgresql_version(self):
self.assertIn(
"SHOW server_version",
get_adapter(
config("pgsql")
).version_command(),
)
def test_mysql_identity(self):
self.assertIn(
"SELECT DATABASE(), CURRENT_USER(), @@server_uuid",
get_adapter(config()).identity_command(),
)
def test_postgresql_identity(self):
self.assertIn(
"SELECT current_database(), current_user",
get_adapter(
config("pgsql")
).identity_command(),
)
def test_mysql_database_target(self):
command = get_adapter(config()).backup_command()
self.assertIn("example_db", command)
def test_postgresql_database_target(self):
command = get_adapter(
config("pgsql")
).backup_command()
self.assertIn(
"--dbname=example_db",
command,
)
def test_mysql_backup_extension(self):
self.assertEqual(
get_adapter(config()).backup_extension,
".sql",
)
def test_postgresql_backup_extension(self):
self.assertEqual(
get_adapter(
config("pgsql")
).backup_extension,
".dump",
)
def test_mysql_restore_target(self):
command = get_adapter(
config()
).restore_command("isolated_restore_test")
self.assertIn(
"--database=isolated_restore_test",
command,
)
self.assertIn("-i", command)
def test_postgresql_restore_target(self):
command = get_adapter(
config("pgsql")
).restore_command("isolated_restore_test")
self.assertIn("pg_restore", command)
self.assertIn("--exit-on-error", command)
self.assertIn(
"--dbname=isolated_restore_test",
command,
)
self.assertIn("-i", command)
def test_live_mysql_restore_rejected(self):
with self.assertRaises(DatabaseError):
get_adapter(
config()
).restore_command("example_db")
def test_live_postgresql_restore_rejected(self):
with self.assertRaises(DatabaseError):
get_adapter(
config("pgsql")
).restore_command("example_db")
def test_case_variant_restore_rejected(self):
with self.assertRaises(DatabaseError):
get_adapter(
config()
).restore_command("EXAMPLE_DB")
def test_invalid_restore_database_rejected(self):
with self.assertRaises(DatabaseError):
get_adapter(
config()
).restore_command("test; command")
def test_invalid_restore_prefix_rejected(self):
with self.assertRaises(DatabaseError):
get_adapter(
config()
).restore_command("another_application")
def test_mysql_system_database_rejected(self):
with self.assertRaises(DatabaseError):
get_adapter(
config()
).restore_command("mysql")
def test_postgresql_system_database_rejected(self):
with self.assertRaises(DatabaseError):
get_adapter(
config("pgsql")
).restore_command("postgres")
def test_mysql_no_password_argument(self):
command = get_adapter(config()).backup_command()
self.assertFalse(
any(
item.startswith("--password")
for item in command
)
)
def test_postgresql_no_password_argument(self):
command = get_adapter(
config("pgsql")
).backup_command()
self.assertFalse(
any(
"PGPASSWORD=" in item
for item in command
)
)
def test_invalid_driver_rejected(self):
data = config()
data["database"]["driver"] = "sqlite"
with self.assertRaises(DatabaseError):
get_adapter(data)
def test_invalid_container_rejected(self):
data = config()
data["database"]["container"] = "--privileged"
with self.assertRaises(DatabaseError):
get_adapter(data)
def test_configuration_not_mutated(self):
data = config()
original = json.dumps(
data, sort_keys=True
)
get_adapter(data).backup_command()
self.assertEqual(
json.dumps(data, sort_keys=True),
original,
)
def test_mysql_secure_client_configuration(self):
command = get_adapter(
config()
).backup_command()
index = command.index("mysqldump")
self.assertEqual(
command[index + 1],
"--defaults-file=/run/secrets/absdev-client.cnf",
)
def test_postgresql_secure_client_configuration(self):
command = get_adapter(
config("pgsql")
).backup_command()
self.assertIn(
"PGPASSFILE=/run/secrets/absdev-pgpass",
command,
)
def test_mysql_interactive_password_disabled(self):
command = get_adapter(config()).ping_command()
self.assertNotIn("-p", command)
def test_postgresql_interactive_password_disabled(self):
command = get_adapter(
config("pgsql")
).ping_command()
self.assertIn("--no-password", command)
if __name__ == "__main__":
unittest.main()
+660
View File
@@ -0,0 +1,660 @@
import tempfile
import unittest
from pathlib import Path
from unittest.mock import Mock
from core.compatibility import provenance_fingerprint
from core.backup_evidence import BackupEvidence
from core.approval_store import ApprovalStore
from core.operation_guard import OperationGuard
from core.deployment import DeploymentController, DeploymentError
from core.locking import DeploymentLock, LockError
from core.releases import ReleaseManager
from core.transactions import TransactionJournal
def evidence(revision):
data = {
"format_version": 1,
"revision": revision,
"migrations": {
"database/migrations/0001_users.php": "a" * 64,
},
"dependencies": {
"composer.json": "b" * 64,
"composer.lock": "c" * 64,
"package.json": "d" * 64,
"package-lock.json": "e" * 64,
},
}
data["fingerprint"] = provenance_fingerprint(data)
return data
class DeploymentTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.app = self.root / "app"
self.app.mkdir()
(self.app / "releases").mkdir()
self.state = self.root / "state"
self.state.mkdir(mode=0o700)
self.releases = ReleaseManager(self.app)
self.journal = TransactionJournal(self.state)
for number, revision in (
("1", "a" * 40),
("2", "b" * 40),
):
release = self.app / "releases" / number
(release / "vendor").mkdir(parents=True)
(release / "public/build").mkdir(parents=True)
(release / "vendor/autoload.php").write_text(
"<?php\n"
)
(release / "public/build/manifest.json").write_text(
"{}"
)
(release / "REVISION").write_text(
revision + "\n"
)
self.releases.activate("1")
self.old = evidence("a" * 40)
self.new = evidence("b" * 40)
self.provenance = Mock()
self.provenance.verify.side_effect = (
lambda path: self.old
if path.name == "1"
else self.new
)
self.services = Mock()
self.backup = Mock()
self.backup.create.return_value = "fixture-backup"
self.manifest = {
"backup_id": "fixture-backup",
"driver": "mysql",
"database": "example_db",
"username": "example_app",
"container": "example-mysql",
"identity": "example-server",
"filename": "database.sql",
"sha256": "c" * 64,
"bytes": 100,
}
self.backup.verify.return_value = self.manifest
self.evidence = BackupEvidence(self.state)
self.approvals = self.root / "approvals"
self.approvals.mkdir(mode=0o700)
self.approval_store = ApprovalStore(self.approvals)
self.operation_guard = OperationGuard(self.approval_store)
self.health = Mock()
self.health.verify.side_effect = (
lambda release: {
"healthy": True,
"release": release,
}
)
self.runtime_check = Mock(return_value=True)
self.stopped_check = Mock(return_value=True)
self.controller = DeploymentController(
site="example-absdev-net",
lock_path=self.root / ".deployment.lock",
releases=self.releases,
provenance=self.provenance,
journal=self.journal,
backup=self.backup,
services=self.services,
health=self.health,
runtime_check=self.runtime_check,
stopped_check=self.stopped_check,
backup_evidence=self.evidence,
operation_guard=self.operation_guard,
)
def deploy(self):
return self.controller.deploy("2")
def test_successful_deployment(self):
self.assertEqual(
self.deploy()["phase"],
"VERIFIED",
)
self.assertEqual(self.releases.current(), "2")
def test_backup_created(self):
self.deploy()
self.backup.create.assert_called_once()
def test_backup_verified(self):
self.deploy()
self.backup.verify.assert_called_once_with(
"fixture-backup"
)
def test_services_quiesced(self):
self.deploy()
self.services.quiesce.assert_called_once()
def test_services_refreshed(self):
self.deploy()
self.services.refresh.assert_called_once()
def test_workers_restored(self):
self.deploy()
self.services.resume.assert_called_once()
def test_health_verified(self):
self.deploy()
self.health.verify.assert_called_once_with("2")
def test_persistent_verified_transaction(self):
self.deploy()
self.assertEqual(
self.journal.load()["phase"],
"VERIFIED",
)
def test_previous_release_preserved(self):
self.deploy()
self.assertTrue(
self.releases.release_path("1").is_dir()
)
def test_existing_transaction_blocks_deployment(self):
self.journal.create(
"example-absdev-net",
"1",
"2",
"b" * 40,
self.new["fingerprint"],
)
with self.assertRaises(DeploymentError):
self.deploy()
self.backup.create.assert_not_called()
def test_concurrent_deployment_rejected(self):
with DeploymentLock(
self.root / ".deployment.lock"
):
with self.assertRaises(LockError):
self.deploy()
def test_same_release_rejected(self):
with self.assertRaises(DeploymentError):
self.controller.deploy("1")
def test_missing_release_rejected(self):
with self.assertRaises(DeploymentError):
self.controller.deploy("99")
self.assertEqual(self.releases.current(), "1")
def test_provenance_failure_blocks_deployment(self):
self.provenance.verify.side_effect = RuntimeError()
with self.assertRaises(DeploymentError):
self.deploy()
self.backup.create.assert_not_called()
def test_migration_change_blocks_deployment(self):
self.new["migrations"][
"database/migrations/0002_orders.php"
] = "f" * 64
self.new["fingerprint"] = (
provenance_fingerprint(self.new)
)
with self.assertRaises(DeploymentError):
self.deploy()
self.backup.create.assert_not_called()
self.assertEqual(self.releases.current(), "1")
def test_database_readiness_required(self):
self.runtime_check.return_value = False
with self.assertRaises(DeploymentError):
self.deploy()
self.backup.create.assert_not_called()
def test_backup_failure_blocks_activation(self):
self.backup.create.side_effect = RuntimeError()
with self.assertRaises(DeploymentError):
self.deploy()
self.assertEqual(self.releases.current(), "1")
self.services.quiesce.assert_not_called()
self.assertEqual(
self.journal.load()["phase"],
"FAILED",
)
def test_backup_verification_failure(self):
self.backup.verify.side_effect = RuntimeError()
with self.assertRaises(DeploymentError):
self.deploy()
self.services.quiesce.assert_not_called()
def test_worker_shutdown_failure(self):
self.services.quiesce.side_effect = RuntimeError()
with self.assertRaises(DeploymentError):
self.deploy()
self.assertEqual(self.releases.current(), "1")
def test_worker_state_verification_required(self):
self.stopped_check.return_value = False
with self.assertRaises(DeploymentError):
self.deploy()
self.assertEqual(self.releases.current(), "1")
def test_refresh_failure_preserves_transaction(self):
self.services.refresh.side_effect = RuntimeError()
with self.assertRaises(DeploymentError):
self.deploy()
self.assertEqual(
self.journal.load()["phase"],
"FAILED",
)
self.assertEqual(self.releases.current(), "2")
def test_health_failure_requires_explicit_recovery(self):
self.health.verify.side_effect = RuntimeError()
with self.assertRaises(DeploymentError):
self.deploy()
self.assertEqual(
self.journal.load()["phase"],
"FAILED",
)
self.assertEqual(self.releases.current(), "2")
def test_false_health_result_rejected(self):
self.health.verify.side_effect = None
self.health.verify.return_value = {
"healthy": False,
"release": "2",
}
with self.assertRaises(DeploymentError):
self.deploy()
def test_wrong_health_release_rejected(self):
self.health.verify.side_effect = None
self.health.verify.return_value = {
"healthy": True,
"release": "1",
}
with self.assertRaises(DeploymentError):
self.deploy()
def test_failed_transaction_blocks_retry(self):
self.health.verify.side_effect = RuntimeError()
with self.assertRaises(DeploymentError):
self.deploy()
with self.assertRaises(DeploymentError):
self.deploy()
self.backup.create.assert_called_once()
def test_lock_released_after_failure(self):
self.backup.create.side_effect = RuntimeError()
with self.assertRaises(DeploymentError):
self.deploy()
with DeploymentLock(
self.root / ".deployment.lock"
) as lock:
self.assertTrue(lock.acquired)
def test_runtime_rechecked_before_activation(self):
self.runtime_check.side_effect = [True, False]
with self.assertRaises(DeploymentError):
self.deploy()
self.assertEqual(self.releases.current(), "1")
def test_failure_after_worker_resume_quiesces_again(self):
self.health.verify.side_effect = RuntimeError()
with self.assertRaises(DeploymentError):
self.deploy()
self.assertEqual(
self.services.quiesce.call_count,
2,
)
def test_recovery_plan_is_read_only(self):
self.health.verify.side_effect = RuntimeError()
with self.assertRaises(DeploymentError):
self.deploy()
before = self.journal.load()
plan = self.controller.recovery_plan()
self.assertEqual(plan["previous"], "1")
self.assertEqual(plan["candidate"], "2")
self.assertEqual(plan["current"], "2")
self.assertFalse(
plan["automatic_rollback_allowed"]
)
self.assertEqual(self.journal.load(), before)
def test_clear_recovery_plan(self):
self.assertEqual(
self.controller.recovery_plan()["status"],
"CLEAR",
)
def test_backup_evidence_persisted(self):
result = self.deploy()
evidence = self.evidence.load(
result["transaction_id"]
)
self.assertEqual(
evidence["backup"],
self.manifest,
)
def test_evidence_exists_before_worker_shutdown(self):
def check():
transaction = self.journal.load()
evidence = self.evidence.load(
transaction["transaction_id"]
)
self.assertEqual(
evidence["backup"]["sha256"],
self.manifest["sha256"],
)
self.services.quiesce.side_effect = check
self.deploy()
def test_evidence_persistence_failure_blocks_deploy(self):
self.evidence.create = Mock(
side_effect=RuntimeError("write failure")
)
with self.assertRaises(DeploymentError):
self.deploy()
self.assertEqual(self.releases.current(), "1")
self.services.quiesce.assert_not_called()
self.assertEqual(
self.journal.load()["phase"],
"FAILED",
)
def test_invalid_manifest_blocks_deploy(self):
self.manifest["sha256"] = "invalid"
with self.assertRaises(DeploymentError):
self.deploy()
self.services.quiesce.assert_not_called()
self.assertEqual(self.releases.current(), "1")
def test_evidence_readback_failure_blocks_deploy(self):
self.evidence.load = Mock(
side_effect=RuntimeError("read failure")
)
with self.assertRaises(DeploymentError):
self.deploy()
self.services.quiesce.assert_not_called()
def test_evidence_survives_health_failure(self):
self.health.verify.side_effect = RuntimeError()
with self.assertRaises(DeploymentError):
self.deploy()
transaction = self.journal.load()
evidence = self.evidence.load(
transaction["transaction_id"]
)
self.assertEqual(
evidence["backup"]["backup_id"],
"fixture-backup",
)
def test_failed_backup_creates_no_evidence(self):
self.backup.create.side_effect = RuntimeError()
with self.assertRaises(DeploymentError):
self.deploy()
self.assertFalse(
list(self.state.glob("*.backup.json"))
)
def test_failed_verification_creates_no_evidence(self):
self.backup.verify.side_effect = RuntimeError()
with self.assertRaises(DeploymentError):
self.deploy()
self.assertFalse(
list(self.state.glob("*.backup.json"))
)
def test_recovery_plan_contains_backup_evidence(self):
self.health.verify.side_effect = RuntimeError()
with self.assertRaises(DeploymentError):
self.deploy()
plan = self.controller.recovery_plan()
self.assertTrue(plan["backup_evidence_present"])
self.assertEqual(
plan["backup_id"],
"fixture-backup",
)
def test_missing_backup_evidence_reported(self):
self.backup.create.side_effect = RuntimeError()
with self.assertRaises(DeploymentError):
self.deploy()
plan = self.controller.recovery_plan()
self.assertFalse(plan["backup_evidence_present"])
self.assertIsNone(plan["backup_id"])
def test_corrupt_backup_evidence_blocks_recovery(self):
self.deploy()
transaction = self.journal.load()
self.evidence.path(
transaction["transaction_id"]
).write_text("{invalid")
with self.assertRaises(DeploymentError):
self.controller.recovery_plan()
def test_recovery_does_not_restore_database(self):
self.deploy()
self.controller.recovery_plan()
self.backup.restore.assert_not_called()
def test_previous_release_revision_bound(self):
result = self.deploy()
self.assertEqual(
result["previous_revision"],
self.old["revision"],
)
def test_previous_release_provenance_bound(self):
result = self.deploy()
self.assertEqual(
result["previous_provenance"],
self.old["fingerprint"],
)
def test_previous_evidence_survives_failure(self):
self.health.verify.side_effect = RuntimeError()
with self.assertRaises(DeploymentError):
self.deploy()
result = self.journal.load()
self.assertEqual(
result["previous_provenance"],
self.old["fingerprint"],
)
def test_unfinished_migration_blocks_deployment(self):
path = self.approvals / (
"a" * 32 + ".migration-intent.json"
)
path.touch(mode=0o600)
with self.assertRaises(DeploymentError):
self.deploy()
self.backup.create.assert_not_called()
self.services.quiesce.assert_not_called()
self.assertEqual(self.releases.current(), "1")
if __name__ == "__main__":
unittest.main()
+300
View File
@@ -0,0 +1,300 @@
import io
import sys
import tempfile
import unittest
from pathlib import Path
from core.execution import (
ExecutionError,
CommandRunner,
)
class ExecutionTests(unittest.TestCase):
def command(self, source):
return [
sys.executable,
"-I",
"-c",
source,
]
def runner(self, command, timeout=10):
return CommandRunner(
allowed_commands=[command],
timeout=timeout,
)
def test_successful_execution(self):
command = self.command(
"print('SUCCESS')"
)
output = io.BytesIO()
self.runner(command)(command, output)
self.assertEqual(
output.getvalue(),
b"SUCCESS\n",
)
def test_binary_output_preserved(self):
command = self.command(
"import sys; "
"sys.stdout.buffer.write(bytes(range(256)))"
)
output = io.BytesIO()
self.runner(command)(command, output)
self.assertEqual(
output.getvalue(),
bytes(range(256)),
)
def test_large_output_preserved(self):
command = self.command(
"import sys; "
"sys.stdout.buffer.write(b'x' * 1048576)"
)
output = io.BytesIO()
self.runner(command)(command, output)
self.assertEqual(
len(output.getvalue()),
1048576,
)
def test_output_to_file(self):
command = self.command(
"print('DATABASE BACKUP')"
)
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "backup.sql"
with path.open("wb") as handle:
self.runner(command)(
command,
handle,
)
self.assertEqual(
path.read_bytes(),
b"DATABASE BACKUP\n",
)
def test_nonzero_exit_rejected(self):
command = self.command(
"raise SystemExit(7)"
)
with self.assertRaises(ExecutionError):
self.runner(command)(
command,
io.BytesIO(),
)
def test_timeout_rejected(self):
command = self.command(
"import time; time.sleep(10)"
)
with self.assertRaises(ExecutionError):
self.runner(command, timeout=1)(
command,
io.BytesIO(),
)
def test_unauthorised_command_rejected(self):
allowed = self.command("print('allowed')")
denied = self.command("print('denied')")
with self.assertRaises(ExecutionError):
self.runner(allowed)(
denied,
io.BytesIO(),
)
def test_modified_arguments_rejected(self):
command = self.command("print('allowed')")
runner = self.runner(command)
modified = command + ["unexpected"]
with self.assertRaises(ExecutionError):
runner(modified, io.BytesIO())
def test_command_string_rejected(self):
command = self.command("print('allowed')")
with self.assertRaises(ExecutionError):
self.runner(command)(
"echo unsafe",
io.BytesIO(),
)
def test_empty_command_rejected(self):
with self.assertRaises(ExecutionError):
CommandRunner(
allowed_commands=[[]],
)
def test_empty_allowlist_rejected(self):
with self.assertRaises(ExecutionError):
CommandRunner(allowed_commands=[])
def test_invalid_argument_rejected(self):
with self.assertRaises(ExecutionError):
CommandRunner(
allowed_commands=[["echo", 123]]
)
def test_null_argument_rejected(self):
with self.assertRaises(ExecutionError):
CommandRunner(
allowed_commands=[
["echo", "bad\x00argument"]
]
)
def test_invalid_timeout_rejected(self):
command = self.command("print('test')")
for timeout in (0, -1, True, 100000):
with self.subTest(timeout=timeout):
with self.assertRaises(ExecutionError):
self.runner(command, timeout)
def test_stdin_is_disabled(self):
command = self.command(
"import sys; "
"print(len(sys.stdin.read()))"
)
output = io.BytesIO()
self.runner(command)(command, output)
self.assertEqual(
output.getvalue(),
b"0\n",
)
def test_shell_metacharacters_not_interpreted(self):
command = self.command(
"import sys; print(sys.argv[1])"
) + ["$(echo unsafe); echo unsafe"]
output = io.BytesIO()
self.runner(command)(command, output)
self.assertEqual(
output.getvalue(),
b"$(echo unsafe); echo unsafe\n",
)
def test_sensitive_stderr_not_disclosed(self):
command = self.command(
"import sys; "
"sys.stderr.write('PRIVATE_TEST_VALUE'); "
"raise SystemExit(1)"
)
with self.assertRaises(ExecutionError) as error:
self.runner(command)(
command,
io.BytesIO(),
)
self.assertNotIn(
"PRIVATE_TEST_VALUE",
str(error.exception),
)
def test_allowlist_copied(self):
command = self.command("print('original')")
runner = self.runner(command)
command[-1] = "print('modified')"
with self.assertRaises(ExecutionError):
runner(command, io.BytesIO())
def test_missing_executable_rejected(self):
command = [
"/nonexistent/absdev-test-executable"
]
with self.assertRaises(ExecutionError):
self.runner(command)(
command,
io.BytesIO(),
)
def test_failed_output_not_published(self):
command = self.command(
"print('partial backup'); "
"raise SystemExit(1)"
)
output = io.BytesIO()
with self.assertRaises(ExecutionError):
self.runner(command)(command, output)
self.assertEqual(
output.getvalue(),
b"",
)
if __name__ == "__main__":
unittest.main()
+416
View File
@@ -0,0 +1,416 @@
import copy
import json
import unittest
from pathlib import Path
from unittest.mock import Mock
from core.health import (
HealthError,
HealthVerifier,
)
class HealthTests(unittest.TestCase):
def setUp(self):
self.config = json.loads(
Path("config/site.example.json").read_text()
)
self.http = Mock(return_value=200)
self.service = Mock(return_value=True)
self.database = Mock(return_value=True)
self.redis = Mock(return_value=True)
self.assets = Mock(return_value=True)
self.release = Mock(return_value="2")
self.sleep = Mock()
def verifier(self, **options):
return HealthVerifier(
self.config,
http_probe=self.http,
service_probe=self.service,
database_probe=self.database,
redis_probe=self.redis,
asset_probe=self.assets,
release_probe=self.release,
sleep=self.sleep,
**options,
)
def verify(self, **options):
return self.verifier(**options).verify("2")
def test_healthy_application(self):
self.assertTrue(self.verify()["healthy"])
def test_expected_release(self):
self.assertEqual(
self.verify()["release"], "2"
)
def test_all_http_endpoints_checked(self):
result = self.verify()
self.assertEqual(
set(result["http"]),
{"/", "/up", "/login"},
)
self.assertEqual(
self.http.call_count, 3
)
def test_all_services_checked(self):
result = self.verify()
self.assertEqual(
set(result["services"]),
{"php", "web", "queue", "scheduler"},
)
self.assertEqual(
self.service.call_count, 4
)
def test_database_checked(self):
self.assertTrue(
self.verify()["database"]
)
self.database.assert_called_once()
def test_redis_checked(self):
self.assertTrue(
self.verify()["redis"]
)
self.redis.assert_called_once()
def test_assets_checked(self):
self.assertTrue(
self.verify()["assets"]
)
self.assets.assert_called_once()
def test_origin_is_loopback(self):
self.verify()
expected = (
"http://127.0.0.1:"
+ str(self.config["site"]["origin_port"])
)
for call in self.http.call_args_list:
self.assertTrue(
call.args[0].startswith(expected + "/")
)
def test_host_header_passed(self):
self.verify()
for call in self.http.call_args_list:
self.assertEqual(
call.kwargs["host"],
self.config["site"]["domain"],
)
def test_http_timeout_passed(self):
self.verify()
self.assertEqual(
self.http.call_args.kwargs["timeout"],
self.config["health"]["timeout_seconds"],
)
def test_http_500_rejected(self):
self.http.return_value = 500
with self.assertRaises(HealthError):
self.verify()
def test_http_404_rejected(self):
self.http.return_value = 404
with self.assertRaises(HealthError):
self.verify()
def test_http_redirect_rejected(self):
self.http.return_value = 302
with self.assertRaises(HealthError):
self.verify()
def test_http_boolean_rejected(self):
self.http.return_value = True
with self.assertRaises(HealthError):
self.verify()
def test_http_string_rejected(self):
self.http.return_value = "200"
with self.assertRaises(HealthError):
self.verify()
def test_http_exception_rejected(self):
self.http.side_effect = TimeoutError()
with self.assertRaises(HealthError):
self.verify()
def test_service_failure_rejected(self):
self.service.return_value = False
with self.assertRaises(HealthError):
self.verify()
def test_database_failure_rejected(self):
self.database.return_value = False
with self.assertRaises(HealthError):
self.verify()
def test_redis_failure_rejected(self):
self.redis.return_value = False
with self.assertRaises(HealthError):
self.verify()
def test_asset_failure_rejected(self):
self.assets.return_value = False
with self.assertRaises(HealthError):
self.verify()
def test_wrong_release_rejected(self):
self.release.return_value = "1"
with self.assertRaises(HealthError):
self.verify()
def test_release_change_during_verification(self):
self.release.side_effect = ["2", "3"]
with self.assertRaises(HealthError):
self.verify()
def test_missing_release_rejected(self):
self.release.return_value = None
with self.assertRaises(HealthError):
self.verify()
def test_non_boolean_database_result_rejected(self):
self.database.return_value = 1
with self.assertRaises(HealthError):
self.verify()
def test_non_boolean_service_result_rejected(self):
self.service.return_value = "running"
with self.assertRaises(HealthError):
self.verify()
def test_retry_recovers_http_failure(self):
self.http.side_effect = [
503, 200, 200, 200
]
result = self.verify(attempts=2)
self.assertTrue(result["healthy"])
self.assertEqual(
result["attempt"], 2
)
self.sleep.assert_called_once_with(2)
def test_retry_limit_enforced(self):
self.http.return_value = 503
with self.assertRaises(HealthError):
self.verify(attempts=3)
self.assertEqual(
self.http.call_count, 3
)
self.assertEqual(
self.sleep.call_count, 2
)
def test_no_sleep_after_success(self):
self.verify(attempts=3)
self.sleep.assert_not_called()
def test_custom_retry_delay(self):
self.http.side_effect = [
503, 200, 200, 200
]
self.verify(
attempts=2,
retry_delay=5,
)
self.sleep.assert_called_once_with(5)
def test_invalid_retry_count_rejected(self):
for value in (0, -1, 11, True, "3"):
with self.subTest(value=value):
with self.assertRaises(HealthError):
self.verifier(attempts=value)
def test_invalid_retry_delay_rejected(self):
for value in (-1, 31, True, "2"):
with self.subTest(value=value):
with self.assertRaises(HealthError):
self.verifier(retry_delay=value)
def test_invalid_expected_release_rejected(self):
with self.assertRaises(HealthError):
self.verifier().verify("../outside")
self.http.assert_not_called()
def test_invalid_configuration_rejected(self):
self.config["health"]["endpoints"] = [
"https://example.invalid"
]
with self.assertRaises(HealthError):
self.verifier()
def test_configuration_not_mutated(self):
original = copy.deepcopy(self.config)
self.verify()
self.assertEqual(self.config, original)
def test_configuration_snapshot(self):
verifier = self.verifier()
self.config["health"]["endpoints"] = ["/changed"]
result = verifier.verify("2")
self.assertNotIn(
"/changed",
result["http"],
)
def test_sensitive_probe_error_not_disclosed(self):
self.database.side_effect = RuntimeError(
"private-password"
)
with self.assertRaises(HealthError) as result:
self.verify()
self.assertNotIn(
"private-password",
str(result.exception),
)
def test_custom_service_names(self):
self.config["docker"]["php_service"] = "application"
result = self.verify()
self.assertIn(
"application",
result["services"],
)
self.assertNotIn(
"php",
result["services"],
)
def test_invalid_probe_rejected(self):
self.http = None
with self.assertRaises(HealthError):
self.verifier()
def test_no_probes_during_initialisation(self):
self.verifier()
for probe in (
self.http,
self.service,
self.database,
self.redis,
self.assets,
self.release,
):
probe.assert_not_called()
def test_failed_http_prevents_later_probes(self):
self.http.return_value = 500
with self.assertRaises(HealthError):
self.verify()
self.database.assert_not_called()
self.assets.assert_not_called()
if __name__ == "__main__":
unittest.main()
+264
View File
@@ -0,0 +1,264 @@
import copy
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from core.inspection_cli import (
inventory_report,
provisioning_plan,
capabilities,
)
from core.configuration import load_config
ROOT = Path(__file__).resolve().parents[2]
class InspectionCLITests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.app = self.root / "app"
self.app.mkdir()
(self.app / "releases").mkdir()
for release in ("1", "2", "3"):
(self.app / "releases" / release).mkdir()
(self.app / "current").symlink_to("releases/3")
self.config = load_config(
ROOT / "config/site.example.json"
)
def cli(self, *args):
return subprocess.run(
[
sys.executable,
str(ROOT / "bin/absdev-deploy"),
*args,
],
cwd=ROOT,
capture_output=True,
text=True,
timeout=10,
)
def test_inventory(self):
result = inventory_report(self.app)
self.assertEqual(result["inventory"], ["1", "2", "3"])
self.assertEqual(result["current"], "3")
def test_failed_release_inventory(self):
(
self.app / "releases/1/BAD_RELEASE"
).touch()
self.assertEqual(
inventory_report(self.app)["failed"],
["1"],
)
def test_failed_current_rejected(self):
(
self.app / "releases/3/BAD_RELEASE"
).touch()
with self.assertRaises(RuntimeError):
inventory_report(self.app)
def test_inventory_is_read_only(self):
before = sorted(
str(path.relative_to(self.app))
for path in self.app.rglob("*")
)
inventory_report(self.app)
after = sorted(
str(path.relative_to(self.app))
for path in self.app.rglob("*")
)
self.assertEqual(before, after)
def test_inventory_does_not_authorise_execution(self):
self.assertFalse(
inventory_report(self.app)["execution_permitted"]
)
def test_provisioning_plan(self):
result = provisioning_plan(self.config)
self.assertEqual(result["status"], "PLAN_ONLY")
self.assertEqual(
result["site"],
self.config["site"]["identifier"],
)
def test_provisioning_does_not_mutate_config(self):
original = copy.deepcopy(self.config)
provisioning_plan(self.config)
self.assertEqual(self.config, original)
def test_provisioning_deterministic(self):
self.assertEqual(
provisioning_plan(self.config),
provisioning_plan(self.config),
)
def test_provisioning_execution_disabled(self):
result = provisioning_plan(self.config)
self.assertFalse(result["execution_permitted"])
self.assertFalse(result["database_creation_permitted"])
def test_provisioning_database_driver(self):
result = provisioning_plan(self.config)
self.assertEqual(
result["database"]["driver"],
self.config["database"]["driver"],
)
def test_capabilities(self):
result = capabilities()
self.assertFalse(result["production_ready"])
self.assertFalse(result["deployment_execution_enabled"])
def test_cli_capabilities(self):
result = self.cli("capabilities")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(json.loads(result.stdout), capabilities())
def test_cli_inventory(self):
result = self.cli(
"inventory",
"--app",
str(self.app),
)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(
json.loads(result.stdout)["current"],
"3",
)
def test_cli_provisioning(self):
result = self.cli(
"provision-plan",
"--config",
str(ROOT / "config/site.example.json"),
)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(
json.loads(result.stdout)["status"],
"PLAN_ONLY",
)
def test_cli_missing_config(self):
result = self.cli(
"provision-plan",
"--config",
str(self.root / "missing.json"),
)
self.assertNotEqual(result.returncode, 0)
def test_cli_retention_plan(self):
policy = self.root / "retention.json"
policy.write_text(json.dumps({
"inventory": ["1", "2", "3", "4"],
"current": "4",
"keep": 2,
"protected": [],
"failed": [],
"unresolved": [],
}))
result = self.cli(
"retention-plan",
"--policy",
str(policy),
)
self.assertEqual(result.returncode, 0, result.stderr)
report = json.loads(result.stdout)
self.assertEqual(report["archive_candidates"], ["1", "2"])
self.assertFalse(report["execution_permitted"])
def test_cli_retention_invalid_json(self):
policy = self.root / "retention.json"
policy.write_text("{invalid")
result = self.cli(
"retention-plan",
"--policy",
str(policy),
)
self.assertNotEqual(result.returncode, 0)
def test_cli_duplicate_json_fields(self):
policy = self.root / "retention.json"
policy.write_text('{"current":"1","current":"2"}')
result = self.cli(
"retention-plan",
"--policy",
str(policy),
)
self.assertNotEqual(result.returncode, 0)
def test_original_validation_preserved(self):
result = self.cli(
"validate",
"--config",
str(ROOT / "config/site.example.json"),
)
self.assertEqual(result.returncode, 0, result.stderr)
def test_cli_help(self):
result = self.cli("--help")
self.assertEqual(result.returncode, 0)
self.assertIn("validate", result.stdout)
self.assertIn("inventory", result.stdout)
self.assertIn("provision-plan", result.stdout)
def test_unknown_command_rejected(self):
result = self.cli("unknown-command")
self.assertNotEqual(result.returncode, 0)
def test_live_deployment_command_disabled(self):
result = self.cli("deploy")
self.assertNotEqual(result.returncode, 0)
if __name__ == "__main__":
unittest.main()
+281
View File
@@ -0,0 +1,281 @@
import os
import stat
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from core.locking import DeploymentLock, LockError
class LockingTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.path = self.root / ".deployment.lock"
def test_lock_acquisition(self):
with DeploymentLock(self.path) as lock:
self.assertTrue(lock.acquired)
def test_lock_file_created(self):
with DeploymentLock(self.path):
self.assertTrue(self.path.is_file())
def test_lock_file_permissions(self):
with DeploymentLock(self.path):
self.assertEqual(
stat.S_IMODE(self.path.stat().st_mode),
0o600,
)
def test_lock_release(self):
lock = DeploymentLock(self.path)
with lock:
self.assertTrue(lock.acquired)
self.assertFalse(lock.acquired)
def test_lock_file_preserved(self):
with DeploymentLock(self.path):
original = self.path.stat().st_ino
self.assertTrue(self.path.exists())
self.assertEqual(
self.path.stat().st_ino,
original,
)
def test_reacquisition(self):
with DeploymentLock(self.path):
pass
with DeploymentLock(self.path) as lock:
self.assertTrue(lock.acquired)
def test_concurrent_lock_rejected(self):
with DeploymentLock(self.path):
with self.assertRaises(LockError):
with DeploymentLock(self.path):
pass
def test_independent_locks(self):
with DeploymentLock(self.path):
with DeploymentLock(
self.root / ".other.lock"
) as lock:
self.assertTrue(lock.acquired)
def test_release_after_exception(self):
with self.assertRaises(RuntimeError):
with DeploymentLock(self.path):
raise RuntimeError("Simulated failure")
with DeploymentLock(self.path) as lock:
self.assertTrue(lock.acquired)
def test_symlink_rejected(self):
target = self.root / "target"
target.touch()
self.path.symlink_to(target)
with self.assertRaises(LockError):
with DeploymentLock(self.path):
pass
def test_dangling_symlink_rejected(self):
self.path.symlink_to(
self.root / "missing"
)
with self.assertRaises(LockError):
with DeploymentLock(self.path):
pass
def test_hardlink_rejected(self):
target = self.root / "target"
target.touch(mode=0o600)
os.link(target, self.path)
with self.assertRaises(LockError):
with DeploymentLock(self.path):
pass
def test_directory_rejected(self):
self.path.mkdir()
with self.assertRaises(LockError):
with DeploymentLock(self.path):
pass
def test_fifo_rejected(self):
os.mkfifo(self.path, 0o600)
with self.assertRaises(LockError):
with DeploymentLock(self.path):
pass
def test_insecure_permissions_rejected(self):
self.path.touch()
self.path.chmod(0o666)
with self.assertRaises(LockError):
with DeploymentLock(self.path):
pass
def test_missing_parent_rejected(self):
path = self.root / "missing" / ".lock"
with self.assertRaises(LockError):
with DeploymentLock(path):
pass
def test_symlink_parent_rejected(self):
actual = self.root / "actual"
actual.mkdir()
link = self.root / "linked"
link.symlink_to(actual)
with self.assertRaises(LockError):
with DeploymentLock(link / ".lock"):
pass
def test_relative_path_rejected(self):
with self.assertRaises(LockError):
DeploymentLock("relative.lock")
def test_duplicate_acquire_rejected(self):
lock = DeploymentLock(self.path)
with lock:
with self.assertRaises(LockError):
lock.acquire()
def test_release_is_idempotent(self):
lock = DeploymentLock(self.path)
lock.acquire()
lock.release()
lock.release()
self.assertFalse(lock.acquired)
def test_cross_process_contention(self):
code = """
import sys
from core.locking import DeploymentLock, LockError
try:
with DeploymentLock(sys.argv[1]):
sys.exit(0)
except LockError:
sys.exit(7)
"""
with DeploymentLock(self.path):
result = subprocess.run(
[
sys.executable,
"-B",
"-c",
code,
str(self.path),
],
stdin=subprocess.DEVNULL,
capture_output=True,
timeout=10,
)
self.assertEqual(result.returncode, 7)
def test_process_exit_releases_lock(self):
code = """
import os
import sys
from core.locking import DeploymentLock
lock = DeploymentLock(sys.argv[1])
lock.acquire()
os._exit(0)
"""
result = subprocess.run(
[
sys.executable,
"-B",
"-c",
code,
str(self.path),
],
stdin=subprocess.DEVNULL,
capture_output=True,
timeout=10,
)
self.assertEqual(result.returncode, 0)
with DeploymentLock(self.path) as lock:
self.assertTrue(lock.acquired)
if __name__ == "__main__":
unittest.main()
+360
View File
@@ -0,0 +1,360 @@
import copy
import unittest
from datetime import timedelta
from unittest.mock import Mock
import test_approval_store
from core.migration import MigrationCoordinator, MigrationError
from core.locking import DeploymentLock, LockError
class MigrationTests(unittest.TestCase):
def setUp(self):
self.fixture = test_approval_store.ApprovalStoreTests()
self.addCleanup(self.fixture.doCleanups)
self.fixture.setUp()
self.fixture.save()
self.root = self.fixture.root
self.context = Mock(
side_effect=lambda: copy.deepcopy(self.fixture.base)
)
self.contain = Mock(return_value=True)
self.contained = Mock(return_value=True)
self.backup = Mock(return_value=True)
self.before = ["2026_01_01_000000_create_users"]
self.after = (
self.before + self.fixture.base["pending_migrations"]
)
self.history = Mock(
side_effect=[
list(self.before),
list(self.before),
list(self.after),
]
)
self.migrate = Mock(return_value=0)
self.application = Mock(return_value=True)
self.clock = Mock(return_value=self.fixture.now)
self.coordinator = MigrationCoordinator(
store=self.fixture.store,
lock_path=self.root / ".deployment.lock",
context_probe=self.context,
contain=self.contain,
containment_probe=self.contained,
backup_probe=self.backup,
history_probe=self.history,
migration_runner=self.migrate,
application_probe=self.application,
clock=self.clock,
)
def execute(self):
return self.coordinator.execute(
self.fixture.identifier,
self.fixture.rehearsal,
confirmation=self.fixture.approval["confirmation"],
)
def test_successful_migration(self):
self.assertEqual(self.execute()["status"], "MIGRATED")
def test_runner_called_once(self):
self.execute()
self.migrate.assert_called_once()
def test_exact_migration_inventory(self):
self.execute()
self.migrate.assert_called_once_with(
tuple(self.fixture.base["pending_migrations"])
)
def test_approval_consumed_before_execution(self):
def check(pending):
self.assertTrue(
self.fixture.store.consumed_path(
self.fixture.identifier
).exists()
)
return 0
self.migrate.side_effect = check
self.execute()
def test_intent_persisted_before_execution(self):
def check(pending):
record = self.fixture.store.read(
self.coordinator.intent_path(self.fixture.identifier)
)
self.assertEqual(record["status"], "MIGRATION_INTENT")
return 0
self.migrate.side_effect = check
self.execute()
def test_wrong_confirmation_rejected(self):
with self.assertRaises(MigrationError):
self.coordinator.execute(
self.fixture.identifier,
self.fixture.rehearsal,
confirmation="INVALID",
)
self.contain.assert_not_called()
self.migrate.assert_not_called()
def test_expired_approval_rejected(self):
self.clock.return_value += timedelta(hours=25)
with self.assertRaises(MigrationError):
self.execute()
self.migrate.assert_not_called()
def test_context_change_rejected(self):
self.fixture.base["database_identity"] = "0" * 64
with self.assertRaises(MigrationError):
self.execute()
self.contain.assert_not_called()
def test_backup_verification_required(self):
self.backup.return_value = False
with self.assertRaises(MigrationError):
self.execute()
self.migrate.assert_not_called()
def test_containment_required(self):
self.contain.return_value = False
with self.assertRaises(MigrationError):
self.execute()
self.migrate.assert_not_called()
def test_containment_verification_required(self):
self.contained.return_value = False
with self.assertRaises(MigrationError):
self.execute()
self.migrate.assert_not_called()
def test_context_rechecked_after_containment(self):
original = copy.deepcopy(self.fixture.base)
changed = copy.deepcopy(original)
changed["database_identity"] = "0" * 64
self.context.side_effect = [original, changed]
with self.assertRaises(MigrationError):
self.execute()
self.migrate.assert_not_called()
def test_backup_rechecked_after_containment(self):
self.backup.side_effect = [True, False]
with self.assertRaises(MigrationError):
self.execute()
self.migrate.assert_not_called()
def test_history_change_before_execution(self):
self.history.side_effect = [
self.before,
self.before + ["unexpected"],
]
with self.assertRaises(MigrationError):
self.execute()
self.migrate.assert_not_called()
def test_previously_applied_migration_rejected(self):
self.history.side_effect = [self.after]
with self.assertRaises(MigrationError):
self.execute()
self.migrate.assert_not_called()
def test_runner_failure_rejected(self):
self.migrate.return_value = 1
with self.assertRaises(MigrationError):
self.execute()
self.application.assert_not_called()
def test_runner_exception_rejected(self):
self.migrate.side_effect = RuntimeError()
with self.assertRaises(MigrationError):
self.execute()
def test_missing_applied_migration_rejected(self):
self.history.side_effect = [
self.before, self.before, self.before
]
with self.assertRaises(MigrationError):
self.execute()
def test_unexpected_migration_rejected(self):
self.history.side_effect = [
self.before,
self.before,
self.after + ["unexpected"],
]
with self.assertRaises(MigrationError):
self.execute()
def test_removed_history_rejected(self):
self.history.side_effect = [
self.before,
self.before,
self.fixture.base["pending_migrations"],
]
with self.assertRaises(MigrationError):
self.execute()
def test_application_verification_required(self):
self.application.return_value = False
with self.assertRaises(MigrationError):
self.execute()
def test_success_evidence_persisted(self):
result = self.execute()
self.assertEqual(
result,
self.fixture.store.read(
self.coordinator.result_path(self.fixture.identifier)
),
)
def test_failure_evidence_persisted(self):
self.migrate.return_value = 1
with self.assertRaises(MigrationError):
self.execute()
result = self.fixture.store.read(
self.coordinator.result_path(self.fixture.identifier)
)
self.assertEqual(result["status"], "FAILED")
self.assertTrue(result["manual_recovery_required"])
def test_failed_execution_cannot_repeat(self):
self.migrate.return_value = 1
with self.assertRaises(MigrationError):
self.execute()
self.migrate.return_value = 0
with self.assertRaises(MigrationError):
self.execute()
self.migrate.assert_called_once()
def test_successful_execution_cannot_repeat(self):
self.execute()
with self.assertRaises(MigrationError):
self.execute()
self.migrate.assert_called_once()
def test_existing_intent_blocks_execution(self):
self.coordinator.intent_path(
self.fixture.identifier
).touch(mode=0o600)
with self.assertRaises(MigrationError):
self.execute()
self.migrate.assert_not_called()
def test_concurrent_deployment_rejected(self):
with DeploymentLock(self.root / ".deployment.lock"):
with self.assertRaises(LockError):
self.execute()
def test_database_rollback_prohibited(self):
self.assertFalse(
self.execute()["automatic_database_rollback"]
)
def test_application_activation_not_performed(self):
self.assertFalse(self.execute()["application_activated"])
def test_containment_remains_required(self):
self.assertTrue(self.execute()["containment_required"])
def test_boolean_runner_result_rejected(self):
self.migrate.return_value = False
with self.assertRaises(MigrationError):
self.execute()
def test_approval_expiry_rechecked(self):
self.clock.side_effect = [
self.fixture.now,
self.fixture.now + timedelta(hours=25),
]
with self.assertRaises(MigrationError):
self.execute()
self.migrate.assert_not_called()
def test_different_approval_intent_blocks_migration(self):
identifier = "0" * 32
self.fixture.store.path(
identifier,
".migration-intent.json",
).touch(mode=0o600)
with self.assertRaises(MigrationError):
self.execute()
self.contain.assert_not_called()
self.migrate.assert_not_called()
def test_other_consumed_approval_blocks_migration(self):
self.fixture.store.consumed_path(
"0" * 32
).touch(mode=0o600)
with self.assertRaises(MigrationError):
self.execute()
self.migrate.assert_not_called()
if __name__ == "__main__":
unittest.main()
+345
View File
@@ -0,0 +1,345 @@
import copy
import json
import unittest
from unittest.mock import Mock, patch
import test_migration_recovery
from core.approval_store import ApprovalStoreError
from core.compatibility import canonical_hash
from core.locking import DeploymentLock, LockError
from core.operation_guard import OperationGuard, OperationBlocked
from core.migration_archive import (
MigrationArchive,
MigrationArchiveError,
)
class MigrationArchiveTests(unittest.TestCase):
def setUp(self):
self.fixture = (
test_migration_recovery.MigrationRecoveryTests()
)
self.addCleanup(self.fixture.doCleanups)
self.fixture.setUp()
self.fixture.execute()
self.store = self.fixture.store
self.identifier = self.fixture.identifier
self.archive = MigrationArchive(
site=self.fixture.recovery.site,
store=self.store,
lock_path=self.fixture.recovery.lock_path,
identity_probe=self.fixture.identity,
history_probe=self.fixture.history,
provenance_probe=self.fixture.provenance,
backup_probe=self.fixture.backup,
current_probe=self.fixture.current,
health_probe=self.fixture.health,
writes_enabled_probe=self.fixture.writes_enabled,
)
self.guard = OperationGuard(self.store)
def plan(self):
return self.archive.plan(self.identifier)
def execute(self):
plan = self.plan()
return self.archive.execute(
self.identifier,
confirmation=plan["confirmation"],
fingerprint=plan["fingerprint"],
)
def rewrite(self, suffix, **changes):
path = self.store.path(
self.identifier, suffix
)
record = self.store.read(path)
record.update(changes)
record.pop("checksum", None)
record["checksum"] = canonical_hash(record)
path.write_text(json.dumps(record))
def test_valid_archive_plan(self):
self.assertEqual(
self.plan()["status"],
"ARCHIVE_READY",
)
def test_successful_archive(self):
result = self.execute()
self.assertEqual(
result["status"],
"ARCHIVED",
)
def test_original_records_preserved(self):
before = {
path.name: path.read_bytes()
for path in self.store.directory.glob("*.json")
}
self.execute()
for name, content in before.items():
self.assertEqual(
(self.store.directory / name).read_bytes(),
content,
)
def test_guard_blocks_before_archive(self):
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_guard_clears_after_archive(self):
self.execute()
self.assertEqual(
self.guard.require_clear()["status"],
"CLEAR",
)
def test_consumed_approval_preserved(self):
self.execute()
self.assertTrue(
self.store.consumed_path(
self.identifier
).exists()
)
def test_archived_approval_cannot_be_reused(self):
self.execute()
with self.assertRaises(ApprovalStoreError):
self.fixture.fixture.fixture.consume()
def test_missing_activation_result_rejected(self):
self.fixture.recovery.result_path(
self.identifier
).unlink()
with self.assertRaises(MigrationArchiveError):
self.plan()
def test_failed_activation_rejected(self):
self.rewrite(
".activation-result.json",
status="FAILED",
)
with self.assertRaises(MigrationArchiveError):
self.plan()
def test_changed_database_identity_rejected(self):
self.fixture.identity.return_value = "0" * 64
with self.assertRaises(MigrationArchiveError):
self.plan()
def test_changed_history_rejected(self):
self.fixture.history.return_value = ["unexpected"]
with self.assertRaises(MigrationArchiveError):
self.plan()
def test_changed_provenance_rejected(self):
self.fixture.provenance.return_value[
"fingerprint"
] = "0" * 64
with self.assertRaises(MigrationArchiveError):
self.plan()
def test_wrong_active_release_rejected(self):
self.fixture.active = "1"
with self.assertRaises(MigrationArchiveError):
self.plan()
def test_backup_verification_required(self):
self.fixture.backup.return_value = False
with self.assertRaises(MigrationArchiveError):
self.plan()
def test_health_verification_required(self):
self.fixture.health.side_effect = None
self.fixture.health.return_value = {
"healthy": False,
"release": "2",
}
with self.assertRaises(MigrationArchiveError):
self.plan()
def test_writes_enabled_verification_required(self):
self.fixture.writes_enabled.return_value = False
with self.assertRaises(MigrationArchiveError):
self.plan()
def test_wrong_confirmation_rejected(self):
plan = self.plan()
with self.assertRaises(MigrationArchiveError):
self.archive.execute(
self.identifier,
confirmation="INVALID",
fingerprint=plan["fingerprint"],
)
def test_wrong_fingerprint_rejected(self):
plan = self.plan()
with self.assertRaises(MigrationArchiveError):
self.archive.execute(
self.identifier,
confirmation=plan["confirmation"],
fingerprint="0" * 64,
)
def test_duplicate_archival_rejected(self):
self.execute()
with self.assertRaises(MigrationArchiveError):
self.execute()
def test_corrupted_archive_blocks_operations(self):
self.execute()
self.archive.path(
self.identifier
).write_text("{invalid")
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_missing_consumption_blocks_operations(self):
self.execute()
self.store.consumed_path(
self.identifier
).unlink()
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_changed_archived_evidence_blocks_operations(self):
self.execute()
self.rewrite(
".activation-result.json",
active_release="99",
)
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_unrelated_intent_still_blocks_operations(self):
self.execute()
self.store.path(
"0" * 32,
".migration-intent.json",
).touch(mode=0o600)
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_archive_publication_failure_blocks_operations(self):
plan = self.plan()
with patch(
"core.approval_store.os.link",
side_effect=OSError("publication failure"),
):
with self.assertRaises(MigrationArchiveError):
self.archive.execute(
self.identifier,
confirmation=plan["confirmation"],
fingerprint=plan["fingerprint"],
)
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_concurrent_operation_rejected(self):
with DeploymentLock(
self.fixture.recovery.lock_path
):
with self.assertRaises(LockError):
self.plan()
def test_archive_marker_alone_does_not_clear_guard(self):
self.archive.path(
self.identifier
).touch(mode=0o600)
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_archival_never_reexecutes_migration(self):
self.execute()
self.fixture.fixture.migrate.assert_called_once()
def test_no_database_restore(self):
result = self.execute()
self.assertFalse(result["database_restored"])
if __name__ == "__main__":
unittest.main()
+427
View File
@@ -0,0 +1,427 @@
import copy
import json
import unittest
from unittest.mock import Mock
import test_migration
from core.compatibility import canonical_hash
from core.locking import DeploymentLock, LockError
from core.migration_recovery import (
MigrationRecovery,
MigrationRecoveryError,
)
class MigrationRecoveryTests(unittest.TestCase):
def setUp(self):
self.fixture = test_migration.MigrationTests()
self.addCleanup(self.fixture.doCleanups)
self.fixture.setUp()
self.identifier = self.fixture.fixture.identifier
self.store = self.fixture.fixture.store
self.migration_result = self.fixture.execute()
self.identity = Mock(
return_value=self.migration_result[
"database_identity"
]
)
self.history = Mock(
return_value=list(self.fixture.after)
)
self.provenance = Mock(
return_value={
"revision": self.fixture.fixture.base["revision"],
"fingerprint": self.fixture.fixture.base["provenance"],
}
)
self.backup = Mock(return_value=True)
self.contain = Mock(return_value=True)
self.contained = Mock(return_value=True)
self.active = "1"
self.current = Mock(
side_effect=lambda: self.active
)
def activate(release):
self.active = release
return True
self.activate = Mock(side_effect=activate)
self.refresh = Mock(return_value=True)
self.ready = Mock(return_value=True)
self.release_containment = Mock(return_value=True)
self.writes_enabled = Mock(return_value=True)
self.health = Mock(
side_effect=lambda release: {
"healthy": True,
"release": release,
}
)
self.recovery = MigrationRecovery(
site=self.fixture.fixture.base["site"],
store=self.store,
lock_path=self.fixture.root / ".deployment.lock",
identity_probe=self.identity,
history_probe=self.history,
provenance_probe=self.provenance,
backup_probe=self.backup,
contain=self.contain,
containment_probe=self.contained,
current_probe=self.current,
activate=self.activate,
refresh=self.refresh,
readiness_probe=self.ready,
release_containment=self.release_containment,
writes_enabled_probe=self.writes_enabled,
health_probe=self.health,
)
def plan(self):
return self.recovery.inspect(self.identifier)
def execute(self):
plan = self.plan()
return self.recovery.execute(
self.identifier,
confirmation=plan["confirmation"],
fingerprint=plan["plan_fingerprint"],
)
def rewrite(self, path, record):
data = copy.deepcopy(record)
data.pop("checksum", None)
data["checksum"] = canonical_hash(data)
path.write_text(json.dumps(data))
def test_valid_recovery_plan(self):
self.assertEqual(
self.plan()["status"],
"FORWARD_ACTIVATION_READY",
)
def test_plan_is_read_only(self):
before = {
path.name: path.read_bytes()
for path in self.store.directory.glob("*.json")
}
self.plan()
after = {
path.name: path.read_bytes()
for path in self.store.directory.glob("*.json")
}
self.assertEqual(before, after)
self.activate.assert_not_called()
self.release_containment.assert_not_called()
def test_successful_activation(self):
result = self.execute()
self.assertEqual(result["status"], "VERIFIED")
self.assertEqual(self.active, "2")
def test_migration_never_repeated(self):
self.execute()
self.fixture.migrate.assert_called_once()
def test_wrong_confirmation(self):
plan = self.plan()
with self.assertRaises(MigrationRecoveryError):
self.recovery.execute(
self.identifier,
confirmation="INVALID",
fingerprint=plan["plan_fingerprint"],
)
self.activate.assert_not_called()
def test_wrong_fingerprint(self):
plan = self.plan()
with self.assertRaises(MigrationRecoveryError):
self.recovery.execute(
self.identifier,
confirmation=plan["confirmation"],
fingerprint="0" * 64,
)
self.activate.assert_not_called()
def test_changed_database_identity(self):
self.identity.return_value = "0" * 64
with self.assertRaises(MigrationRecoveryError):
self.plan()
def test_changed_migration_history(self):
self.history.return_value = ["unexpected"]
with self.assertRaises(MigrationRecoveryError):
self.plan()
def test_changed_candidate_revision(self):
self.provenance.return_value["revision"] = "0" * 40
with self.assertRaises(MigrationRecoveryError):
self.plan()
def test_changed_candidate_fingerprint(self):
self.provenance.return_value["fingerprint"] = "0" * 64
with self.assertRaises(MigrationRecoveryError):
self.plan()
def test_backup_verification_required(self):
self.backup.return_value = False
with self.assertRaises(MigrationRecoveryError):
self.plan()
def test_missing_result_rejected(self):
self.fixture.coordinator.result_path(
self.identifier
).unlink()
with self.assertRaises(MigrationRecoveryError):
self.plan()
def test_corrupted_result_rejected(self):
self.fixture.coordinator.result_path(
self.identifier
).write_text("{invalid")
with self.assertRaises(MigrationRecoveryError):
self.plan()
def test_failed_migration_rejected(self):
path = self.fixture.coordinator.result_path(
self.identifier
)
record = self.store.read(path)
record["status"] = "FAILED"
self.rewrite(path, record)
with self.assertRaises(MigrationRecoveryError):
self.plan()
def test_inconsistent_history_evidence_rejected(self):
path = self.fixture.coordinator.result_path(
self.identifier
)
record = self.store.read(path)
record["history_after"] = ["unexpected"]
self.rewrite(path, record)
with self.assertRaises(MigrationRecoveryError):
self.plan()
def test_wrong_site_rejected(self):
self.recovery.site = "different-site"
with self.assertRaises(MigrationRecoveryError):
self.plan()
def test_consumption_evidence_required(self):
self.store.consumed_path(
self.identifier
).unlink()
with self.assertRaises(MigrationRecoveryError):
self.plan()
def test_containment_required(self):
self.contained.return_value = False
with self.assertRaises(MigrationRecoveryError):
self.execute()
self.activate.assert_not_called()
def test_activation_intent_persisted_first(self):
def check(release):
path = self.recovery.intent_path(
self.identifier
)
self.assertTrue(path.exists())
self.active = release
return True
self.activate.side_effect = check
self.execute()
def test_activation_failure_preserves_containment(self):
self.activate.return_value = False
self.activate.side_effect = None
with self.assertRaises(MigrationRecoveryError):
self.execute()
self.release_containment.assert_not_called()
def test_refresh_failure_preserves_containment(self):
self.refresh.return_value = False
with self.assertRaises(MigrationRecoveryError):
self.execute()
self.release_containment.assert_not_called()
def test_readiness_required_before_reopening(self):
self.ready.return_value = False
with self.assertRaises(MigrationRecoveryError):
self.execute()
self.release_containment.assert_not_called()
def test_failed_health_reestablishes_containment(self):
self.health.side_effect = RuntimeError()
with self.assertRaises(MigrationRecoveryError):
self.execute()
self.assertGreaterEqual(
self.contain.call_count,
2,
)
def test_reopening_must_be_verified(self):
self.writes_enabled.return_value = False
with self.assertRaises(MigrationRecoveryError):
self.execute()
self.health.assert_not_called()
def test_existing_activation_intent_blocks_retry(self):
self.recovery.intent_path(
self.identifier
).touch(mode=0o600)
with self.assertRaises(MigrationRecoveryError):
self.execute()
self.activate.assert_not_called()
def test_successful_execution_cannot_repeat(self):
self.execute()
with self.assertRaises(MigrationRecoveryError):
self.execute()
self.activate.assert_called_once()
def test_concurrent_operation_rejected(self):
with DeploymentLock(
self.fixture.root / ".deployment.lock"
):
with self.assertRaises(LockError):
self.plan()
def test_original_migration_evidence_preserved(self):
path = self.fixture.coordinator.result_path(
self.identifier
)
before = path.read_bytes()
self.execute()
self.assertEqual(path.read_bytes(), before)
def test_database_rollback_prohibited(self):
result = self.execute()
self.assertFalse(
result["database_restored"]
)
self.assertFalse(
result["migration_reexecuted"]
)
def test_final_result_persisted(self):
result = self.execute()
self.assertEqual(
self.store.read(
self.recovery.result_path(self.identifier)
),
result,
)
def test_failure_result_persisted(self):
self.refresh.return_value = False
with self.assertRaises(MigrationRecoveryError):
self.execute()
result = self.store.read(
self.recovery.result_path(self.identifier)
)
self.assertEqual(result["status"], "FAILED")
if __name__ == "__main__":
unittest.main()
+179
View File
@@ -0,0 +1,179 @@
import os
import tempfile
import unittest
from pathlib import Path
from core.approval_store import ApprovalStore
from core.operation_guard import OperationGuard, OperationBlocked
class OperationGuardTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.store = ApprovalStore(self.root)
self.guard = OperationGuard(self.store)
self.identifier = "a" * 32
def marker(self, suffix):
path = self.root / (self.identifier + suffix)
path.touch(mode=0o600)
return path
def test_empty_store_clear(self):
self.assertEqual(self.guard.inspect()["status"], "CLEAR")
def test_empty_store_permits_operations(self):
self.guard.require_clear()
def test_unused_approval_permitted(self):
import test_approval_store
fixture = test_approval_store.ApprovalStoreTests()
self.addCleanup(fixture.doCleanups)
fixture.setUp()
fixture.save()
OperationGuard(fixture.store).require_clear()
def test_migration_intent_blocks(self):
self.marker(".migration-intent.json")
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_consumed_approval_blocks(self):
self.marker(".consumed.json")
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_migration_result_blocks_until_archived(self):
self.marker(".migration-result.json")
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_activation_intent_blocks(self):
self.marker(".activation-intent.json")
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_activation_result_blocks_until_archived(self):
self.marker(".activation-result.json")
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_successful_result_does_not_bypass_guard(self):
path = self.marker(".activation-result.json")
path.write_text('{"status":"VERIFIED"}')
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_corrupted_record_blocks(self):
path = self.marker(".migration-intent.json")
path.write_text("{invalid")
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_dangling_symlink_blocks(self):
path = self.root / (
self.identifier + ".migration-intent.json"
)
path.symlink_to(self.root / "missing")
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_directory_marker_blocks(self):
path = self.root / (
self.identifier + ".migration-result.json"
)
path.mkdir()
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_invalid_identifier_blocks(self):
(self.root / "invalid.migration-intent.json").touch()
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_temporary_publication_record_blocks(self):
(self.root / ".approval-tmp-interrupted").touch()
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_unknown_json_record_blocks(self):
(self.root / "unexpected.json").touch()
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_multiple_operations_reported(self):
self.marker(".migration-intent.json")
self.marker(".consumed.json")
result = self.guard.inspect()
self.assertEqual(result["status"], "BLOCKED")
self.assertEqual(len(result["blockers"]), 2)
def test_deterministic_report(self):
self.marker(".migration-result.json")
self.marker(".consumed.json")
self.assertEqual(
self.guard.inspect(),
self.guard.inspect(),
)
def test_read_only_inspection(self):
path = self.marker(".migration-intent.json")
path.write_text("original")
before = path.read_bytes()
self.guard.inspect()
self.assertEqual(path.read_bytes(), before)
def test_lock_file_ignored(self):
(self.root / ".approval.lock").touch(mode=0o600)
self.guard.require_clear()
def test_insecure_directory_blocks(self):
self.root.chmod(0o755)
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
def test_missing_directory_blocks(self):
self.root.rename(self.root.with_name(
self.root.name + "-moved"
))
moved = self.root.with_name(
self.root.name + "-moved"
)
self.addCleanup(moved.rmdir)
with self.assertRaises(OperationBlocked):
self.guard.require_clear()
if __name__ == "__main__":
unittest.main()
+310
View File
@@ -0,0 +1,310 @@
import copy
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from core.configuration import load_config
from core.preflight import PreflightError, site_preflight
from core.inspection_cli import provisioning_plan
ROOT = Path(__file__).resolve().parents[2]
class PreflightTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.config = load_config(
ROOT / "config/site.example.json"
)
self.other = copy.deepcopy(self.config)
self.other["site"].update({
"identifier": "other-absdev-net",
"domain": "other.absdev.net",
"root": "/opt/laravel-sites/other-absdev-net",
"origin_port": 8198,
})
self.other["docker"]["project"] = (
"site-other-absdev-net"
)
self.other["database"]["name"] = "other_db"
self.other["database"]["username"] = "other_app"
def preflight(self, registry=None):
return site_preflight(
self.config,
[] if registry is None else registry,
)
def write_json(self, name, data):
path = self.root / name
path.write_text(json.dumps(data))
return path
def cli(self, *args):
return subprocess.run(
[
sys.executable,
str(ROOT / "bin/absdev-deploy"),
*map(str, args),
],
cwd=ROOT,
capture_output=True,
text=True,
timeout=10,
)
def test_valid_preflight(self):
result = self.preflight()
self.assertEqual(
result["status"],
"STATIC_PREFLIGHT_PASSED",
)
def test_valid_existing_registry(self):
result = self.preflight([self.other])
self.assertEqual(result["site_count"], 2)
def test_duplicate_site_rejected(self):
with self.assertRaises(PreflightError):
self.preflight([self.config])
def test_port_conflict_rejected(self):
self.other["site"]["origin_port"] = (
self.config["site"]["origin_port"]
)
with self.assertRaises(PreflightError):
self.preflight([self.other])
def test_domain_conflict_rejected(self):
self.other["site"]["domain"] = (
self.config["site"]["domain"]
)
with self.assertRaises(PreflightError):
self.preflight([self.other])
def test_database_conflict_rejected(self):
self.other["database"]["name"] = (
self.config["database"]["name"]
)
with self.assertRaises(PreflightError):
self.preflight([self.other])
def test_username_conflict_rejected(self):
self.other["database"]["username"] = (
self.config["database"]["username"]
)
with self.assertRaises(PreflightError):
self.preflight([self.other])
def test_untrusted_site_root_rejected(self):
self.config["site"]["root"] = "/etc"
with self.assertRaises(PreflightError):
self.preflight()
def test_invalid_registry_rejected(self):
with self.assertRaises(PreflightError):
self.preflight("invalid")
def test_deterministic_preflight(self):
self.assertEqual(
self.preflight(),
self.preflight(),
)
def test_input_not_mutated(self):
original = copy.deepcopy(self.config)
self.preflight([self.other])
self.assertEqual(self.config, original)
def test_runtime_not_verified(self):
self.assertFalse(
self.preflight()["runtime_verified"]
)
def test_execution_disabled(self):
self.assertFalse(
self.preflight()["execution_permitted"]
)
def test_registry_completeness_not_assumed(self):
self.assertFalse(
self.preflight()["registry_completeness_verified"]
)
def test_provision_plan_enforces_site_policy(self):
self.config["database"]["username"] = "root"
with self.assertRaises(RuntimeError):
provisioning_plan(self.config)
def test_provision_plan_reports_static_validation(self):
result = provisioning_plan(self.config)
self.assertTrue(result["static_policy_verified"])
def test_cli_site_policy(self):
config = self.write_json(
"site.json",
self.config,
)
result = self.cli(
"site-policy",
"--config",
config,
)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(
json.loads(result.stdout)["status"],
"VALID",
)
def test_cli_registry_validation(self):
registry = self.write_json(
"registry.json",
[self.config, self.other],
)
result = self.cli(
"registry-validate",
"--registry",
registry,
)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(
json.loads(result.stdout)["site_count"],
2,
)
def test_cli_registry_conflict(self):
registry = self.write_json(
"registry.json",
[self.config, self.config],
)
result = self.cli(
"registry-validate",
"--registry",
registry,
)
self.assertNotEqual(result.returncode, 0)
def test_cli_preflight(self):
config = self.write_json("site.json", self.config)
registry = self.write_json("registry.json", [self.other])
result = self.cli(
"preflight",
"--config",
config,
"--registry",
registry,
)
self.assertEqual(result.returncode, 0, result.stderr)
report = json.loads(result.stdout)
self.assertEqual(
report["status"],
"STATIC_PREFLIGHT_PASSED",
)
self.assertFalse(report["execution_permitted"])
def test_cli_preflight_requires_registry(self):
config = self.write_json("site.json", self.config)
result = self.cli(
"preflight",
"--config",
config,
)
self.assertNotEqual(result.returncode, 0)
def test_cli_missing_registry_rejected(self):
result = self.cli(
"registry-validate",
"--registry",
self.root / "missing.json",
)
self.assertNotEqual(result.returncode, 0)
def test_cli_capabilities_updated(self):
result = self.cli("capabilities")
self.assertEqual(result.returncode, 0)
report = json.loads(result.stdout)
for command in (
"site-policy",
"registry-validate",
"preflight",
):
self.assertIn(command, report["commands"])
def test_cli_provisioning_rejects_unsafe_site(self):
self.config["site"]["root"] = "/etc"
config = self.write_json(
"site.json",
self.config,
)
result = self.cli(
"provision-plan",
"--config",
config,
)
self.assertNotEqual(result.returncode, 0)
def test_mutating_commands_remain_unavailable(self):
for command in (
"deploy",
"migrate",
"rollback",
"restore",
"provision",
"delete",
):
with self.subTest(command=command):
self.assertNotEqual(
self.cli(command).returncode,
0,
)
if __name__ == "__main__":
unittest.main()
+299
View File
@@ -0,0 +1,299 @@
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
from core.provenance import (
ProvenanceError,
ProvenanceVerifier,
)
class ProvenanceTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.repository = self.root / "repository"
self.repository.mkdir()
self.release = self.root / "release"
self.git("init", "-q")
self.git("config", "user.name", "Test User")
self.git("config", "user.email", "[email protected]")
files = {
"composer.json": "{}",
"composer.lock": "{}",
"package.json": "{}",
"package-lock.json": "{}",
"database/migrations/0001_create_users.php":
"<?php // users\n",
"database/migrations/0002_create_orders.php":
"<?php // orders\n",
}
for name, content in files.items():
path = self.repository / name
path.parent.mkdir(
parents=True,
exist_ok=True,
)
path.write_text(content)
self.git("add", ".")
self.git("commit", "-qm", "Test release")
self.revision = self.git(
"rev-parse", "HEAD"
).strip()
shutil.copytree(
self.repository,
self.release,
ignore=shutil.ignore_patterns(".git"),
)
(self.release / "REVISION").write_text(
self.revision + "\n"
)
self.verifier = ProvenanceVerifier(
self.repository
)
def git(self, *args):
return subprocess.check_output(
[
"git",
"-C",
str(self.repository),
*args,
],
stdin=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
text=True,
timeout=20,
)
def verify(self):
return self.verifier.verify(self.release)
def test_valid_release(self):
self.assertEqual(
self.verify()["revision"],
self.revision,
)
def test_migration_inventory(self):
self.assertEqual(
len(self.verify()["migrations"]),
2,
)
def test_dependency_inventory(self):
self.assertEqual(
len(self.verify()["dependencies"]),
4,
)
def test_deterministic_fingerprint(self):
self.assertEqual(
self.verify()["fingerprint"],
self.verify()["fingerprint"],
)
def test_fingerprint_format(self):
self.assertRegex(
self.verify()["fingerprint"],
r"^[a-f0-9]{64}$",
)
def test_modified_migration_rejected(self):
path = (
self.release
/ "database/migrations/0001_create_users.php"
)
path.write_text("modified")
with self.assertRaises(ProvenanceError):
self.verify()
def test_missing_migration_rejected(self):
(
self.release
/ "database/migrations/0001_create_users.php"
).unlink()
with self.assertRaises(ProvenanceError):
self.verify()
def test_unexpected_migration_rejected(self):
(
self.release
/ "database/migrations/unexpected.php"
).write_text("unexpected")
with self.assertRaises(ProvenanceError):
self.verify()
def test_modified_composer_manifest_rejected(self):
(self.release / "composer.json").write_text("changed")
with self.assertRaises(ProvenanceError):
self.verify()
def test_modified_composer_lock_rejected(self):
(self.release / "composer.lock").write_text("changed")
with self.assertRaises(ProvenanceError):
self.verify()
def test_modified_package_manifest_rejected(self):
(self.release / "package.json").write_text("changed")
with self.assertRaises(ProvenanceError):
self.verify()
def test_modified_package_lock_rejected(self):
(self.release / "package-lock.json").write_text("changed")
with self.assertRaises(ProvenanceError):
self.verify()
def test_missing_dependency_rejected(self):
(self.release / "composer.lock").unlink()
with self.assertRaises(ProvenanceError):
self.verify()
def test_invalid_revision_rejected(self):
(self.release / "REVISION").write_text("invalid")
with self.assertRaises(ProvenanceError):
self.verify()
def test_unknown_revision_rejected(self):
(self.release / "REVISION").write_text("a" * 40)
with self.assertRaises(ProvenanceError):
self.verify()
def test_missing_revision_rejected(self):
(self.release / "REVISION").unlink()
with self.assertRaises(ProvenanceError):
self.verify()
def test_symlink_revision_rejected(self):
path = self.release / "REVISION"
path.unlink()
target = self.root / "revision"
target.write_text(self.revision)
path.symlink_to(target)
with self.assertRaises(ProvenanceError):
self.verify()
def test_symlink_migration_rejected(self):
path = (
self.release
/ "database/migrations/0001_create_users.php"
)
original = path.read_bytes()
path.unlink()
target = self.root / "migration.php"
target.write_bytes(original)
path.symlink_to(target)
with self.assertRaises(ProvenanceError):
self.verify()
def test_symlink_dependency_rejected(self):
path = self.release / "composer.json"
path.unlink()
path.symlink_to(
self.repository / "composer.json"
)
with self.assertRaises(ProvenanceError):
self.verify()
def test_symlink_migration_directory_rejected(self):
path = self.release / "database/migrations"
shutil.rmtree(path)
path.symlink_to(
self.repository / "database/migrations"
)
with self.assertRaises(ProvenanceError):
self.verify()
def test_invalid_repository_rejected(self):
with self.assertRaises(ProvenanceError):
ProvenanceVerifier(
self.root / "missing"
)
def test_symlink_release_rejected(self):
link = self.root / "linked-release"
link.symlink_to(self.release)
with self.assertRaises(ProvenanceError):
self.verifier.verify(link)
def test_no_git_repository_required_in_release(self):
self.assertFalse(
(self.release / ".git").exists()
)
self.verify()
if __name__ == "__main__":
unittest.main()
+463
View File
@@ -0,0 +1,463 @@
import copy
import tempfile
import unittest
from pathlib import Path
from unittest.mock import Mock
from core.compatibility import provenance_fingerprint
from core.recovery import RecoveryPlanner, RecoveryError
from core.transactions import TransactionJournal
from core.backup_evidence import BackupEvidence
from core.releases import ReleaseManager
from core.locking import DeploymentLock, LockError
def provenance(revision):
data = {
"format_version": 1,
"revision": revision,
"migrations": {
"database/migrations/0001_users.php": "a" * 64,
},
"dependencies": {
"composer.json": "b" * 64,
"composer.lock": "c" * 64,
"package.json": "d" * 64,
"package-lock.json": "e" * 64,
},
}
data["fingerprint"] = provenance_fingerprint(data)
return data
class RecoveryTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.app = self.root / "app"
self.app.mkdir()
(self.app / "releases").mkdir()
self.state = self.root / "state"
self.state.mkdir(mode=0o700)
self.releases = ReleaseManager(self.app)
self.journal = TransactionJournal(self.state)
self.evidence = BackupEvidence(self.state)
self.old = provenance("a" * 40)
self.new = provenance("b" * 40)
for number, evidence in (
("1", self.old),
("2", self.new),
("3", provenance("c" * 40)),
):
root = self.app / "releases" / number
(root / "vendor").mkdir(parents=True)
(root / "public/build").mkdir(parents=True)
(root / "vendor/autoload.php").write_text(
"<?php\n"
)
(root / "public/build/manifest.json").write_text(
"{}"
)
(root / "REVISION").write_text(
evidence["revision"] + "\n"
)
self.releases.activate("1")
self.provenance = Mock()
self.provenance.verify.side_effect = (
lambda path: copy.deepcopy(
self.old if path.name == "1" else self.new
)
)
self.manifest = {
"backup_id": "fixture-backup",
"driver": "mysql",
"database": "example_db",
"username": "example_app",
"container": "example-mysql",
"identity": "fixture-server",
"filename": "database.sql",
"sha256": "f" * 64,
"bytes": 1024,
}
self.backup_verify = Mock(
return_value=copy.deepcopy(self.manifest)
)
self.runtime_check = Mock(return_value=True)
self.planner = RecoveryPlanner(
site="example-absdev-net",
lock_path=self.root / ".deployment.lock",
releases=self.releases,
provenance=self.provenance,
journal=self.journal,
backup_evidence=self.evidence,
backup_verify=self.backup_verify,
runtime_check=self.runtime_check,
)
def prepare(self, failed=True):
transaction = self.journal.create(
"example-absdev-net",
"1",
"2",
self.new["revision"],
self.new["fingerprint"],
previous_revision=self.old["revision"],
previous_provenance=self.old["fingerprint"],
)
self.evidence.create(
transaction["transaction_id"],
self.manifest,
)
for phase in (
"BACKED_UP",
"QUIESCED",
"ACTIVATING",
):
transaction = self.journal.transition(
transaction["transaction_id"],
transaction["phase"],
phase,
)
self.releases.activate("2")
transaction = self.journal.transition(
transaction["transaction_id"],
"ACTIVATING",
"ACTIVATED",
)
return self.journal.transition(
transaction["transaction_id"],
"ACTIVATED",
"FAILED" if failed else "VERIFIED",
)
def test_clear_status(self):
self.assertEqual(
self.planner.inspect()["status"],
"CLEAR",
)
def test_failed_transaction_rollback_plan(self):
self.prepare()
result = self.planner.inspect()
self.assertEqual(
result["status"],
"ROLLBACK_REVIEW_READY",
)
self.assertEqual(result["target"], "1")
def test_verified_transaction_not_rollback_eligible(self):
self.prepare(failed=False)
self.assertEqual(
self.planner.inspect()["status"],
"VERIFIED",
)
def test_plan_is_read_only(self):
self.prepare()
before = self.journal.load()
current = self.releases.current()
self.planner.inspect()
self.assertEqual(self.journal.load(), before)
self.assertEqual(self.releases.current(), current)
def test_backup_verification_required(self):
self.prepare()
self.planner.inspect()
self.backup_verify.assert_called_once_with(
"fixture-backup"
)
def test_backup_checksum_mismatch_rejected(self):
self.prepare()
self.backup_verify.return_value["sha256"] = "0" * 64
with self.assertRaises(RecoveryError):
self.planner.inspect()
def test_database_identity_mismatch_rejected(self):
self.prepare()
self.backup_verify.return_value["identity"] = (
"different-server"
)
with self.assertRaises(RecoveryError):
self.planner.inspect()
def test_backup_size_mismatch_rejected(self):
self.prepare()
self.backup_verify.return_value["bytes"] = 99
with self.assertRaises(RecoveryError):
self.planner.inspect()
def test_backup_failure_rejected(self):
self.prepare()
self.backup_verify.side_effect = RuntimeError()
with self.assertRaises(RecoveryError):
self.planner.inspect()
def test_runtime_check_required(self):
self.prepare()
self.runtime_check.return_value = False
with self.assertRaises(RecoveryError):
self.planner.inspect()
def test_wrong_active_release_rejected(self):
self.prepare()
self.releases.activate("3")
with self.assertRaises(RecoveryError):
self.planner.inspect()
def test_previous_release_already_active(self):
self.prepare()
self.releases.activate("1")
self.assertEqual(
self.planner.inspect()["status"],
"PREVIOUS_ACTIVE_REVIEW_REQUIRED",
)
def test_bad_previous_release_rejected(self):
self.prepare()
(
self.releases.release_path("1") / "BAD_RELEASE"
).touch()
with self.assertRaises(RecoveryError):
self.planner.inspect()
def test_missing_previous_release_rejected(self):
self.prepare()
self.releases.release_path("1").rename(
self.root / "removed-release"
)
with self.assertRaises(RecoveryError):
self.planner.inspect()
def test_changed_candidate_provenance_rejected(self):
self.prepare()
self.new["dependencies"]["composer.lock"] = "0" * 64
self.new["fingerprint"] = provenance_fingerprint(
self.new
)
with self.assertRaises(RecoveryError):
self.planner.inspect()
def test_migration_difference_rejected(self):
self.prepare()
self.old["migrations"][
"database/migrations/0001_users.php"
] = "0" * 64
self.old["fingerprint"] = provenance_fingerprint(
self.old
)
with self.assertRaises(RecoveryError):
self.planner.inspect()
def test_missing_backup_evidence_rejected(self):
transaction = self.prepare()
self.evidence.path(
transaction["transaction_id"]
).unlink()
with self.assertRaises(RecoveryError):
self.planner.inspect()
def test_corrupt_backup_evidence_rejected(self):
transaction = self.prepare()
self.evidence.path(
transaction["transaction_id"]
).write_text("{invalid")
with self.assertRaises(RecoveryError):
self.planner.inspect()
def test_concurrent_operation_rejected(self):
self.prepare()
with DeploymentLock(
self.root / ".deployment.lock"
):
with self.assertRaises(LockError):
self.planner.inspect()
def test_confirmation_bound_to_transaction(self):
transaction = self.prepare()
result = self.planner.inspect()
self.assertEqual(
result["confirmation"],
"ROLLBACK-" + transaction["transaction_id"],
)
def test_automatic_rollback_prohibited(self):
self.prepare()
self.assertFalse(
self.planner.inspect()[
"automatic_rollback_allowed"
]
)
def test_database_restore_prohibited(self):
self.prepare()
self.assertFalse(
self.planner.inspect()[
"database_restore_allowed"
]
)
def test_deterministic_plan(self):
self.prepare()
self.assertEqual(
self.planner.inspect(),
self.planner.inspect(),
)
def test_prepared_transaction_requires_review(self):
self.journal.create(
"example-absdev-net",
"1",
"2",
self.new["revision"],
self.new["fingerprint"],
)
self.assertEqual(
self.planner.inspect()["status"],
"PREVIOUS_ACTIVE_REVIEW_REQUIRED",
)
self.backup_verify.assert_not_called()
def test_wrong_site_rejected(self):
self.prepare()
self.planner.site = "different-site"
with self.assertRaises(RecoveryError):
self.planner.inspect()
def test_replaced_previous_revision_rejected(self):
self.prepare()
self.old["revision"] = "d" * 40
self.old["fingerprint"] = provenance_fingerprint(
self.old
)
with self.assertRaises(RecoveryError):
self.planner.inspect()
def test_changed_previous_dependencies_rejected(self):
self.prepare()
self.old["dependencies"]["composer.lock"] = "0" * 64
self.old["fingerprint"] = provenance_fingerprint(
self.old
)
with self.assertRaises(RecoveryError):
self.planner.inspect()
if __name__ == "__main__":
unittest.main()
+390
View File
@@ -0,0 +1,390 @@
import copy
import unittest
from datetime import datetime, timedelta, timezone
from core.compatibility import canonical_hash
from core.rehearsal import (
RehearsalError,
create_rehearsal,
verify_rehearsal,
approval_context,
)
class RehearsalTests(unittest.TestCase):
def setUp(self):
self.now = datetime(
2026, 11, 26, 10, 0,
tzinfo=timezone.utc,
)
self.context = {
"site": "example-absdev-net",
"release": "2",
"revision": "a" * 40,
"provenance": "b" * 64,
"compatibility": "c" * 64,
"database_identity": "d" * 64,
"backup_sha256": "e" * 64,
"pending_migrations": [
"2026_11_26_100000_create_products"
],
}
self.execution = {
"driver": "mysql",
"source_database": "example_db",
"target_database": "isolated_restore_fixture",
"target_identity": "f" * 64,
"applied_migrations": list(
self.context["pending_migrations"]
),
"checks": {
"isolation_verified": True,
"backup_restored": True,
"migration_succeeded": True,
"migration_history_verified": True,
"application_verified": True,
"cleanup_verified": True,
},
}
def create(self):
return create_rehearsal(
self.context,
self.execution,
completed_at=self.now,
)
def verify(self, record=None, now=None):
return verify_rehearsal(
self.create() if record is None else record,
self.context,
now=self.now if now is None else now,
)
def test_valid_rehearsal(self):
self.assertTrue(self.verify())
def test_rehearsal_identifier(self):
self.assertRegex(
self.create()["rehearsal_id"],
r"^[a-f0-9]{32}$",
)
def test_unique_rehearsal_identifier(self):
self.assertNotEqual(
self.create()["rehearsal_id"],
self.create()["rehearsal_id"],
)
def test_fingerprint_format(self):
self.assertRegex(
self.create()["fingerprint"],
r"^[a-f0-9]{64}$",
)
def test_live_database_target_rejected(self):
self.execution["target_database"] = "example_db"
with self.assertRaises(RehearsalError):
self.create()
def test_invalid_target_prefix_rejected(self):
self.execution["target_database"] = "other_database"
with self.assertRaises(RehearsalError):
self.create()
def test_same_database_identity_rejected(self):
self.execution["target_identity"] = (
self.context["database_identity"]
)
with self.assertRaises(RehearsalError):
self.create()
def test_invalid_target_identity_rejected(self):
self.execution["target_identity"] = "invalid"
with self.assertRaises(RehearsalError):
self.create()
def test_invalid_driver_rejected(self):
self.execution["driver"] = "sqlite"
with self.assertRaises(RehearsalError):
self.create()
def test_postgresql_supported(self):
self.execution["driver"] = "postgresql"
self.assertTrue(self.verify())
def test_missing_applied_migration_rejected(self):
self.execution["applied_migrations"] = []
with self.assertRaises(RehearsalError):
self.create()
def test_unexpected_applied_migration_rejected(self):
self.execution["applied_migrations"].append(
"unexpected_migration"
)
with self.assertRaises(RehearsalError):
self.create()
def test_migration_order_mismatch_rejected(self):
self.context["pending_migrations"].append(
"2026_11_26_110000_create_orders"
)
self.execution["applied_migrations"] = list(
reversed(
self.context["pending_migrations"]
)
)
with self.assertRaises(RehearsalError):
self.create()
def test_every_check_is_mandatory(self):
for field in self.execution["checks"]:
with self.subTest(field=field):
self.execution["checks"][field] = False
with self.assertRaises(RehearsalError):
self.create()
self.execution["checks"][field] = True
def test_numeric_check_rejected(self):
self.execution["checks"]["backup_restored"] = 1
with self.assertRaises(RehearsalError):
self.create()
def test_missing_check_rejected(self):
del self.execution["checks"]["cleanup_verified"]
with self.assertRaises(RehearsalError):
self.create()
def test_unknown_check_rejected(self):
self.execution["checks"]["unexpected"] = True
with self.assertRaises(RehearsalError):
self.create()
def test_changed_backup_rejected(self):
record = self.create()
self.context["backup_sha256"] = "0" * 64
with self.assertRaises(RehearsalError):
self.verify(record)
def test_changed_release_rejected(self):
record = self.create()
self.context["release"] = "3"
with self.assertRaises(RehearsalError):
self.verify(record)
def test_changed_database_rejected(self):
record = self.create()
self.context["database_identity"] = "0" * 64
with self.assertRaises(RehearsalError):
self.verify(record)
def test_changed_pending_migrations_rejected(self):
record = self.create()
self.context["pending_migrations"].append(
"unexpected_migration"
)
with self.assertRaises(RehearsalError):
self.verify(record)
def test_expired_rehearsal_rejected(self):
record = self.create()
with self.assertRaises(RehearsalError):
self.verify(
record,
self.now + timedelta(hours=24),
)
def test_future_rehearsal_rejected(self):
record = self.create()
with self.assertRaises(RehearsalError):
self.verify(
record,
self.now - timedelta(seconds=1),
)
def test_modified_evidence_rejected(self):
record = self.create()
record["execution"]["target_identity"] = "0" * 64
with self.assertRaises(RehearsalError):
self.verify(record)
def test_invalid_check_with_new_fingerprint_rejected(self):
record = self.create()
record["execution"]["checks"][
"isolation_verified"
] = False
del record["fingerprint"]
record["fingerprint"] = canonical_hash(record)
with self.assertRaises(RehearsalError):
self.verify(record)
def test_unknown_record_field_rejected(self):
record = self.create()
record["unexpected"] = True
with self.assertRaises(RehearsalError):
self.verify(record)
def test_unknown_execution_field_rejected(self):
self.execution["password"] = "private-secret"
with self.assertRaises(RehearsalError):
self.create()
def test_input_not_mutated(self):
original = copy.deepcopy(self.execution)
self.create()
self.assertEqual(self.execution, original)
def test_record_independent_of_input(self):
record = self.create()
self.execution["checks"]["backup_restored"] = False
self.assertTrue(
record["execution"]["checks"]["backup_restored"]
)
def test_approval_context_binding(self):
record = self.create()
result = approval_context(
record,
self.context,
now=self.now,
)
self.assertEqual(
result["rehearsal_fingerprint"],
record["fingerprint"],
)
def test_expired_rehearsal_cannot_create_approval_context(self):
record = self.create()
with self.assertRaises(RehearsalError):
approval_context(
record,
self.context,
now=self.now + timedelta(hours=25),
)
def test_approval_policy_integration(self):
from core.approval import (
issue_approval,
verify_approval,
)
record = self.create()
context = approval_context(
record,
self.context,
now=self.now,
)
approval = issue_approval(
context,
approver="operator",
now=self.now,
)
self.assertTrue(
verify_approval(
approval,
context,
confirmation=approval["confirmation"],
now=self.now,
)
)
def test_invalid_source_database_rejected(self):
self.execution["source_database"] = "../outside"
with self.assertRaises(RehearsalError):
self.create()
def test_naive_timestamp_rejected(self):
with self.assertRaises(RehearsalError):
create_rehearsal(
self.context,
self.execution,
completed_at=self.now.replace(tzinfo=None),
)
def test_invalid_record_type_rejected(self):
with self.assertRaises(RehearsalError):
verify_rehearsal(
"invalid",
self.context,
now=self.now,
)
if __name__ == "__main__":
unittest.main()
+212
View File
@@ -0,0 +1,212 @@
import tempfile
import unittest
from pathlib import Path
from core.releases import ReleaseManager, ReleaseError
class ReleaseTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.app = Path(self.temp.name) / "app"
self.app.mkdir()
self.releases = self.app / "releases"
self.releases.mkdir()
self.manager = ReleaseManager(self.app)
def create_release(self, number):
root = self.releases / str(number)
root.mkdir()
(root / "vendor").mkdir()
(root / "public/build").mkdir(parents=True)
(root / "vendor/autoload.php").write_text(
"<?php\n"
)
(root / "public/build/manifest.json").write_text(
"{}"
)
(root / "REVISION").write_text(
"a" * 40 + "\n"
)
return root
def test_empty_inventory(self):
self.assertEqual(self.manager.inventory(), [])
def test_numeric_sorting(self):
for number in (10, 2, 1):
self.create_release(number)
self.assertEqual(
self.manager.inventory(),
["1", "2", "10"],
)
def test_no_active_release(self):
self.assertIsNone(self.manager.current())
def test_initial_activation(self):
self.create_release(1)
self.manager.activate("1")
self.assertEqual(
self.manager.current(), "1"
)
def test_switch_release(self):
self.create_release(1)
self.create_release(2)
self.manager.activate("1")
self.manager.activate("2")
self.assertEqual(
self.manager.current(), "2"
)
def test_relative_activation_link(self):
self.create_release(1)
self.manager.activate("1")
self.assertEqual(
str((self.app / "current").readlink()),
"releases/1",
)
def test_previous_release_preserved(self):
self.create_release(1)
self.create_release(2)
self.manager.activate("1")
self.manager.activate("2")
self.assertTrue(
(self.releases / "1").is_dir()
)
def test_missing_release_rejected(self):
with self.assertRaises(ReleaseError):
self.manager.activate("99")
def test_path_traversal_rejected(self):
with self.assertRaises(ReleaseError):
self.manager.activate("../outside")
def test_invalid_release_number(self):
for value in ("0", "-1", "01", "abc"):
with self.subTest(value=value):
with self.assertRaises(ReleaseError):
self.manager.activate(value)
def test_bad_release_rejected(self):
root = self.create_release(1)
(root / "BAD_RELEASE").touch()
with self.assertRaises(ReleaseError):
self.manager.activate("1")
def test_missing_vendor_rejected(self):
root = self.create_release(1)
(root / "vendor/autoload.php").unlink()
with self.assertRaises(ReleaseError):
self.manager.activate("1")
def test_missing_manifest_rejected(self):
root = self.create_release(1)
(root / "public/build/manifest.json").unlink()
with self.assertRaises(ReleaseError):
self.manager.activate("1")
def test_invalid_revision_rejected(self):
root = self.create_release(1)
(root / "REVISION").write_text("invalid")
with self.assertRaises(ReleaseError):
self.manager.activate("1")
def test_symlink_release_rejected(self):
root = self.create_release(1)
(self.releases / "2").symlink_to(root)
with self.assertRaises(ReleaseError):
self.manager.activate("2")
def test_invalid_current_link_rejected(self):
(self.app / "current").symlink_to("/tmp")
with self.assertRaises(ReleaseError):
self.manager.current()
def test_current_regular_file_rejected(self):
(self.app / "current").touch()
with self.assertRaises(ReleaseError):
self.manager.current()
def test_failed_activation_preserves_current(self):
self.create_release(1)
self.manager.activate("1")
with self.assertRaises(ReleaseError):
self.manager.activate("2")
self.assertEqual(
self.manager.current(), "1"
)
def test_no_temporary_activation_links(self):
self.create_release(1)
self.manager.activate("1")
self.assertEqual(
sorted(p.name for p in self.app.iterdir()),
["current", "releases"],
)
def test_invalid_inventory_entry(self):
(self.releases / "unexpected").mkdir()
with self.assertRaises(ReleaseError):
self.manager.inventory()
if __name__ == "__main__":
unittest.main()
+273
View File
@@ -0,0 +1,273 @@
import unittest
from core.retention import RetentionError, plan_retention
class RetentionTests(unittest.TestCase):
def setUp(self):
self.releases = [str(i) for i in range(1, 11)]
self.options = {
"inventory": self.releases,
"current": "10",
"keep": 5,
"protected": [],
"failed": [],
"unresolved": [],
}
def plan(self, **changes):
return plan_retention({
**self.options,
**changes,
})
def test_default_retention(self):
result = self.plan()
self.assertEqual(
result["retained"],
["6", "7", "8", "9", "10"],
)
self.assertEqual(
result["archive_candidates"],
["1", "2", "3", "4", "5"],
)
def test_active_release_protected(self):
result = self.plan(current="1")
self.assertIn("1", result["retained"])
self.assertNotIn("1", result["archive_candidates"])
def test_explicitly_protected_release(self):
result = self.plan(protected=["2"])
self.assertIn("2", result["retained"])
def test_multiple_protected_releases(self):
result = self.plan(protected=["1", "2", "3"])
for release in ("1", "2", "3"):
self.assertIn(release, result["retained"])
def test_failed_release_preserved(self):
result = self.plan(failed=["1"])
self.assertIn("1", result["retained"])
def test_failed_current_rejected(self):
with self.assertRaises(RetentionError):
self.plan(failed=["10"])
def test_unresolved_transaction_blocks_archival(self):
result = self.plan(unresolved=["1", "2"])
self.assertEqual(result["status"], "BLOCKED")
self.assertEqual(result["archive_candidates"], [])
self.assertEqual(result["retained"], self.releases)
def test_no_automatic_deletion(self):
self.assertFalse(
self.plan()["automatic_deletion"]
)
def test_no_automatic_archival(self):
self.assertFalse(
self.plan()["automatic_archival"]
)
def test_small_inventory_retained(self):
result = self.plan(
inventory=["1", "2"],
current="2",
)
self.assertEqual(result["archive_candidates"], [])
def test_single_release_retained(self):
result = self.plan(
inventory=["1"],
current="1",
)
self.assertEqual(result["retained"], ["1"])
def test_empty_inventory_rejected(self):
with self.assertRaises(RetentionError):
self.plan(inventory=[])
def test_missing_current_rejected(self):
with self.assertRaises(RetentionError):
self.plan(current="99")
def test_duplicate_release_rejected(self):
with self.assertRaises(RetentionError):
self.plan(inventory=["1", "1", "10"])
def test_numeric_release_order(self):
result = self.plan(
inventory=["100", "2", "10", "1"],
current="100",
keep=2,
)
self.assertEqual(
result["retained"],
["10", "100"],
)
def test_invalid_release_identifiers(self):
for value in (
"../outside", "0", "01",
"-1", "", 10, True, "1.0",
):
with self.subTest(value=value):
with self.assertRaises(RetentionError):
self.plan(inventory=["10", value])
def test_invalid_retention_values(self):
for value in (
0, 1, -1, True, "5", 1001,
):
with self.subTest(value=value):
with self.assertRaises(RetentionError):
self.plan(keep=value)
def test_missing_protected_release_rejected(self):
with self.assertRaises(RetentionError):
self.plan(protected=["99"])
def test_missing_failed_release_rejected(self):
with self.assertRaises(RetentionError):
self.plan(failed=["99"])
def test_missing_unresolved_release_rejected(self):
with self.assertRaises(RetentionError):
self.plan(unresolved=["99"])
def test_duplicate_protected_release_rejected(self):
with self.assertRaises(RetentionError):
self.plan(protected=["1", "1"])
def test_invalid_inventory_type(self):
with self.assertRaises(RetentionError):
self.plan(inventory="123")
def test_invalid_protection_type(self):
with self.assertRaises(RetentionError):
self.plan(protected="1")
def test_missing_policy_field_rejected(self):
data = dict(self.options)
del data["failed"]
with self.assertRaises(RetentionError):
plan_retention(data)
def test_unknown_policy_field_rejected(self):
with self.assertRaises(RetentionError):
self.plan(delete=True)
def test_input_not_mutated(self):
original = list(self.releases)
self.plan()
self.assertEqual(self.releases, original)
def test_plan_fingerprint(self):
self.assertRegex(
self.plan()["fingerprint"],
r"^[a-f0-9]{64}$",
)
def test_deterministic_plan(self):
self.assertEqual(self.plan(), self.plan())
def test_fingerprint_changes_with_policy(self):
self.assertNotEqual(
self.plan()["fingerprint"],
self.plan(keep=6)["fingerprint"],
)
def test_fingerprint_changes_with_protection(self):
self.assertNotEqual(
self.plan()["fingerprint"],
self.plan(protected=["1"])["fingerprint"],
)
def test_all_releases_accounted_for(self):
result = self.plan(
protected=["1"],
failed=["2"],
)
retained = set(result["retained"])
candidates = set(result["archive_candidates"])
self.assertFalse(retained & candidates)
self.assertEqual(
retained | candidates,
set(self.releases),
)
def test_retention_reasons(self):
result = self.plan(
protected=["1"],
failed=["2"],
)
self.assertIn(
"active",
result["reasons"]["10"],
)
self.assertIn(
"explicitly_protected",
result["reasons"]["1"],
)
self.assertIn(
"failed_release",
result["reasons"]["2"],
)
def test_no_candidates_when_every_release_protected(self):
result = self.plan(protected=self.releases)
self.assertEqual(result["archive_candidates"], [])
def test_keep_larger_than_inventory(self):
result = self.plan(keep=100)
self.assertEqual(result["archive_candidates"], [])
def test_previous_healthy_release_preserved(self):
result = self.plan(
current="5",
keep=2,
)
self.assertIn("4", result["retained"])
def test_failed_release_not_selected_as_previous(self):
result = self.plan(
current="5",
keep=2,
failed=["4"],
)
self.assertIn("3", result["retained"])
self.assertIn(
"previous_available",
result["reasons"]["3"],
)
if __name__ == "__main__":
unittest.main()
+325
View File
@@ -0,0 +1,325 @@
import json
import stat
import unittest
from unittest.mock import Mock
import test_recovery
from core.rollback import RollbackExecutor, RollbackError
from core.locking import DeploymentLock, LockError
class RollbackTests(unittest.TestCase):
def setUp(self):
self.fixture = test_recovery.RecoveryTests()
self.addCleanup(self.fixture.doCleanups)
self.fixture.setUp()
self.fixture.prepare()
self.services = Mock()
self.stopped = Mock(return_value=True)
self.health = Mock()
self.health.verify.side_effect = (
lambda release: {
"healthy": True,
"release": release,
}
)
self.executor = RollbackExecutor(
planner=self.fixture.planner,
services=self.services,
health=self.health,
stopped_check=self.stopped,
)
self.plan = self.fixture.planner.inspect()
def execute(self):
return self.executor.execute(
self.plan["confirmation"],
self.plan["plan_fingerprint"],
)
def test_successful_rollback(self):
result = self.execute()
self.assertEqual(result["status"], "ROLLED_BACK")
self.assertEqual(
self.fixture.releases.current(),
"1",
)
def test_wrong_confirmation_rejected(self):
with self.assertRaises(RollbackError):
self.executor.execute(
"INVALID",
self.plan["plan_fingerprint"],
)
self.services.quiesce.assert_not_called()
def test_wrong_fingerprint_rejected(self):
with self.assertRaises(RollbackError):
self.executor.execute(
self.plan["confirmation"],
"0" * 64,
)
self.services.quiesce.assert_not_called()
def test_changed_provenance_rejected(self):
self.fixture.old["revision"] = "0" * 40
with self.assertRaises(RollbackError):
self.execute()
self.services.quiesce.assert_not_called()
def test_changed_backup_rejected(self):
self.fixture.backup_verify.return_value[
"sha256"
] = "0" * 64
with self.assertRaises(RollbackError):
self.execute()
self.services.quiesce.assert_not_called()
def test_intent_persisted_before_shutdown(self):
def check():
path = self.executor.intent_path(
self.plan["transaction_id"]
)
record = json.loads(path.read_text())
self.assertEqual(
record["status"],
"ROLLBACK_INTENT",
)
self.services.quiesce.side_effect = check
self.execute()
def test_worker_shutdown_required(self):
self.stopped.return_value = False
with self.assertRaises(RollbackError):
self.execute()
self.assertEqual(
self.fixture.releases.current(),
"2",
)
def test_service_refresh_failure(self):
self.services.refresh.side_effect = RuntimeError()
with self.assertRaises(RollbackError):
self.execute()
self.assertEqual(
self.fixture.releases.current(),
"1",
)
self.services.resume.assert_not_called()
def test_health_failure_contains_workers(self):
self.health.verify.side_effect = RuntimeError()
with self.assertRaises(RollbackError):
self.execute()
self.assertEqual(
self.services.quiesce.call_count,
2,
)
def test_unhealthy_result_rejected(self):
self.health.verify.side_effect = None
self.health.verify.return_value = {
"healthy": False,
"release": "1",
}
with self.assertRaises(RollbackError):
self.execute()
def test_wrong_health_release_rejected(self):
self.health.verify.side_effect = None
self.health.verify.return_value = {
"healthy": True,
"release": "2",
}
with self.assertRaises(RollbackError):
self.execute()
def test_repeated_execution_rejected(self):
self.execute()
with self.assertRaises(RollbackError):
self.execute()
self.services.refresh.assert_called_once()
def test_failed_rollback_cannot_repeat(self):
self.stopped.return_value = False
with self.assertRaises(RollbackError):
self.execute()
self.stopped.return_value = True
with self.assertRaises(RollbackError):
self.execute()
self.services.refresh.assert_not_called()
def test_original_transaction_preserved(self):
original = self.fixture.journal.load()
self.execute()
self.assertEqual(
self.fixture.journal.load(),
original,
)
def test_success_evidence_persisted(self):
result = self.execute()
path = self.executor.result_path(
self.plan["transaction_id"]
)
self.assertEqual(
json.loads(path.read_text()),
result,
)
def test_evidence_permissions(self):
self.execute()
for path in (
self.executor.intent_path(
self.plan["transaction_id"]
),
self.executor.result_path(
self.plan["transaction_id"]
),
):
self.assertEqual(
stat.S_IMODE(path.stat().st_mode),
0o600,
)
def test_concurrent_operation_rejected(self):
with DeploymentLock(
self.fixture.root / ".deployment.lock"
):
with self.assertRaises(LockError):
self.execute()
def test_failed_release_preserved(self):
self.execute()
self.assertTrue(
self.fixture.releases.release_path("2").is_dir()
)
def test_database_restoration_prohibited(self):
result = self.execute()
self.assertFalse(result["database_restored"])
def test_runtime_rechecked_after_shutdown(self):
def change_runtime():
self.fixture.runtime_check.return_value = False
self.services.quiesce.side_effect = change_runtime
with self.assertRaises(RollbackError):
self.execute()
self.assertEqual(
self.fixture.releases.current(),
"2",
)
def test_existing_intent_blocks_execution(self):
path = self.executor.intent_path(
self.plan["transaction_id"]
)
path.touch(mode=0o600)
with self.assertRaises(RollbackError):
self.execute()
self.services.quiesce.assert_not_called()
def test_successful_health_verification(self):
self.execute()
self.health.verify.assert_called_once_with("1")
def test_invalid_confirmation_has_no_intent(self):
with self.assertRaises(RollbackError):
self.executor.execute(
"INVALID",
self.plan["plan_fingerprint"],
)
self.assertFalse(
self.executor.intent_path(
self.plan["transaction_id"]
).exists()
)
if __name__ == "__main__":
unittest.main()
+252
View File
@@ -0,0 +1,252 @@
import json
import unittest
from unittest.mock import Mock, patch
import test_rollback
from core.rollback_archive import RollbackArchive, ArchiveError
from core.compatibility import canonical_hash
from core.locking import DeploymentLock, LockError
class RollbackArchiveTests(unittest.TestCase):
def setUp(self):
self.fixture = test_rollback.RollbackTests()
self.addCleanup(self.fixture.doCleanups)
self.fixture.setUp()
self.fixture.execute()
self.recovery = self.fixture.fixture
self.planner = self.recovery.planner
self.journal = self.recovery.journal
self.transaction = self.journal.load()
self.identifier = self.transaction["transaction_id"]
self.directory = self.recovery.root / "archives"
self.directory.mkdir(mode=0o700)
self.archive = RollbackArchive(
planner=self.planner,
directory=self.directory,
health_probe=self.fixture.health.verify,
)
self.marker = (
self.recovery.releases.release_path("2")
/ "BAD_RELEASE"
)
def execute(self):
plan = self.archive.plan()
return self.archive.execute(
confirmation=plan["confirmation"],
fingerprint=plan["fingerprint"],
)
def rewrite(self, path, **changes):
record = json.loads(path.read_text())
record.update(changes)
record.pop("checksum", None)
record["checksum"] = canonical_hash(record)
path.write_text(json.dumps(record))
def test_valid_plan(self):
self.assertEqual(
self.archive.plan()["status"],
"ARCHIVE_READY",
)
def test_plan_is_read_only(self):
self.archive.plan()
self.assertFalse(self.marker.exists())
self.assertEqual(
self.journal.load(),
self.transaction,
)
def test_successful_archive(self):
result = self.execute()
self.assertEqual(result["status"], "ARCHIVED")
self.assertIsNone(self.journal.load())
def test_failed_candidate_marked(self):
self.execute()
self.assertTrue(self.marker.is_file())
def test_original_transaction_preserved(self):
result = self.execute()
self.assertEqual(
result["transaction"],
self.transaction,
)
def test_original_rollback_evidence_preserved(self):
intent = self.fixture.executor.intent_path(
self.identifier
)
result = self.fixture.executor.result_path(
self.identifier
)
before = (intent.read_bytes(), result.read_bytes())
self.execute()
self.assertEqual(
(intent.read_bytes(), result.read_bytes()),
before,
)
def test_missing_result_rejected(self):
self.fixture.executor.result_path(
self.identifier
).unlink()
with self.assertRaises(ArchiveError):
self.archive.plan()
def test_missing_intent_rejected(self):
self.fixture.executor.intent_path(
self.identifier
).unlink()
with self.assertRaises(ArchiveError):
self.archive.plan()
def test_wrong_active_release_rejected(self):
self.recovery.releases.activate("2")
with self.assertRaises(ArchiveError):
self.archive.plan()
def test_changed_provenance_rejected(self):
self.recovery.old["fingerprint"] = "0" * 64
with self.assertRaises(ArchiveError):
self.archive.plan()
def test_changed_backup_rejected(self):
self.recovery.backup_verify.return_value[
"sha256"
] = "0" * 64
with self.assertRaises(ArchiveError):
self.archive.plan()
def test_runtime_verification_required(self):
self.recovery.runtime_check.return_value = False
with self.assertRaises(ArchiveError):
self.archive.plan()
def test_health_verification_required(self):
self.fixture.health.verify.side_effect = None
self.fixture.health.verify.return_value = {
"healthy": False,
"release": "1",
}
with self.assertRaises(ArchiveError):
self.archive.plan()
def test_wrong_confirmation_rejected(self):
plan = self.archive.plan()
with self.assertRaises(ArchiveError):
self.archive.execute(
confirmation="INVALID",
fingerprint=plan["fingerprint"],
)
self.assertFalse(self.marker.exists())
def test_wrong_fingerprint_rejected(self):
plan = self.archive.plan()
with self.assertRaises(ArchiveError):
self.archive.execute(
confirmation=plan["confirmation"],
fingerprint="0" * 64,
)
def test_modified_rollback_result_rejected(self):
self.rewrite(
self.fixture.executor.result_path(
self.identifier
),
active_release="99",
)
with self.assertRaises(ArchiveError):
self.archive.plan()
def test_publication_failure_preserves_journal(self):
plan = self.archive.plan()
with patch(
"core.approval_store.os.link",
side_effect=OSError("publication failed"),
):
with self.assertRaises(ArchiveError):
self.archive.execute(
confirmation=plan["confirmation"],
fingerprint=plan["fingerprint"],
)
self.assertEqual(
self.journal.load(),
self.transaction,
)
self.assertFalse(self.marker.exists())
def test_concurrent_operation_rejected(self):
with DeploymentLock(self.planner.lock_path):
with self.assertRaises(LockError):
self.archive.plan()
def test_duplicate_archival_rejected(self):
self.execute()
with self.assertRaises(ArchiveError):
self.archive.plan()
def test_no_database_restoration(self):
self.assertFalse(
self.execute()["database_restored"]
)
def test_both_releases_preserved(self):
self.execute()
for release in ("1", "2"):
self.assertTrue(
self.recovery.releases.release_path(
release
).is_dir()
)
def test_failed_release_cannot_be_validated(self):
self.execute()
with self.assertRaises(Exception):
self.recovery.releases.validate("2")
def test_archive_readback(self):
result = self.execute()
self.assertEqual(
self.archive.load(self.identifier),
result,
)
if __name__ == "__main__":
unittest.main()
+410
View File
@@ -0,0 +1,410 @@
import copy
import json
import unittest
from pathlib import Path
from unittest.mock import Mock
from core.services import (
ServiceError,
ServiceLifecycle,
)
class ServiceTests(unittest.TestCase):
def setUp(self):
self.config = json.loads(
Path("config/site.example.json").read_text()
)
self.runner = Mock(return_value=0)
self.manager = ServiceLifecycle(
self.config,
self.runner,
)
self.prefix = [
"docker",
"compose",
"--project-name",
self.config["docker"]["project"],
"--project-directory",
self.config["site"]["root"],
"--file",
self.config["site"]["root"] + "/compose.yaml",
]
def commands(self):
return [
list(call.args[0])
for call in self.runner.call_args_list
]
def test_no_commands_on_initialisation(self):
self.runner.assert_not_called()
def test_quiesce_workers(self):
self.manager.quiesce()
self.assertEqual(
self.commands(),
[
self.prefix + [
"stop", "--timeout", "90",
"queue", "scheduler",
],
],
)
def test_restart_php(self):
self.manager.restart_php()
self.assertEqual(
self.commands(),
[
self.prefix + [
"restart", "--timeout", "90", "php",
],
],
)
def test_validate_nginx(self):
self.manager.validate_nginx()
self.assertEqual(
self.commands(),
[
self.prefix + [
"exec", "-T", "--interactive=false",
"web", "nginx", "-t",
],
],
)
def test_reload_nginx(self):
self.manager.reload_nginx()
self.assertEqual(
self.commands(),
[
self.prefix + [
"exec", "-T", "--interactive=false",
"web", "nginx", "-t",
],
self.prefix + [
"exec", "-T", "--interactive=false",
"web", "nginx", "-s", "reload",
],
],
)
def test_resume_workers(self):
self.manager.resume()
self.assertEqual(
self.commands(),
[
self.prefix + [
"up", "-d", "--no-deps",
"queue", "scheduler",
],
],
)
def test_refresh_application(self):
self.manager.refresh()
self.assertEqual(
self.commands(),
[
self.prefix + [
"restart", "--timeout", "90", "php",
],
self.prefix + [
"exec", "-T", "--interactive=false",
"web", "nginx", "-t",
],
self.prefix + [
"exec", "-T", "--interactive=false",
"web", "nginx", "-s", "reload",
],
],
)
def test_custom_php_service(self):
self.config["docker"]["php_service"] = "application"
manager = ServiceLifecycle(
self.config,
self.runner,
)
manager.restart_php()
self.assertEqual(
self.commands()[0][-1],
"application",
)
def test_custom_web_service(self):
self.config["docker"]["web_service"] = "frontend"
manager = ServiceLifecycle(
self.config,
self.runner,
)
manager.validate_nginx()
self.assertEqual(
self.commands()[0][-3:],
["frontend", "nginx", "-t"],
)
def test_custom_worker_services(self):
self.config["docker"]["queue_service"] = "jobs"
self.config["docker"]["scheduler_service"] = "cron"
manager = ServiceLifecycle(
self.config,
self.runner,
)
manager.quiesce()
self.assertEqual(
self.commands()[0][-2:],
["jobs", "cron"],
)
def test_stop_failure_rejected(self):
self.runner.return_value = 1
with self.assertRaises(ServiceError):
self.manager.quiesce()
def test_php_failure_rejected(self):
self.runner.return_value = 1
with self.assertRaises(ServiceError):
self.manager.restart_php()
def test_nginx_validation_failure_rejected(self):
self.runner.return_value = 1
with self.assertRaises(ServiceError):
self.manager.validate_nginx()
def test_nginx_reload_failure_rejected(self):
self.runner.side_effect = [0, 1]
with self.assertRaises(ServiceError):
self.manager.reload_nginx()
def test_worker_resume_failure_rejected(self):
self.runner.return_value = 1
with self.assertRaises(ServiceError):
self.manager.resume()
def test_php_failure_stops_refresh(self):
self.runner.return_value = 1
with self.assertRaises(ServiceError):
self.manager.refresh()
self.assertEqual(self.runner.call_count, 1)
def test_nginx_validation_prevents_reload(self):
self.runner.return_value = 1
with self.assertRaises(ServiceError):
self.manager.reload_nginx()
self.assertEqual(self.runner.call_count, 1)
def test_refresh_does_not_restart_workers(self):
self.manager.refresh()
self.assertFalse(
any(
"queue" in cmd or "scheduler" in cmd
for cmd in self.commands()
)
)
def test_configuration_copied(self):
original = copy.deepcopy(self.config)
self.manager.refresh()
self.assertEqual(self.config, original)
def test_later_configuration_mutation_ignored(self):
self.config["docker"]["php_service"] = "changed"
self.manager.restart_php()
self.assertEqual(
self.commands()[0][-1],
"php",
)
def test_invalid_runner_rejected(self):
with self.assertRaises(ServiceError):
ServiceLifecycle(self.config, None)
def test_runner_exception_rejected(self):
self.runner.side_effect = OSError("failure")
with self.assertRaises(ServiceError):
self.manager.quiesce()
def test_boolean_runner_result_rejected(self):
self.runner.return_value = False
with self.assertRaises(ServiceError):
self.manager.quiesce()
def test_missing_runner_result_rejected(self):
self.runner.return_value = None
with self.assertRaises(ServiceError):
self.manager.quiesce()
def test_command_timeout_passed(self):
self.manager.quiesce()
self.assertEqual(
self.runner.call_args.kwargs["timeout"],
120,
)
def test_nginx_timeout_passed(self):
self.manager.validate_nginx()
self.assertEqual(
self.runner.call_args.kwargs["timeout"],
30,
)
def test_invalid_stop_timeout_rejected(self):
for value in (0, -1, True, 301, "90"):
with self.subTest(value=value):
with self.assertRaises(ServiceError):
ServiceLifecycle(
self.config,
self.runner,
stop_timeout=value,
)
def test_custom_stop_timeout(self):
manager = ServiceLifecycle(
self.config,
self.runner,
stop_timeout=60,
)
manager.quiesce()
self.assertEqual(
self.commands()[0][-4:],
["--timeout", "60", "queue", "scheduler"],
)
self.assertEqual(
self.runner.call_args.kwargs["timeout"],
90,
)
def test_no_destructive_compose_commands(self):
self.manager.quiesce()
self.manager.refresh()
self.manager.resume()
forbidden = {
"down", "rm", "prune", "--volumes",
"--remove-orphans", "--force-recreate",
}
for command in self.commands():
self.assertFalse(
set(command) & forbidden
)
def test_invalid_configuration_rejected(self):
self.config["docker"]["php_service"] = "../bad"
with self.assertRaises(ServiceError):
ServiceLifecycle(
self.config,
self.runner,
)
def test_root_path_binding(self):
self.manager.refresh()
for command in self.commands():
self.assertEqual(
command[:len(self.prefix)],
self.prefix,
)
def test_sensitive_runner_exception_not_exposed(self):
self.runner.side_effect = RuntimeError(
"private-secret"
)
with self.assertRaises(ServiceError) as result:
self.manager.quiesce()
self.assertNotIn(
"private-secret",
str(result.exception),
)
if __name__ == "__main__":
unittest.main()
+255
View File
@@ -0,0 +1,255 @@
import copy
import unittest
from pathlib import Path
from core.configuration import load_config
from core.site_policy import (
SitePolicyError,
validate_site,
validate_registry,
)
ROOT = Path(__file__).resolve().parents[2]
class SitePolicyTests(unittest.TestCase):
def setUp(self):
self.config = load_config(
ROOT / "config/site.example.json"
)
self.other = copy.deepcopy(self.config)
self.other["site"].update({
"identifier": "other-absdev-net",
"domain": "other.absdev.net",
"root": "/opt/laravel-sites/other-absdev-net",
"origin_port": 8198,
})
self.other["docker"]["project"] = (
"site-other-absdev-net"
)
self.other["database"]["name"] = "other_db"
self.other["database"]["username"] = "other_app"
def test_valid_site(self):
result = validate_site(self.config)
self.assertEqual(result["status"], "VALID")
def test_root_must_match_identifier(self):
self.config["site"]["root"] = (
"/opt/laravel-sites/different"
)
with self.assertRaises(SitePolicyError):
validate_site(self.config)
def test_untrusted_root_rejected(self):
self.config["site"]["root"] = "/etc"
with self.assertRaises(SitePolicyError):
validate_site(self.config)
def test_nested_root_rejected(self):
self.config["site"]["root"] = (
"/opt/laravel-sites/nested/example-absdev-net"
)
with self.assertRaises(SitePolicyError):
validate_site(self.config)
def test_double_slash_rejected(self):
self.config["site"]["root"] = (
"//opt/laravel-sites/example-absdev-net"
)
with self.assertRaises(SitePolicyError):
validate_site(self.config)
def test_project_must_match_site(self):
self.config["docker"]["project"] = "other-project"
with self.assertRaises(SitePolicyError):
validate_site(self.config)
def test_root_database_user_rejected(self):
self.config["database"]["username"] = "root"
with self.assertRaises(SitePolicyError):
validate_site(self.config)
def test_postgres_admin_rejected(self):
self.config["database"]["username"] = "postgres"
with self.assertRaises(SitePolicyError):
validate_site(self.config)
def test_mysql_system_database_rejected(self):
self.config["database"]["name"] = "mysql"
with self.assertRaises(SitePolicyError):
validate_site(self.config)
def test_postgres_system_database_rejected(self):
self.config["database"]["name"] = "template1"
with self.assertRaises(SitePolicyError):
validate_site(self.config)
def test_distinct_services_required(self):
self.config["docker"]["queue_service"] = (
self.config["docker"]["php_service"]
)
with self.assertRaises(SitePolicyError):
validate_site(self.config)
def test_distinct_networks_required(self):
self.config["docker"]["proxy_network"] = (
self.config["docker"]["backend_network"]
)
with self.assertRaises(SitePolicyError):
validate_site(self.config)
def test_reserved_origin_port_rejected(self):
self.config["site"]["origin_port"] = 443
with self.assertRaises(SitePolicyError):
validate_site(self.config)
def test_valid_registry(self):
result = validate_registry([
self.config, self.other,
])
self.assertEqual(result["site_count"], 2)
self.assertEqual(result["status"], "VALID")
def test_duplicate_site_rejected(self):
with self.assertRaises(SitePolicyError):
validate_registry([
self.config, self.config,
])
def test_duplicate_domain_rejected(self):
self.other["site"]["domain"] = (
self.config["site"]["domain"]
)
with self.assertRaises(SitePolicyError):
validate_registry([
self.config, self.other,
])
def test_duplicate_port_rejected(self):
self.other["site"]["origin_port"] = (
self.config["site"]["origin_port"]
)
with self.assertRaises(SitePolicyError):
validate_registry([
self.config, self.other,
])
def test_duplicate_database_rejected(self):
self.other["database"]["name"] = (
self.config["database"]["name"]
)
with self.assertRaises(SitePolicyError):
validate_registry([
self.config, self.other,
])
def test_duplicate_database_user_rejected(self):
self.other["database"]["username"] = (
self.config["database"]["username"]
)
with self.assertRaises(SitePolicyError):
validate_registry([
self.config, self.other,
])
def test_case_insensitive_database_conflict(self):
self.other["database"]["name"] = (
self.config["database"]["name"].upper()
)
with self.assertRaises(SitePolicyError):
validate_registry([
self.config, self.other,
])
def test_shared_database_container_permitted(self):
self.assertEqual(
self.config["database"]["container"],
self.other["database"]["container"],
)
validate_registry([
self.config, self.other,
])
def test_registry_order_independent(self):
self.assertEqual(
validate_registry([
self.config, self.other,
]),
validate_registry([
self.other, self.config,
]),
)
def test_empty_registry_rejected(self):
with self.assertRaises(SitePolicyError):
validate_registry([])
def test_invalid_registry_type_rejected(self):
with self.assertRaises(SitePolicyError):
validate_registry("invalid")
def test_input_not_mutated(self):
before = copy.deepcopy(self.config)
validate_site(self.config)
self.assertEqual(self.config, before)
def test_execution_remains_disabled(self):
result = validate_site(self.config)
self.assertFalse(result["execution_permitted"])
self.assertFalse(result["runtime_verified"])
def test_registry_not_runtime_verification(self):
result = validate_registry([self.config])
self.assertFalse(result["runtime_verified"])
self.assertFalse(result["execution_permitted"])
def test_fingerprint_deterministic(self):
self.assertEqual(
validate_site(self.config),
validate_site(self.config),
)
def test_invalid_configuration_wrapped(self):
del self.config["database"]
with self.assertRaises(SitePolicyError):
validate_site(self.config)
def test_reserved_username_case_insensitive(self):
self.config["database"]["username"] = "ROOT"
with self.assertRaises(SitePolicyError):
validate_site(self.config)
if __name__ == "__main__":
unittest.main()
+468
View File
@@ -0,0 +1,468 @@
import hashlib
import json
import os
import stat
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from core.transactions import (
TransactionError,
TransactionJournal,
)
class TransactionTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.journal = TransactionJournal(self.root)
def create(self):
return self.journal.create(
site="example-absdev-net",
previous="1",
candidate="2",
revision="a" * 40,
provenance="b" * 64,
)
def advance(self, phase):
current = self.journal.load()
return self.journal.transition(
current["transaction_id"],
current["phase"],
phase,
)
def complete(self):
self.create()
for phase in (
"BACKED_UP",
"QUIESCED",
"ACTIVATING",
"ACTIVATED",
"VERIFIED",
):
self.advance(phase)
return self.journal.load()
def test_empty_journal(self):
self.assertIsNone(self.journal.load())
def test_create_transaction(self):
self.assertEqual(
self.create()["phase"], "PREPARED"
)
def test_transaction_identifier(self):
self.assertRegex(
self.create()["transaction_id"],
r"^[a-f0-9]{32}$",
)
def test_persistent_transaction(self):
original = self.create()
self.assertEqual(
TransactionJournal(self.root).load(),
original,
)
def test_duplicate_transaction_rejected(self):
self.create()
with self.assertRaises(TransactionError):
self.create()
def test_file_permissions(self):
self.create()
self.assertEqual(
stat.S_IMODE(
self.journal.path.stat().st_mode
),
0o600,
)
def test_initial_history(self):
result = self.create()
self.assertEqual(
len(result["history"]), 1
)
self.assertEqual(
result["history"][0]["phase"],
"PREPARED",
)
def test_valid_transition(self):
self.create()
self.assertEqual(
self.advance("BACKED_UP")["phase"],
"BACKED_UP",
)
def test_invalid_transition_rejected(self):
self.create()
with self.assertRaises(TransactionError):
self.advance("ACTIVATED")
def test_unknown_phase_rejected(self):
self.create()
with self.assertRaises(TransactionError):
self.advance("UNKNOWN")
def test_duplicate_phase_rejected(self):
self.create()
with self.assertRaises(TransactionError):
self.advance("PREPARED")
def test_wrong_transaction_rejected(self):
self.create()
with self.assertRaises(TransactionError):
self.journal.transition(
"0" * 32,
"PREPARED",
"BACKED_UP",
)
def test_stale_phase_rejected(self):
transaction = self.create()
self.advance("BACKED_UP")
with self.assertRaises(TransactionError):
self.journal.transition(
transaction["transaction_id"],
"PREPARED",
"BACKED_UP",
)
def test_complete_transaction(self):
self.assertEqual(
self.complete()["phase"],
"VERIFIED",
)
def test_history_preserved(self):
result = self.complete()
self.assertEqual(
[item["phase"] for item in result["history"]],
[
"PREPARED",
"BACKED_UP",
"QUIESCED",
"ACTIVATING",
"ACTIVATED",
"VERIFIED",
],
)
def test_verified_is_terminal(self):
self.complete()
with self.assertRaises(TransactionError):
self.advance("FAILED")
def test_failure_containment(self):
self.create()
result = self.advance("FAILED")
self.assertEqual(result["phase"], "FAILED")
def test_failed_is_terminal(self):
self.create()
self.advance("FAILED")
with self.assertRaises(TransactionError):
self.advance("BACKED_UP")
def test_corrupted_json_rejected(self):
self.create()
self.journal.path.write_text("{invalid")
with self.assertRaises(TransactionError):
self.journal.load()
def test_modified_evidence_rejected(self):
self.create()
data = json.loads(
self.journal.path.read_text()
)
data["candidate"] = "99"
self.journal.path.write_text(
json.dumps(data)
)
with self.assertRaises(TransactionError):
self.journal.load()
def test_duplicate_json_keys_rejected(self):
self.create()
self.journal.path.write_text(
'{"phase":"FAILED","phase":"VERIFIED"}'
)
with self.assertRaises(TransactionError):
self.journal.load()
def test_invalid_history_rejected(self):
data = self.create()
data["history"][0]["phase"] = "VERIFIED"
del data["checksum"]
data["checksum"] = hashlib.sha256(
json.dumps(
data,
sort_keys=True,
separators=(",", ":"),
allow_nan=False,
).encode()
).hexdigest()
self.journal.path.write_text(
json.dumps(data)
)
with self.assertRaises(TransactionError):
self.journal.load()
def test_symlink_rejected(self):
target = self.root / "external"
target.write_text("{}")
self.journal.path.symlink_to(target)
with self.assertRaises(TransactionError):
self.journal.load()
def test_hardlink_rejected(self):
self.create()
os.link(
self.journal.path,
self.root / "duplicate",
)
with self.assertRaises(TransactionError):
self.journal.load()
def test_insecure_permissions_rejected(self):
self.create()
self.journal.path.chmod(0o644)
with self.assertRaises(TransactionError):
self.journal.load()
def test_invalid_site_rejected(self):
with self.assertRaises(TransactionError):
self.journal.create(
"../outside",
"1",
"2",
"a" * 40,
"b" * 64,
)
def test_invalid_revision_rejected(self):
with self.assertRaises(TransactionError):
self.journal.create(
"example",
"1",
"2",
"invalid",
"b" * 64,
)
def test_invalid_candidate_rejected(self):
with self.assertRaises(TransactionError):
self.journal.create(
"example",
"1",
"../outside",
"a" * 40,
"b" * 64,
)
def test_same_release_rejected(self):
with self.assertRaises(TransactionError):
self.journal.create(
"example",
"1",
"1",
"a" * 40,
"b" * 64,
)
def test_atomic_write_failure(self):
original = self.create()
with patch(
"core.transactions.os.replace",
side_effect=OSError("Simulated failure"),
):
with self.assertRaises(TransactionError):
self.advance("BACKED_UP")
self.assertEqual(
self.journal.load(), original
)
def test_no_temporary_files_remaining(self):
self.complete()
self.assertFalse(
list(self.root.glob(".transaction-*"))
)
def test_insecure_directory_rejected(self):
self.root.chmod(0o777)
with self.assertRaises(TransactionError):
TransactionJournal(self.root)
def test_concurrent_writer_rejected(self):
from core.locking import DeploymentLock, LockError
with DeploymentLock(
self.root / ".journal.lock"
):
with self.assertRaises(LockError):
self.create()
def test_invalid_provenance_rejected(self):
with self.assertRaises(TransactionError):
self.journal.create(
"example",
"1",
"2",
"a" * 40,
"invalid",
)
def test_failed_transition_preserves_evidence(self):
original = self.create()
with self.assertRaises(TransactionError):
self.advance("VERIFIED")
self.assertEqual(
self.journal.load(), original
)
def test_previous_provenance_persisted(self):
result = self.journal.create(
"example",
"1",
"2",
"a" * 40,
"b" * 64,
previous_revision="c" * 40,
previous_provenance="d" * 64,
)
self.assertEqual(
result["previous_revision"],
"c" * 40,
)
self.assertEqual(
self.journal.load()["previous_provenance"],
"d" * 64,
)
def test_partial_previous_evidence_rejected(self):
with self.assertRaises(TransactionError):
self.journal.create(
"example",
"1",
"2",
"a" * 40,
"b" * 64,
previous_revision="c" * 40,
)
def test_invalid_previous_revision_rejected(self):
with self.assertRaises(TransactionError):
self.journal.create(
"example",
"1",
"2",
"a" * 40,
"b" * 64,
previous_revision="invalid",
previous_provenance="d" * 64,
)
def test_invalid_previous_provenance_rejected(self):
with self.assertRaises(TransactionError):
self.journal.create(
"example",
"1",
"2",
"a" * 40,
"b" * 64,
previous_revision="c" * 40,
previous_provenance="invalid",
)
def test_previous_evidence_survives_transition(self):
transaction = self.journal.create(
"example",
"1",
"2",
"a" * 40,
"b" * 64,
previous_revision="c" * 40,
previous_provenance="d" * 64,
)
result = self.journal.transition(
transaction["transaction_id"],
"PREPARED",
"BACKED_UP",
)
self.assertEqual(
result["previous_provenance"],
"d" * 64,
)
if __name__ == "__main__":
unittest.main()