From d6e2317016627e579e4ea6eda8f955a75d581095 Mon Sep 17 00:00:00 2001 From: Mark Gregory Date: Thu, 26 Nov 2026 11:35:28 +0000 Subject: [PATCH] Initial ABSDEV deployment framework development preview --- .gitea/workflows/framework-ci.yaml | 29 + .gitignore | 49 ++ CHANGELOG.md | 35 ++ README.md | 75 +++ VERSION | 1 + adapters/__init__.py | 0 adapters/mysql/__init__.py | 0 adapters/mysql/adapter.py | 92 +++ adapters/postgresql/__init__.py | 0 adapters/postgresql/adapter.py | 86 +++ bin/absdev-deploy | 22 + bin/absdev-deploy-validate.py | 75 +++ config/site.example.json | 52 ++ core/__init__.py | 0 core/approval.py | 304 ++++++++++ core/approval_store.py | 419 ++++++++++++++ core/archive.py | 465 ++++++++++++++++ core/backup.py | 450 +++++++++++++++ core/backup_evidence.py | 424 ++++++++++++++ core/compatibility.py | 221 ++++++++ core/configuration.py | 442 +++++++++++++++ core/database.py | 122 ++++ core/deployment.py | 363 ++++++++++++ core/execution.py | 161 ++++++ core/health.py | 246 +++++++++ core/inspection_cli.py | 323 +++++++++++ core/locking.py | 202 +++++++ core/migration.py | 350 ++++++++++++ core/migration_archive.py | 474 ++++++++++++++++ core/migration_recovery.py | 521 +++++++++++++++++ core/operation_guard.py | 100 ++++ core/preflight.py | 68 +++ core/provenance.py | 284 ++++++++++ core/recovery.py | 242 ++++++++ core/rehearsal.py | 304 ++++++++++ core/releases.py | 231 ++++++++ core/retention.py | 191 +++++++ core/rollback.py | 377 +++++++++++++ core/rollback_archive.py | 457 +++++++++++++++ core/services.py | 182 ++++++ core/site_policy.py | 186 +++++++ core/transactions.py | 491 ++++++++++++++++ docs/ARCHITECTURE.md | 69 +++ docs/PRODUCTION-READINESS.md | 42 ++ scripts/build-release.py | 226 ++++++++ scripts/ci-check.sh | 146 +++++ tests/integration/test_mysql.py | 768 ++++++++++++++++++++++++++ tests/unit/test_approval.py | 343 ++++++++++++ tests/unit/test_approval_store.py | 466 ++++++++++++++++ tests/unit/test_archive.py | 313 +++++++++++ tests/unit/test_backup.py | 399 +++++++++++++ tests/unit/test_backup_evidence.py | 328 +++++++++++ tests/unit/test_ci_policy.py | 118 ++++ tests/unit/test_compatibility.py | 392 +++++++++++++ tests/unit/test_configuration.py | 282 ++++++++++ tests/unit/test_database.py | 363 ++++++++++++ tests/unit/test_deployment.py | 660 ++++++++++++++++++++++ tests/unit/test_execution.py | 300 ++++++++++ tests/unit/test_health.py | 416 ++++++++++++++ tests/unit/test_inspection_cli.py | 264 +++++++++ tests/unit/test_locking.py | 281 ++++++++++ tests/unit/test_migration.py | 360 ++++++++++++ tests/unit/test_migration_archive.py | 345 ++++++++++++ tests/unit/test_migration_recovery.py | 427 ++++++++++++++ tests/unit/test_operation_guard.py | 179 ++++++ tests/unit/test_preflight.py | 310 +++++++++++ tests/unit/test_provenance.py | 299 ++++++++++ tests/unit/test_recovery.py | 463 ++++++++++++++++ tests/unit/test_rehearsal.py | 390 +++++++++++++ tests/unit/test_releases.py | 212 +++++++ tests/unit/test_retention.py | 273 +++++++++ tests/unit/test_rollback.py | 325 +++++++++++ tests/unit/test_rollback_archive.py | 252 +++++++++ tests/unit/test_services.py | 410 ++++++++++++++ tests/unit/test_site_policy.py | 255 +++++++++ tests/unit/test_transactions.py | 468 ++++++++++++++++ 76 files changed, 20260 insertions(+) create mode 100644 .gitea/workflows/framework-ci.yaml create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 README.md create mode 100644 VERSION create mode 100644 adapters/__init__.py create mode 100644 adapters/mysql/__init__.py create mode 100644 adapters/mysql/adapter.py create mode 100644 adapters/postgresql/__init__.py create mode 100644 adapters/postgresql/adapter.py create mode 100755 bin/absdev-deploy create mode 100755 bin/absdev-deploy-validate.py create mode 100644 config/site.example.json create mode 100644 core/__init__.py create mode 100644 core/approval.py create mode 100644 core/approval_store.py create mode 100644 core/archive.py create mode 100644 core/backup.py create mode 100644 core/backup_evidence.py create mode 100644 core/compatibility.py create mode 100644 core/configuration.py create mode 100644 core/database.py create mode 100644 core/deployment.py create mode 100644 core/execution.py create mode 100644 core/health.py create mode 100644 core/inspection_cli.py create mode 100644 core/locking.py create mode 100644 core/migration.py create mode 100644 core/migration_archive.py create mode 100644 core/migration_recovery.py create mode 100644 core/operation_guard.py create mode 100644 core/preflight.py create mode 100644 core/provenance.py create mode 100644 core/recovery.py create mode 100644 core/rehearsal.py create mode 100644 core/releases.py create mode 100644 core/retention.py create mode 100644 core/rollback.py create mode 100644 core/rollback_archive.py create mode 100644 core/services.py create mode 100644 core/site_policy.py create mode 100644 core/transactions.py create mode 100644 docs/ARCHITECTURE.md create mode 100644 docs/PRODUCTION-READINESS.md create mode 100755 scripts/build-release.py create mode 100755 scripts/ci-check.sh create mode 100644 tests/integration/test_mysql.py create mode 100644 tests/unit/test_approval.py create mode 100644 tests/unit/test_approval_store.py create mode 100644 tests/unit/test_archive.py create mode 100644 tests/unit/test_backup.py create mode 100644 tests/unit/test_backup_evidence.py create mode 100644 tests/unit/test_ci_policy.py create mode 100644 tests/unit/test_compatibility.py create mode 100644 tests/unit/test_configuration.py create mode 100644 tests/unit/test_database.py create mode 100644 tests/unit/test_deployment.py create mode 100644 tests/unit/test_execution.py create mode 100644 tests/unit/test_health.py create mode 100644 tests/unit/test_inspection_cli.py create mode 100644 tests/unit/test_locking.py create mode 100644 tests/unit/test_migration.py create mode 100644 tests/unit/test_migration_archive.py create mode 100644 tests/unit/test_migration_recovery.py create mode 100644 tests/unit/test_operation_guard.py create mode 100644 tests/unit/test_preflight.py create mode 100644 tests/unit/test_provenance.py create mode 100644 tests/unit/test_recovery.py create mode 100644 tests/unit/test_rehearsal.py create mode 100644 tests/unit/test_releases.py create mode 100644 tests/unit/test_retention.py create mode 100644 tests/unit/test_rollback.py create mode 100644 tests/unit/test_rollback_archive.py create mode 100644 tests/unit/test_services.py create mode 100644 tests/unit/test_site_policy.py create mode 100644 tests/unit/test_transactions.py diff --git a/.gitea/workflows/framework-ci.yaml b/.gitea/workflows/framework-ci.yaml new file mode 100644 index 0000000..525bb1b --- /dev/null +++ b/.gitea/workflows/framework-ci.yaml @@ -0,0 +1,29 @@ +name: ABSDEV Framework CI + +on: + push: + pull_request: + workflow_dispatch: + +jobs: + framework-validation: + runs-on: ubuntu-latest + + timeout-minutes: 10 + + env: + PYTHONDONTWRITEBYTECODE: "1" + PYTHONUNBUFFERED: "1" + ABSDEV_INTEGRATION_TESTS: "0" + + steps: + - name: Checkout framework + uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Verify Python availability + run: python3 --version + + - name: Run framework validation + run: bash scripts/ci-check.sh diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1ed0e27 --- /dev/null +++ b/.gitignore @@ -0,0 +1,49 @@ +# Secrets and runtime configuration +.env +.env.* +!.env.example +*.pem +*.key +*.crt +*.sql +*.sql.gz +*.credentials +credentials.json +secrets/ +site.local.json + +# Runtime state +backups/ +recovery/ +runtime/ +logs/ +*.log +*.lock +*.backup* +*.bak* + +# Unreviewed reference implementation +/reference/ +/REFERENCE.sha256 + +# Python +__pycache__/ +*.py[cod] +.pytest_cache/ +.coverage +htmlcov/ +.venv/ + +# PHP +vendor/ + +# Node +node_modules/ + +# macOS and IDE +.DS_Store +.idea/ +.vscode/ + +# Private reference audit +/docs/reference-audit.json diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..712f1a3 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,35 @@ +# Changelog + +## 0.1.0-dev.1 — 2026-11-26 + +Initial development preview. + +- Configuration and site isolation policies. +- MySQL and PostgreSQL database adapters. +- Backup creation and verification. +- Release management and deployment locking. +- Provenance and migration compatibility. +- Deployment transaction coordination. +- Controlled application rollback. +- Migration approval and rehearsal validation. +- Persistent single-use approvals. +- Migration and forward activation coordination. +- Transaction archival and failed-release quarantine. +- Read-only retention planning. +- Eight-command inspection CLI. +- Local CI and Gitea workflow. +- 853 passing unit tests. + +Production execution remains disabled. + +## Previous development history + +# Changelog + +## 0.1.0-dev + +- Established separate framework development workspace. +- Preserved the verified Testrig reference implementation. +- Recorded source checksums. +- Established directory structure and security exclusions. +- Portable implementation and regression tests pending. diff --git a/README.md b/README.md new file mode 100644 index 0000000..387eaea --- /dev/null +++ b/README.md @@ -0,0 +1,75 @@ +# ABSDEV Deployment Framework + +Portable deployment and operational safety framework +for Docker-hosted Laravel applications. + +## Version + +0.1.0-dev.1 — Development Preview + +Production execution is not authorised. + +## Requirements + +- Linux +- Python 3.14 +- Bash +- Git + +## Supported database adapters + +- MySQL +- PostgreSQL + +## CLI commands + + bin/absdev-deploy capabilities + + bin/absdev-deploy validate \ + --config config/site.example.json + + bin/absdev-deploy site-policy \ + --config config/site.example.json + + bin/absdev-deploy inventory \ + --app /path/to/site/app + + bin/absdev-deploy provision-plan \ + --config config/site.example.json + + bin/absdev-deploy registry-validate \ + --registry registry.json + + bin/absdev-deploy preflight \ + --config config/site.example.json \ + --registry registry.json + + bin/absdev-deploy retention-plan \ + --policy retention.json + +All available commands are inspection or planning operations. + +## Testing + + python3 -B -m unittest discover -s tests/unit + + bash scripts/ci-check.sh + +Development baseline: 853 passing unit tests. + +## Documentation + +- docs/ARCHITECTURE.md +- docs/PRODUCTION-READINESS.md +- CHANGELOG.md + +## Restrictions + +Do not invoke internal deployment components directly +against production infrastructure. + +Real database integration remains outstanding. +Remote Gitea CI execution remains unverified. + +Private reference files, runtime records and credentials +must not be included in distributable packages. diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..2cb21bd --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.1.0-dev.1 diff --git a/adapters/__init__.py b/adapters/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/adapters/mysql/__init__.py b/adapters/mysql/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/adapters/mysql/adapter.py b/adapters/mysql/adapter.py new file mode 100644 index 0000000..28b67f3 --- /dev/null +++ b/adapters/mysql/adapter.py @@ -0,0 +1,92 @@ +"""MySQL database command construction.""" + +from core.database import DatabaseAdapter + + +class MySQLAdapter(DatabaseAdapter): + + backup_extension = ".sql" + + client_configuration = ( + "--defaults-file=/run/secrets/absdev-client.cnf" + ) + + def connection_arguments(self): + + return [ + "--protocol=TCP", + f"--host={self.database['host']}", + f"--port={self.database['port']}", + f"--user={self.database['username']}", + ] + + def query_command(self, query): + + return ( + self.docker_exec() + + [ + "mysql", + self.client_configuration, + ] + + self.connection_arguments() + + [ + "--batch", + "--skip-column-names", + f"--database={self.database['name']}", + "--execute", + query, + ] + ) + + def ping_command(self): + + return self.query_command("SELECT 1") + + def version_command(self): + + return self.query_command("SELECT VERSION()") + + def identity_command(self): + + return self.query_command( + "SELECT DATABASE(), CURRENT_USER(), @@server_uuid" + ) + + def backup_command(self): + + return ( + self.docker_exec() + + [ + "mysqldump", + self.client_configuration, + ] + + self.connection_arguments() + + [ + "--single-transaction", + "--quick", + "--no-tablespaces", + "--skip-lock-tables", + "--set-gtid-purged=OFF", + "--hex-blob", + "--triggers", + "--routines", + "--events", + self.database["name"], + ] + ) + + def restore_command(self, target): + + target = self.validate_restore_target(target) + + return ( + self.docker_exec(interactive=True) + + [ + "mysql", + self.client_configuration, + ] + + self.connection_arguments() + + [ + f"--database={target}", + ] + ) diff --git a/adapters/postgresql/__init__.py b/adapters/postgresql/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/adapters/postgresql/adapter.py b/adapters/postgresql/adapter.py new file mode 100644 index 0000000..b03606f --- /dev/null +++ b/adapters/postgresql/adapter.py @@ -0,0 +1,86 @@ +"""PostgreSQL database command construction.""" + +from core.database import DatabaseAdapter + + +class PostgreSQLAdapter(DatabaseAdapter): + + backup_extension = ".dump" + + def client_command( + self, + executable, + interactive=False, + ): + + return ( + self.docker_exec(interactive=interactive) + + [ + "env", + "PGPASSFILE=/run/secrets/absdev-pgpass", + executable, + "--no-password", + f"--host={self.database['host']}", + f"--port={self.database['port']}", + f"--username={self.database['username']}", + ] + ) + + def query_command(self, query): + + return ( + self.client_command("psql") + + [ + "--no-psqlrc", + "--tuples-only", + "--no-align", + "--set=ON_ERROR_STOP=1", + f"--dbname={self.database['name']}", + "--command", + query, + ] + ) + + def ping_command(self): + + return self.query_command("SELECT 1") + + def version_command(self): + + return self.query_command("SHOW server_version") + + def identity_command(self): + + return self.query_command( + "SELECT current_database(), current_user" + ) + + def backup_command(self): + + return ( + self.client_command("pg_dump") + + [ + "--format=custom", + "--no-owner", + "--no-privileges", + f"--dbname={self.database['name']}", + ] + ) + + def restore_command(self, target): + + target = self.validate_restore_target(target) + + return ( + self.client_command( + "pg_restore", + interactive=True, + ) + + [ + "--exit-on-error", + "--no-owner", + "--no-privileges", + "--single-transaction", + f"--dbname={target}", + ] + ) diff --git a/bin/absdev-deploy b/bin/absdev-deploy new file mode 100755 index 0000000..c3a17df --- /dev/null +++ b/bin/absdev-deploy @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 + +import runpy +import sys + +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + +sys.path.insert(0, str(ROOT)) + +# Preserve the original validation behaviour. + +if len(sys.argv) > 1 and sys.argv[1] == "validate": + runpy.run_path( + str(ROOT / "bin/absdev-deploy-validate.py"), + run_name="__main__", + ) +else: + from core.inspection_cli import main + + sys.exit(main()) diff --git a/bin/absdev-deploy-validate.py b/bin/absdev-deploy-validate.py new file mode 100755 index 0000000..a53e4cd --- /dev/null +++ b/bin/absdev-deploy-validate.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 + +import argparse +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent + +sys.path.insert(0, str(ROOT)) + +from core.configuration import ( + ConfigurationError, + load_config, +) + + +def main(): + + parser = argparse.ArgumentParser( + description="ABSDEV Deployment Framework" + ) + + parser.add_argument( + "--version", + action="version", + version=(ROOT / "VERSION").read_text().strip(), + ) + + commands = parser.add_subparsers( + dest="command", + required=True, + ) + + validate = commands.add_parser( + "validate", + help="Validate site configuration without deployment", + ) + + validate.add_argument( + "--config", + required=True, + type=Path, + ) + + args = parser.parse_args() + + try: + + if args.command == "validate": + + config = load_config(args.config) + + print("PASS: Configuration valid") + print("Site:", config["site"]["identifier"]) + print("Domain:", config["site"]["domain"]) + print("Database:", config["database"]["driver"]) + print("Schema:", config["schema_version"]) + print("No deployment performed") + + return 0 + + except ConfigurationError as error: + + print( + f"ERROR: {error}", + file=sys.stderr, + ) + + return 1 + + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/config/site.example.json b/config/site.example.json new file mode 100644 index 0000000..c69282f --- /dev/null +++ b/config/site.example.json @@ -0,0 +1,52 @@ +{ + "schema_version": 1, + "site": { + "identifier": "example-absdev-net", + "domain": "example.absdev.net", + "root": "/opt/laravel-sites/example-absdev-net", + "origin_port": 8199 + }, + "repository": { + "url": "git@example.invalid: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 + } +} diff --git a/core/__init__.py b/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/approval.py b/core/approval.py new file mode 100644 index 0000000..35a087a --- /dev/null +++ b/core/approval.py @@ -0,0 +1,304 @@ +"""Strict migration approval validation. + +This module validates approval records only. +It does not authenticate operators or execute migrations. +""" + +import copy +import re +import uuid + +from datetime import datetime, timedelta, timezone + +from core.compatibility import canonical_hash + + +class ApprovalError(RuntimeError): + """Invalid, expired or mismatched migration approval.""" + + +CONTEXT_FIELDS = { + "site", + "release", + "revision", + "provenance", + "compatibility", + "database_identity", + "backup_sha256", + "rehearsal_fingerprint", + "pending_migrations", +} + +APPROVAL_FIELDS = { + "format_version", + "approval_id", + "approver", + "context", + "issued_at", + "expires_at", + "confirmation", + "checksum", +} + + +def require(condition, message): + + if not condition: + raise ApprovalError(message) + + +def matches(value, pattern): + + return ( + isinstance(value, str) + and re.fullmatch(pattern, value) is not None + ) + + +def timestamp(value): + + require( + isinstance(value, datetime) + and value.utcoffset() is not None, + "Timezone-aware timestamp required", + ) + + return value.astimezone(timezone.utc) + + +def parse_timestamp(value): + + require( + isinstance(value, str), + "Invalid approval timestamp", + ) + + try: + + parsed = datetime.fromisoformat(value) + + return timestamp(parsed) + + except (ValueError, OverflowError): + + raise ApprovalError( + "Invalid approval timestamp" + ) from None + + +def validate_context(context): + + require( + isinstance(context, dict) + and set(context) == CONTEXT_FIELDS, + "Invalid migration approval context", + ) + + require( + matches( + context["site"], + r"[a-z0-9][a-z0-9-]{0,62}", + ), + "Invalid site identifier", + ) + + require( + matches( + context["release"], + r"[1-9][0-9]{0,19}", + ), + "Invalid release identifier", + ) + + require( + matches( + context["revision"], + r"[a-f0-9]{40}", + ), + "Invalid Git revision", + ) + + for field in ( + "provenance", + "compatibility", + "database_identity", + "backup_sha256", + "rehearsal_fingerprint", + ): + + require( + matches( + context[field], + r"[a-f0-9]{64}", + ), + f"Invalid approval evidence: {field}", + ) + + pending = context["pending_migrations"] + + require( + isinstance(pending, list) + and 1 <= len(pending) <= 10000, + "Invalid pending migration inventory", + ) + + for name in pending: + + require( + matches( + name, + r"[A-Za-z0-9_][A-Za-z0-9_-]{0,254}", + ), + "Invalid pending migration name", + ) + + require( + len(set(pending)) == len(pending), + "Duplicate pending migrations", + ) + + +def validate_approver(approver): + + require( + matches( + approver, + r"[A-Za-z0-9][A-Za-z0-9_.@-]{0,127}", + ), + "Invalid approver identifier", + ) + + +def approval_checksum(approval): + + return canonical_hash({ + key: value + for key, value in approval.items() + if key != "checksum" + }) + + +def issue_approval( + context, + *, + approver, + now, + ttl_hours=24, +): + + validate_context(context) + validate_approver(approver) + + issued = timestamp(now) + + require( + type(ttl_hours) is int + and 1 <= ttl_hours <= 24, + "Approval lifetime must be between 1 and 24 hours", + ) + + approval_id = uuid.uuid4().hex + + approval = { + "format_version": 1, + "approval_id": approval_id, + "approver": approver, + "context": copy.deepcopy(context), + "issued_at": issued.isoformat(), + "expires_at": ( + issued + timedelta(hours=ttl_hours) + ).isoformat(), + "confirmation": ( + "MIGRATE-" + approval_id + ), + } + + approval["checksum"] = approval_checksum( + approval + ) + + return approval + + +def verify_approval( + approval, + context, + *, + confirmation, + now, +): + + validate_context(context) + + require( + isinstance(approval, dict) + and set(approval) == APPROVAL_FIELDS, + "Invalid approval record", + ) + + require( + type(approval["format_version"]) is int + and approval["format_version"] == 1, + "Unsupported approval format", + ) + + require( + matches( + approval["approval_id"], + r"[a-f0-9]{32}", + ), + "Invalid approval identifier", + ) + + validate_approver(approval["approver"]) + validate_context(approval["context"]) + + require( + matches( + approval["checksum"], + r"[a-f0-9]{64}", + ) + and approval_checksum(approval) + == approval["checksum"], + "Approval checksum mismatch", + ) + + require( + approval["context"] == context, + "Migration approval context changed", + ) + + expected = ( + "MIGRATE-" + approval["approval_id"] + ) + + require( + isinstance(confirmation, str) + and confirmation == expected + and approval["confirmation"] == expected, + "Migration confirmation mismatch", + ) + + issued = parse_timestamp( + approval["issued_at"] + ) + + expires = parse_timestamp( + approval["expires_at"] + ) + + current = timestamp(now) + + require( + timedelta(0) + < expires - issued + <= timedelta(hours=24), + "Invalid approval lifetime", + ) + + require( + issued <= current < expires, + "Approval expired or not yet valid", + ) + + return True diff --git a/core/approval_store.py b/core/approval_store.py new file mode 100644 index 0000000..9e218f3 --- /dev/null +++ b/core/approval_store.py @@ -0,0 +1,419 @@ +"""Persistent single-use migration approvals. + +Consumption records intent, not successful migration. +No database operations are implemented here. +""" + +import copy +import json +import os +import re +import stat +import uuid + +from pathlib import Path + +from core.approval import ( + verify_approval, + timestamp, + approval_checksum, + APPROVAL_FIELDS, +) + +from core.rehearsal import approval_context +from core.compatibility import canonical_hash +from core.locking import DeploymentLock + + +class ApprovalStoreError(RuntimeError): + """Unsafe, missing, invalid or consumed approval.""" + + +def require(condition, message): + + if not condition: + raise ApprovalStoreError(message) + + +def unique_keys(items): + + result = {} + + for key, value in items: + + require( + key not in result, + "Duplicate approval record key", + ) + + result[key] = value + + return result + + +class ApprovalStore: + + MAX_BYTES = 4 * 1024 * 1024 + + def __init__(self, directory): + + self.directory = Path(directory).absolute() + self.validate_directory() + + def validate_directory(self): + + root = self.directory + + require( + root.is_dir() + and not root.is_symlink() + and root.resolve() == root, + "Invalid approval directory", + ) + + details = root.stat() + + require( + details.st_uid == os.getuid() + and stat.S_IMODE(details.st_mode) == 0o700, + "Approval directory must be private", + ) + + def path(self, identifier, suffix): + + require( + isinstance(identifier, str) + and re.fullmatch( + r"[a-f0-9]{32}", + identifier, + ) is not None, + "Invalid approval identifier", + ) + + return self.directory / ( + identifier + suffix + ) + + def approval_path(self, identifier): + + return self.path( + identifier, + ".approval.json", + ) + + def consumed_path(self, identifier): + + return self.path( + identifier, + ".consumed.json", + ) + + def read(self, path): + + self.validate_directory() + + require( + path.parent == self.directory, + "Invalid approval file path", + ) + + fd = None + + try: + + fd = os.open( + path, + os.O_RDONLY + | os.O_NOFOLLOW + | os.O_NONBLOCK + | os.O_CLOEXEC, + ) + + details = os.fstat(fd) + + require( + stat.S_ISREG(details.st_mode) + and details.st_uid == os.getuid() + and details.st_nlink == 1 + and stat.S_IMODE(details.st_mode) == 0o600 + and details.st_size <= self.MAX_BYTES, + "Unsafe approval record file", + ) + + with os.fdopen(fd, "rb") as handle: + + fd = None + + raw = handle.read(self.MAX_BYTES + 1) + + require( + len(raw) <= self.MAX_BYTES, + "Approval record exceeds size limit", + ) + + return json.loads( + raw, + object_pairs_hook=unique_keys, + ) + + except ApprovalStoreError: + raise + + except (OSError, ValueError, TypeError): + + raise ApprovalStoreError( + "Unable to read approval record" + ) from None + + finally: + + if fd is not None: + os.close(fd) + + def publish(self, path, record): + + self.validate_directory() + + require( + path.parent == self.directory + and not os.path.lexists(path), + "Approval record already exists or path is unsafe", + ) + + temporary = self.directory / ( + ".approval-tmp-" + uuid.uuid4().hex + ) + + fd = None + created = False + + try: + + payload = ( + json.dumps( + record, + sort_keys=True, + indent=2, + allow_nan=False, + ) + "\n" + ).encode() + + require( + len(payload) <= self.MAX_BYTES, + "Approval record exceeds size limit", + ) + + fd = os.open( + temporary, + os.O_WRONLY + | os.O_CREAT + | os.O_EXCL + | os.O_NOFOLLOW + | os.O_CLOEXEC, + 0o600, + ) + + created = True + + with os.fdopen(fd, "wb") as handle: + + fd = None + + handle.write(payload) + handle.flush() + os.fsync(handle.fileno()) + + # Atomic publication without replacement. + + os.link( + temporary, + path, + follow_symlinks=False, + ) + + temporary.unlink() + created = False + + directory_fd = os.open( + self.directory, + os.O_RDONLY + | os.O_DIRECTORY + | os.O_NOFOLLOW, + ) + + try: + os.fsync(directory_fd) + finally: + os.close(directory_fd) + + require( + self.read(path) == record, + "Approval record readback failed", + ) + + return record + + except ApprovalStoreError: + raise + + except (OSError, ValueError, TypeError): + + raise ApprovalStoreError( + "Approval publication failed; inspect evidence" + ) from None + + finally: + + if fd is not None: + os.close(fd) + + if created: + temporary.unlink(missing_ok=True) + + def load(self, identifier): + + record = self.read( + self.approval_path(identifier) + ) + + try: + + require( + isinstance(record, dict) + and set(record) == APPROVAL_FIELDS, + "Invalid stored approval structure", + ) + + require( + record["approval_id"] == identifier + and record["checksum"] + == approval_checksum(record), + "Stored approval identity or checksum mismatch", + ) + + except ApprovalStoreError: + raise + + except (ValueError, TypeError, KeyError): + + raise ApprovalStoreError( + "Invalid stored approval" + ) from None + + return record + + def save( + self, + approval, + context, + *, + confirmation, + now, + ): + + try: + + record = copy.deepcopy(approval) + + verify_approval( + record, + context, + confirmation=confirmation, + now=now, + ) + + except Exception: + + raise ApprovalStoreError( + "Approval validation failed" + ) from None + + self.validate_directory() + + with DeploymentLock( + self.directory / ".approval.lock" + ): + + identifier = record["approval_id"] + + require( + not os.path.lexists( + self.consumed_path(identifier) + ), + "Approval has already been consumed", + ) + + return self.publish( + self.approval_path(identifier), + record, + ) + + def consume( + self, + identifier, + base_context, + rehearsal, + *, + confirmation, + now, + ): + + self.validate_directory() + + with DeploymentLock( + self.directory / ".approval.lock" + ): + + marker = self.consumed_path(identifier) + + # Even corrupt or incomplete consumption + # evidence prevents another execution. + + require( + not os.path.lexists(marker), + "Approval already consumed; review required", + ) + + approval = self.load(identifier) + + try: + + context = approval_context( + rehearsal, + base_context, + now=now, + ) + + verify_approval( + approval, + context, + confirmation=confirmation, + now=now, + ) + + except Exception: + + raise ApprovalStoreError( + "Approval or rehearsal validation failed" + ) from None + + record = { + "format_version": 1, + "status": "CONSUMED", + "approval_id": identifier, + "approval_checksum": approval["checksum"], + "site": context["site"], + "release": context["release"], + "revision": context["revision"], + "database_identity": context["database_identity"], + "backup_sha256": context["backup_sha256"], + "rehearsal_fingerprint": ( + context["rehearsal_fingerprint"] + ), + "consumed_at": timestamp(now).isoformat(), + "migration_executed": False, + } + + record["checksum"] = canonical_hash(record) + + return self.publish(marker, record) diff --git a/core/archive.py b/core/archive.py new file mode 100644 index 0000000..30a248b --- /dev/null +++ b/core/archive.py @@ -0,0 +1,465 @@ +"""Verified deployment transaction archival. + +Failed and migration transactions are not archived here. +External verification operations are injected. +""" + +import json +import os +import re +import stat +import uuid + +from datetime import datetime, timezone +from pathlib import Path + +from core.backup_evidence import FIELDS +from core.compatibility import ( + canonical_hash, + validate_provenance, +) +from core.locking import DeploymentLock + + +class ArchiveError(RuntimeError): + """Transaction archival is unsafe or incomplete.""" + + +def require(condition, message): + if not condition: + raise ArchiveError(message) + + +def unique_keys(items): + result = {} + + for key, value in items: + require( + key not in result, + "Duplicate archive record key", + ) + result[key] = value + + return result + + +def digest(record): + return canonical_hash({ + key: value + for key, value in record.items() + if key != "checksum" + }) + + +def sync_directory(path): + fd = os.open( + path, + os.O_RDONLY + | os.O_DIRECTORY + | os.O_NOFOLLOW + | os.O_CLOEXEC, + ) + + try: + os.fsync(fd) + finally: + os.close(fd) + + +class TransactionArchive: + + MAX_BYTES = 1024 * 1024 + + def __init__( + self, + *, + site, + directory, + lock_path, + journal, + releases, + provenance, + backup_evidence, + backup_verify, + health_probe, + ): + self.site = site + self.directory = Path(directory).absolute() + self.lock_path = Path(lock_path) + self.journal = journal + self.releases = releases + self.provenance = provenance + self.backup_evidence = backup_evidence + self.backup_verify = backup_verify + self.health_probe = health_probe + + self.validate_directory() + + def validate_directory(self): + root = self.directory + + require( + root.is_dir() + and not root.is_symlink() + and root.resolve() == root, + "Invalid archive directory", + ) + + details = root.stat() + + require( + details.st_uid == os.getuid() + and stat.S_IMODE(details.st_mode) == 0o700, + "Archive directory must be private", + ) + + require( + root != self.journal.directory, + "Archive and active journal must be separate", + ) + + def path(self, identifier): + require( + isinstance(identifier, str) + and re.fullmatch( + r"[a-f0-9]{32}", identifier + ) is not None, + "Invalid transaction identifier", + ) + + return self.directory / ( + identifier + ".archive.json" + ) + + def load(self, identifier): + self.validate_directory() + + fd = None + + try: + fd = os.open( + self.path(identifier), + os.O_RDONLY + | os.O_NOFOLLOW + | os.O_NONBLOCK + | os.O_CLOEXEC, + ) + + details = os.fstat(fd) + + require( + stat.S_ISREG(details.st_mode) + and details.st_uid == os.getuid() + and details.st_nlink == 1 + and stat.S_IMODE(details.st_mode) == 0o600 + and details.st_size <= self.MAX_BYTES, + "Unsafe archive file", + ) + + with os.fdopen(fd, "rb") as handle: + fd = None + raw = handle.read(self.MAX_BYTES + 1) + + require( + len(raw) <= self.MAX_BYTES, + "Archive exceeds size limit", + ) + + record = json.loads( + raw, + object_pairs_hook=unique_keys, + ) + + require( + isinstance(record, dict) + and set(record) == { + "format_version", + "status", + "site", + "transaction", + "backup_evidence", + "plan_fingerprint", + "database_restored", + "archived_at", + "checksum", + }, + "Invalid archive structure", + ) + + require( + type(record["format_version"]) is int + and record["format_version"] == 1 + and record["status"] == "ARCHIVED" + and record["site"] == self.site + and record["database_restored"] is False + and record["checksum"] == digest(record), + "Invalid archive checksum or state", + ) + + transaction = record["transaction"] + + self.journal.validate(transaction) + + require( + transaction["transaction_id"] == identifier + and transaction["site"] == self.site + and transaction["phase"] == "VERIFIED", + "Invalid archived transaction", + ) + + self.backup_evidence.validate( + record["backup_evidence"], + identifier, + ) + + return record + + except ArchiveError: + raise + + except Exception: + raise ArchiveError( + "Unable to validate archived transaction" + ) from None + + finally: + if fd is not None: + os.close(fd) + + def _plan(self): + self.validate_directory() + + transaction = self.journal.load() + + require( + transaction is not None + and transaction["phase"] == "VERIFIED", + "Only verified transactions may be archived", + ) + + require( + transaction["site"] == self.site, + "Transaction site mismatch", + ) + + identifier = transaction["transaction_id"] + + require( + not os.path.lexists(self.path(identifier)), + "Existing archive requires inspection", + ) + + candidate = transaction["candidate"] + + require( + self.releases.current() == candidate, + "Active release differs from transaction", + ) + + provenance = self.provenance.verify( + self.releases.validate(candidate) + ) + + validate_provenance(provenance) + + require( + provenance["revision"] == transaction["revision"] + and provenance["fingerprint"] == transaction["provenance"], + "Active release provenance changed", + ) + + evidence = self.backup_evidence.load(identifier) + + backup = evidence["backup"] + + manifest = self.backup_verify( + backup["backup_id"] + ) + + require( + isinstance(manifest, dict) + and FIELDS <= set(manifest) + and { + field: manifest[field] + for field in FIELDS + } == backup, + "Backup integrity verification failed", + ) + + health = self.health_probe(candidate) + + require( + isinstance(health, dict) + and health.get("healthy") is True + and health.get("release") == candidate, + "Application health verification failed", + ) + + require( + self.journal.load() == transaction + and self.releases.current() == candidate, + "Deployment state changed during planning", + ) + + result = { + "format_version": 1, + "status": "ARCHIVE_READY", + "site": self.site, + "transaction_id": identifier, + "transaction_checksum": transaction["checksum"], + "backup_evidence_checksum": evidence["checksum"], + "active_release": candidate, + "confirmation": "ARCHIVE-" + identifier, + } + + result["fingerprint"] = canonical_hash(result) + + return result + + def plan(self): + with DeploymentLock(self.lock_path): + + try: + return self._plan() + + except ArchiveError: + raise + + except Exception: + raise ArchiveError( + "Transaction archive preflight failed" + ) from None + + def publish(self, identifier, record): + path = self.path(identifier) + + temporary = self.directory / ( + ".archive-" + uuid.uuid4().hex + ) + + created = False + + try: + with temporary.open("x", encoding="utf-8") as handle: + created = True + + os.fchmod(handle.fileno(), 0o600) + + json.dump( + record, + handle, + sort_keys=True, + indent=2, + allow_nan=False, + ) + + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + + os.link( + temporary, + path, + follow_symlinks=False, + ) + + temporary.unlink() + created = False + + sync_directory(self.directory) + + require( + self.load(identifier) == record, + "Archive readback verification failed", + ) + + finally: + if created: + temporary.unlink(missing_ok=True) + + def execute(self, *, confirmation, fingerprint): + with DeploymentLock(self.lock_path): + + try: + return self._execute( + confirmation, + fingerprint, + ) + + except ArchiveError: + raise + + except Exception: + raise ArchiveError( + "Archival failed; inspect preserved evidence" + ) from None + + def _execute(self, confirmation, fingerprint): + plan = self._plan() + + require( + confirmation == plan["confirmation"] + and fingerprint == plan["fingerprint"], + "Archive confirmation or fingerprint mismatch", + ) + + with DeploymentLock(self.journal.lock_path): + + transaction = self.journal.load() + identifier = plan["transaction_id"] + + require( + transaction is not None + and transaction["transaction_id"] == identifier + and transaction["checksum"] + == plan["transaction_checksum"], + "Active transaction changed", + ) + + evidence = self.backup_evidence.load( + identifier + ) + + require( + evidence["checksum"] + == plan["backup_evidence_checksum"], + "Backup evidence changed", + ) + + record = { + "format_version": 1, + "status": "ARCHIVED", + "site": self.site, + "transaction": transaction, + "backup_evidence": evidence, + "plan_fingerprint": fingerprint, + "database_restored": False, + "archived_at": datetime.now( + timezone.utc + ).isoformat(), + } + + record["checksum"] = digest(record) + + # Publish and synchronise the archive before + # removing the active journal entry. + + self.publish(identifier, record) + + require( + self.journal.load() == transaction + and self.releases.current() + == plan["active_release"], + "State changed before journal retirement", + ) + + self.journal.path.unlink() + + sync_directory(self.journal.directory) + + require( + self.journal.load() is None, + "Active transaction was not retired", + ) + + return record diff --git a/core/backup.py b/core/backup.py new file mode 100644 index 0000000..eaf21b2 --- /dev/null +++ b/core/backup.py @@ -0,0 +1,450 @@ +"""Recovery-aware database backup storage. + +Execution is delegated to an explicitly supplied runner. +This module does not connect directly to a database. +""" + +import hashlib +import io +import json +import os +import re +import shutil +import stat +import tempfile +import uuid + +from datetime import datetime, timezone +from pathlib import Path + + +class BackupError(RuntimeError): + """Invalid or unsuccessful backup operation.""" + + +def require(condition, message): + + if not condition: + raise BackupError(message) + + +def sync_directory(path): + + fd = os.open( + path, + os.O_RDONLY + | os.O_DIRECTORY + | os.O_NOFOLLOW, + ) + + try: + os.fsync(fd) + finally: + os.close(fd) + + +def secure_directory(path): + + details = path.lstat() + + require( + stat.S_ISDIR(details.st_mode) + and details.st_uid == os.getuid() + and stat.S_IMODE(details.st_mode) == 0o700, + "Unsafe backup directory", + ) + + +def secure_file(path): + + details = path.lstat() + + require( + stat.S_ISREG(details.st_mode) + and details.st_uid == os.getuid() + and details.st_nlink == 1 + and stat.S_IMODE(details.st_mode) == 0o600, + "Unsafe backup file", + ) + + +def open_new(path): + + fd = os.open( + path, + os.O_WRONLY + | os.O_CREAT + | os.O_EXCL + | os.O_NOFOLLOW, + 0o600, + ) + + return os.fdopen(fd, "wb") + + +def checksum(path): + + secure_file(path) + + fd = os.open( + path, + os.O_RDONLY | os.O_NOFOLLOW, + ) + + with os.fdopen(fd, "rb") as handle: + + digest = hashlib.sha256() + size = 0 + + for block in iter( + lambda: handle.read(1024 * 1024), + b"", + ): + + digest.update(block) + size += len(block) + + return digest.hexdigest(), size + + +def flush_file(handle): + + handle.flush() + os.fsync(handle.fileno()) + + +class BackupEngine: + + def __init__(self, adapter, directory, runner): + + self.adapter = adapter + self.root = Path(directory).absolute() + self.runner = runner + + require( + callable(runner), + "Backup execution runner is required", + ) + + require( + adapter.database["driver"] + in ("mysql", "pgsql"), + "Unsupported backup adapter", + ) + + self.filename = ( + "database.sql" + if adapter.database["driver"] == "mysql" + else "database.dump" + ) + + def identity(self): + + output = io.BytesIO() + + self.runner( + self.adapter.identity_command(), + output, + ) + + raw = output.getvalue().decode("utf-8").strip() + + require( + raw and "\n" not in raw, + "Invalid database identity output", + ) + + driver = self.adapter.database["driver"] + + separator = "\t" if driver == "mysql" else "|" + + parts = raw.split(separator) + + require( + len(parts) == (3 if driver == "mysql" else 2), + "Unexpected database identity format", + ) + + name = parts[0] + account = parts[1] + + username = ( + account.rsplit("@", 1)[0] + if driver == "mysql" + else account + ) + + require( + name == self.adapter.database["name"], + "Database identity mismatch", + ) + + require( + username == self.adapter.database["username"], + "Database account mismatch", + ) + + if driver == "mysql": + + require( + bool(parts[2]), + "Missing database server identity", + ) + + return raw + + def create(self): + + temporary = None + published = None + + try: + + secure_directory(self.root) + + identity_before = self.identity() + + stamp = datetime.now(timezone.utc).strftime( + "%Y%m%dT%H%M%S" + ) + + backup_id = ( + f"backup-{stamp}-{uuid.uuid4().hex}" + ) + + destination = self.root / backup_id + + temporary = Path( + tempfile.mkdtemp( + prefix=".partial-", + dir=self.root, + ) + ) + + secure_directory(temporary) + + artifact = temporary / self.filename + + with open_new(artifact) as handle: + + self.runner( + self.adapter.backup_command(), + handle, + ) + + flush_file(handle) + + digest, size = checksum(artifact) + + require(size > 0, "Database backup is empty") + + identity_after = self.identity() + + require( + identity_before == identity_after, + "Database identity changed during backup", + ) + + manifest = { + "format_version": 1, + "backup_id": backup_id, + "created_at": datetime.now( + timezone.utc + ).isoformat(), + "driver": self.adapter.database["driver"], + "database": self.adapter.database["name"], + "username": self.adapter.database["username"], + "container": self.adapter.database["container"], + "identity": identity_before, + "filename": self.filename, + "sha256": digest, + "bytes": size, + } + + with open_new( + temporary / "manifest.json" + ) as handle: + + handle.write( + ( + json.dumps( + manifest, + indent=2, + sort_keys=True, + ) + + "\n" + ).encode() + ) + + flush_file(handle) + + sync_directory(temporary) + + require( + not destination.exists() + and not destination.is_symlink(), + "Backup destination already exists", + ) + + os.rename(temporary, destination) + + temporary = None + published = destination + + sync_directory(self.root) + + self.verify(destination) + + return destination + + except Exception as error: + + if temporary is not None: + + shutil.rmtree(temporary) + + sync_directory(self.root) + + if published is not None: + + # Withdraw an unsuccessful publication. + # Preserve evidence rather than deleting it. + + failed = self.root / ( + ".failed-" + uuid.uuid4().hex + ) + + os.rename(published, failed) + sync_directory(self.root) + + if isinstance(error, BackupError): + raise + + raise BackupError( + "Backup creation failed" + ) from error + + def verify(self, directory): + + try: + + secure_directory(self.root) + + directory = Path(directory).absolute() + + require( + directory.parent == self.root, + "Backup is outside the configured directory", + ) + + require( + re.fullmatch( + r"backup-\d{8}T\d{6}-[a-f0-9]{32}", + directory.name, + ) is not None, + "Invalid backup directory name", + ) + + secure_directory(directory) + + require( + {path.name for path in directory.iterdir()} + == {self.filename, "manifest.json"}, + "Unexpected backup directory contents", + ) + + manifest_path = directory / "manifest.json" + + secure_file(manifest_path) + + require( + manifest_path.stat().st_size <= 65536, + "Oversized backup manifest", + ) + + fd = os.open( + manifest_path, + os.O_RDONLY | os.O_NOFOLLOW, + ) + + with os.fdopen(fd, "r", encoding="utf-8") as handle: + + manifest = json.load(handle) + + fields = { + "format_version", + "backup_id", + "created_at", + "driver", + "database", + "username", + "container", + "identity", + "filename", + "sha256", + "bytes", + } + + require( + isinstance(manifest, dict) + and set(manifest) == fields, + "Invalid backup manifest", + ) + + expected = { + "format_version": 1, + "backup_id": directory.name, + "driver": self.adapter.database["driver"], + "database": self.adapter.database["name"], + "username": self.adapter.database["username"], + "container": self.adapter.database["container"], + "filename": self.filename, + } + + for key, value in expected.items(): + + require( + manifest[key] == value, + f"Backup manifest mismatch: {key}", + ) + + require( + isinstance(manifest["sha256"], str) + and re.fullmatch( + r"[a-f0-9]{64}", + manifest["sha256"], + ) is not None, + "Invalid backup checksum", + ) + + require( + type(manifest["bytes"]) is int + and manifest["bytes"] > 0, + "Invalid backup size", + ) + + digest, size = checksum( + directory / self.filename + ) + + require( + digest == manifest["sha256"], + "Backup checksum mismatch", + ) + + require( + size == manifest["bytes"], + "Backup size mismatch", + ) + + return manifest + + except BackupError: + + raise + + except Exception as error: + + raise BackupError( + "Backup verification failed" + ) from error diff --git a/core/backup_evidence.py b/core/backup_evidence.py new file mode 100644 index 0000000..a3735b1 --- /dev/null +++ b/core/backup_evidence.py @@ -0,0 +1,424 @@ +"""Persistent transaction-bound database backup evidence.""" + +import hashlib +import json +import os +import re +import stat +import uuid + +from pathlib import Path + +from core.locking import DeploymentLock + + +class EvidenceError(RuntimeError): + """Missing, invalid or unsafe backup evidence.""" + + +FIELDS = { + "backup_id", + "driver", + "database", + "username", + "container", + "identity", + "filename", + "sha256", + "bytes", +} + + +def require(condition, message): + + if not condition: + raise EvidenceError(message) + + +def matches(value, pattern): + + return ( + isinstance(value, str) + and re.fullmatch(pattern, value) is not None + ) + + +def checksum(data): + + payload = { + key: value + for key, value in data.items() + if key != "checksum" + } + + return hashlib.sha256( + json.dumps( + payload, + sort_keys=True, + separators=(",", ":"), + allow_nan=False, + ).encode() + ).hexdigest() + + +def unique_keys(items): + + result = {} + + for key, value in items: + + require( + key not in result, + "Duplicate backup evidence key", + ) + + result[key] = value + + return result + + +class BackupEvidence: + + MAX_BYTES = 65536 + + def __init__(self, directory): + + self.directory = Path(directory).absolute() + + self.validate_directory() + + def validate_directory(self): + + root = self.directory + + require( + root.is_dir() + and root.resolve() == root + and not root.is_symlink(), + "Invalid backup evidence directory", + ) + + details = root.stat() + + require( + details.st_uid == os.getuid() + and not ( + stat.S_IMODE(details.st_mode) & 0o077 + ), + "Unsafe backup evidence directory permissions", + ) + + def path(self, transaction_id): + + require( + matches( + transaction_id, + r"[a-f0-9]{32}", + ), + "Invalid transaction identifier", + ) + + return self.directory / ( + transaction_id + ".backup.json" + ) + + def validate_backup(self, backup): + + require( + isinstance(backup, dict) + and set(backup) == FIELDS, + "Invalid backup evidence structure", + ) + + require( + matches( + backup["backup_id"], + r"[A-Za-z0-9][A-Za-z0-9_.-]{0,199}", + ) + and ".." not in backup["backup_id"], + "Invalid backup identifier", + ) + + require( + backup["driver"] in ( + "mysql", + "postgresql", + ), + "Invalid database driver", + ) + + for field in ( + "database", + "username", + "container", + ): + + require( + matches( + backup[field], + r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}", + ), + f"Invalid backup {field}", + ) + + require( + isinstance(backup["identity"], str) + and 1 <= len(backup["identity"]) <= 4096 + and "\x00" not in backup["identity"], + "Invalid database identity", + ) + + filename = { + "mysql": "database.sql", + "postgresql": "database.dump", + }[backup["driver"]] + + require( + backup["filename"] == filename, + "Invalid backup filename", + ) + + require( + matches( + backup["sha256"], + r"[a-f0-9]{64}", + ), + "Invalid backup checksum", + ) + + require( + type(backup["bytes"]) is int + and backup["bytes"] > 0, + "Invalid backup size", + ) + + def validate(self, data, transaction_id): + + require( + isinstance(data, dict) + and set(data) == { + "format_version", + "transaction_id", + "backup", + "checksum", + }, + "Invalid backup evidence record", + ) + + require( + type(data["format_version"]) is int + and data["format_version"] == 1, + "Unsupported evidence format", + ) + + require( + data["transaction_id"] == transaction_id, + "Backup evidence transaction mismatch", + ) + + self.validate_backup(data["backup"]) + + require( + matches( + data["checksum"], + r"[a-f0-9]{64}", + ) + and checksum(data) == data["checksum"], + "Backup evidence checksum mismatch", + ) + + def load(self, transaction_id): + + self.validate_directory() + + path = self.path(transaction_id) + + fd = None + + try: + + fd = os.open( + path, + os.O_RDONLY + | os.O_NOFOLLOW + | os.O_NONBLOCK + | os.O_CLOEXEC, + ) + + details = os.fstat(fd) + + require( + stat.S_ISREG(details.st_mode) + and details.st_uid == os.getuid() + and details.st_nlink == 1 + and stat.S_IMODE(details.st_mode) == 0o600 + and details.st_size <= self.MAX_BYTES, + "Unsafe backup evidence file", + ) + + with os.fdopen(fd, "rb") as handle: + + fd = None + + raw = handle.read( + self.MAX_BYTES + 1 + ) + + require( + len(raw) <= self.MAX_BYTES, + "Backup evidence exceeds size limit", + ) + + data = json.loads( + raw, + object_pairs_hook=unique_keys, + ) + + self.validate( + data, + transaction_id, + ) + + return data + + except EvidenceError: + + raise + + except ( + OSError, + ValueError, + TypeError, + ) as error: + + raise EvidenceError( + "Unable to read backup evidence" + ) from error + + finally: + + if fd is not None: + os.close(fd) + + def create(self, transaction_id, manifest): + + self.validate_directory() + + path = self.path(transaction_id) + + require( + isinstance(manifest, dict) + and FIELDS <= set(manifest), + "Incomplete backup manifest", + ) + + backup = { + field: manifest[field] + for field in FIELDS + } + + self.validate_backup(backup) + + data = { + "format_version": 1, + "transaction_id": transaction_id, + "backup": backup, + } + + data["checksum"] = checksum(data) + + self.validate( + data, + transaction_id, + ) + + with DeploymentLock( + self.directory / ".backup-evidence.lock" + ): + + require( + not path.exists() + and not path.is_symlink(), + "Existing backup evidence cannot be overwritten", + ) + + temporary = self.directory / ( + ".backup-evidence-" + + uuid.uuid4().hex + ) + + fd = None + created = False + + try: + + fd = os.open( + temporary, + os.O_WRONLY + | os.O_CREAT + | os.O_EXCL + | os.O_NOFOLLOW + | os.O_CLOEXEC, + 0o600, + ) + + created = True + + with os.fdopen(fd, "w") as handle: + + fd = None + + json.dump( + data, + handle, + sort_keys=True, + indent=2, + allow_nan=False, + ) + + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + + # Publish without overwriting existing evidence. + os.link( + temporary, + path, + follow_symlinks=False, + ) + + temporary.unlink() + created = False + + directory_fd = os.open( + self.directory, + os.O_RDONLY + | os.O_DIRECTORY + | os.O_NOFOLLOW, + ) + + try: + os.fsync(directory_fd) + finally: + os.close(directory_fd) + + except OSError as error: + + raise EvidenceError( + "Unable to persist backup evidence" + ) from error + + finally: + + if fd is not None: + os.close(fd) + + if created: + temporary.unlink(missing_ok=True) + + require( + self.load(transaction_id) == data, + "Backup evidence verification failed", + ) + + return data diff --git a/core/compatibility.py b/core/compatibility.py new file mode 100644 index 0000000..ff23734 --- /dev/null +++ b/core/compatibility.py @@ -0,0 +1,221 @@ +"""Conservative migration compatibility assessment.""" + +import hashlib +import json +import re + +from pathlib import PurePosixPath + +from core.provenance import DEPENDENCIES + + +class CompatibilityError(RuntimeError): + """Migration compatibility could not be established.""" + + +def require(condition, message): + + if not condition: + raise CompatibilityError(message) + + +def valid_hash(value, length): + + return ( + isinstance(value, str) + and re.fullmatch( + rf"[a-f0-9]{{{length}}}", + value, + ) is not None + ) + + +def canonical_hash(data): + + encoded = json.dumps( + data, + sort_keys=True, + separators=(",", ":"), + allow_nan=False, + ).encode("utf-8") + + return hashlib.sha256(encoded).hexdigest() + + +def provenance_fingerprint(data): + + require( + isinstance(data, dict), + "Invalid provenance evidence", + ) + + return canonical_hash({ + key: value + for key, value in data.items() + if key != "fingerprint" + }) + + +def validate_migration_path(value): + + require( + isinstance(value, str), + "Invalid migration path", + ) + + path = PurePosixPath(value) + + require( + not path.is_absolute() + and path.as_posix() == value + and ".." not in path.parts + and len(path.parts) >= 3 + and path.parts[:2] == ("database", "migrations") + and path.suffix == ".php" + and all( + re.fullmatch( + r"[A-Za-z0-9_.-]+", part + ) is not None + for part in path.parts + ), + "Unsafe migration path", + ) + + +def validate_provenance(data): + + require( + isinstance(data, dict) + and set(data) == { + "format_version", + "revision", + "migrations", + "dependencies", + "fingerprint", + }, + "Invalid provenance evidence structure", + ) + + require( + type(data["format_version"]) is int + and data["format_version"] == 1, + "Unsupported provenance format", + ) + + require( + valid_hash(data["revision"], 40), + "Invalid Git revision", + ) + + require( + isinstance(data["migrations"], dict), + "Invalid migration inventory", + ) + + require( + isinstance(data["dependencies"], dict) + and set(data["dependencies"]) == set(DEPENDENCIES), + "Invalid dependency inventory", + ) + + for name, digest in data["migrations"].items(): + + validate_migration_path(name) + + require( + valid_hash(digest, 64), + "Invalid migration checksum", + ) + + for digest in data["dependencies"].values(): + + require( + valid_hash(digest, 64), + "Invalid dependency checksum", + ) + + require( + valid_hash(data["fingerprint"], 64) + and provenance_fingerprint(data) + == data["fingerprint"], + "Provenance fingerprint mismatch", + ) + + +def compare_migrations(previous, candidate): + + validate_provenance(previous) + validate_provenance(candidate) + + same_revision = ( + previous["revision"] == candidate["revision"] + ) + + require( + not same_revision + or previous["fingerprint"] == candidate["fingerprint"], + "Conflicting evidence for identical Git revision", + ) + + old = previous["migrations"] + new = candidate["migrations"] + + old_names = set(old) + new_names = set(new) + + added = sorted(new_names - old_names) + removed = sorted(old_names - new_names) + + modified = sorted( + name + for name in old_names & new_names + if old[name] != new[name] + ) + + unchanged = sorted( + name + for name in old_names & new_names + if old[name] == new[name] + ) + + compatible = not ( + added or removed or modified + ) + + result = { + "format_version": 1, + "previous_revision": previous["revision"], + "candidate_revision": candidate["revision"], + "previous_fingerprint": previous["fingerprint"], + "candidate_fingerprint": candidate["fingerprint"], + "same_revision": same_revision, + "previous_count": len(old), + "candidate_count": len(new), + "unchanged_count": len(unchanged), + "added": added, + "removed": removed, + "modified": modified, + "unchanged": unchanged, + "compatible_without_migrations": compatible, + "requires_migration_review": not compatible, + "database_runtime_verified": False, + } + + result["fingerprint"] = canonical_hash(result) + + return result + + +def require_compatible(previous, candidate): + + result = compare_migrations( + previous, + candidate, + ) + + require( + result["compatible_without_migrations"], + "Migration changes require review and explicit approval", + ) + + return result diff --git a/core/configuration.py b/core/configuration.py new file mode 100644 index 0000000..fc6c13e --- /dev/null +++ b/core/configuration.py @@ -0,0 +1,442 @@ +"""Strict, non-secret deployment configuration validation.""" + +import copy +import json +import re +from pathlib import Path, PurePosixPath + + +class ConfigurationError(ValueError): + """Invalid deployment configuration.""" + + +def require(condition, message): + + if not condition: + raise ConfigurationError(message) + + +def object_fields(value, fields, location): + + require( + isinstance(value, dict), + f"{location} must be an object", + ) + + require( + set(value) == set(fields), + f"{location} contains missing or unknown fields", + ) + + +def string_pattern(value, pattern, location): + + require( + isinstance(value, str) + and re.fullmatch(pattern, value) is not None, + f"Invalid {location}", + ) + + +def integer(value, minimum, maximum, location): + + require( + type(value) is int + and minimum <= value <= maximum, + f"Invalid {location}", + ) + + +def required_true(value, location): + + require( + value is True, + f"{location} must be enabled", + ) + + +def absolute_path(value, location): + + require( + isinstance(value, str) + and re.fullmatch( + r"/[A-Za-z0-9._/-]+", value + ) is not None, + f"Invalid {location}", + ) + + path = PurePosixPath(value) + + require( + path.is_absolute() + and str(path) == value + and ".." not in path.parts + and value != "/", + f"Unsafe {location}", + ) + + +def domain(value): + + require( + isinstance(value, str) + and len(value) <= 253, + "Invalid site domain", + ) + + parts = value.split(".") + + require( + len(parts) >= 2, + "Invalid site domain", + ) + + for part in parts: + + string_pattern( + part, + r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", + "domain label", + ) + + +def repository_url(value): + + require( + isinstance(value, str), + "Invalid repository URL", + ) + + patterns = ( + r"(?:[A-Za-z0-9_-]+@)?" + r"[A-Za-z0-9.-]+:" + r"[A-Za-z0-9_./-]+\.git", + + r"https://[A-Za-z0-9.-]+" + r"(?::[0-9]+)?" + r"/[A-Za-z0-9_./-]+\.git", + + r"ssh://(?:[A-Za-z0-9_-]+@)?" + r"[A-Za-z0-9.-]+" + r"(?::[0-9]+)?" + r"/[A-Za-z0-9_./-]+\.git", + ) + + require( + any( + re.fullmatch(pattern, value) + for pattern in patterns + ) + and ".." not in value, + "Unsafe or unsupported repository URL", + ) + + +def validate_config(data): + + object_fields( + data, + { + "schema_version", + "site", + "repository", + "database", + "docker", + "retention", + "migration", + "backup", + "health", + }, + "Configuration", + ) + + require( + type(data["schema_version"]) is int + and data["schema_version"] == 1, + "Unsupported configuration schema", + ) + + identifier = r"[a-z0-9][a-z0-9-]{0,62}" + service_name = r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}" + database_name = r"[A-Za-z_][A-Za-z0-9_]{0,62}" + + site = data["site"] + + object_fields( + site, + {"identifier", "domain", "root", "origin_port"}, + "site", + ) + + string_pattern( + site["identifier"], identifier, "site identifier" + ) + + domain(site["domain"]) + absolute_path(site["root"], "site root") + + integer( + site["origin_port"], 1024, 65535, "origin port" + ) + + repository = data["repository"] + + object_fields( + repository, + {"url", "branch"}, + "repository", + ) + + repository_url(repository["url"]) + + branch = repository["branch"] + + string_pattern( + branch, + r"[A-Za-z0-9][A-Za-z0-9_./-]{0,127}", + "repository branch", + ) + + require( + ".." not in branch + and all( + part + and not part.startswith(".") + and not part.endswith(".lock") + and not part.endswith(".") + for part in branch.split("/") + ), + "Unsafe repository branch", + ) + + database = data["database"] + + object_fields( + database, + { + "driver", + "container", + "host", + "port", + "name", + "username", + }, + "database", + ) + + require( + database["driver"] in ("mysql", "pgsql"), + "Unsupported database driver", + ) + + string_pattern( + database["container"], + service_name, + "database container", + ) + + string_pattern( + database["host"], + r"[A-Za-z0-9][A-Za-z0-9.-]{0,252}", + "database host", + ) + + string_pattern( + database["name"], + database_name, + "database name", + ) + + string_pattern( + database["username"], + database_name, + "database username", + ) + + integer( + database["port"], 1, 65535, "database port" + ) + + docker = data["docker"] + + object_fields( + docker, + { + "project", + "application_path", + "php_service", + "web_service", + "queue_service", + "scheduler_service", + "backend_network", + "proxy_network", + }, + "docker", + ) + + absolute_path( + docker["application_path"], + "container application path", + ) + + service_keys = ( + "php_service", + "web_service", + "queue_service", + "scheduler_service", + ) + + for key in ( + "project", + *service_keys, + "backend_network", + "proxy_network", + ): + + string_pattern( + docker[key], service_name, f"docker.{key}" + ) + + require( + len({docker[key] for key in service_keys}) == 4, + "Docker service names must be distinct", + ) + + retention = data["retention"] + + object_fields( + retention, + {"keep_releases", "automatic_deletion"}, + "retention", + ) + + integer( + retention["keep_releases"], + 1, 100, + "retention count", + ) + + require( + retention["automatic_deletion"] is False, + "Automatic destructive cleanup is prohibited", + ) + + migration = data["migration"] + + object_fields( + migration, + { + "require_approval", + "require_rehearsal", + "approval_ttl_hours", + }, + "migration", + ) + + required_true( + migration["require_approval"], "migration approval" + ) + + required_true( + migration["require_rehearsal"], "migration rehearsal" + ) + + integer( + migration["approval_ttl_hours"], + 1, 72, + "migration approval TTL", + ) + + backup = data["backup"] + + object_fields( + backup, + {"required", "verify_checksum"}, + "backup", + ) + + required_true(backup["required"], "database backup") + + required_true( + backup["verify_checksum"], "backup checksum" + ) + + health = data["health"] + + object_fields( + health, + {"endpoints", "timeout_seconds"}, + "health", + ) + + endpoints = health["endpoints"] + + require( + isinstance(endpoints, list) + and 1 <= len(endpoints) <= 20, + "Invalid health endpoint list", + ) + + for endpoint in endpoints: + + string_pattern( + endpoint, + r"/[A-Za-z0-9/_-]*", + "health endpoint", + ) + + require( + not endpoint.startswith("//"), + "External health endpoints are prohibited", + ) + + require( + len(set(endpoints)) == len(endpoints), + "Duplicate health endpoints", + ) + + integer( + health["timeout_seconds"], + 1, 120, + "health timeout", + ) + + return copy.deepcopy(data) + + +def unique_json_object(pairs): + + result = {} + + for key, value in pairs: + + require( + key not in result, + "Duplicate JSON configuration field", + ) + + result[key] = value + + return result + + +def load_config(path): + + try: + + with Path(path).open( + "r", encoding="utf-8" + ) as handle: + + data = json.load( + handle, + object_pairs_hook=unique_json_object, + ) + + except (OSError, UnicodeError, ValueError) as error: + + raise ConfigurationError( + "Unable to read valid configuration" + ) from error + + return validate_config(data) diff --git a/core/database.py b/core/database.py new file mode 100644 index 0000000..e04191f --- /dev/null +++ b/core/database.py @@ -0,0 +1,122 @@ +"""Database adapter interface and validated adapter factory.""" + +from abc import ABC, abstractmethod +from types import MappingProxyType +import re + +from core.configuration import ( + ConfigurationError, + validate_config, +) + + +class DatabaseError(RuntimeError): + """Invalid or unsafe database operation.""" + + +class DatabaseAdapter(ABC): + + def __init__(self, config): + + try: + + validated = validate_config(config) + + except ConfigurationError as error: + + raise DatabaseError( + "Invalid database configuration" + ) from error + + self.database = MappingProxyType( + validated["database"] + ) + + @property + @abstractmethod + def backup_extension(self): + pass + + @abstractmethod + def ping_command(self): + pass + + @abstractmethod + def version_command(self): + pass + + @abstractmethod + def identity_command(self): + pass + + @abstractmethod + def backup_command(self): + pass + + @abstractmethod + def restore_command(self, target): + pass + + def docker_exec(self, interactive=False): + + command = ["docker", "exec"] + + if interactive: + command.append("-i") + + command.append( + self.database["container"] + ) + + return command + + def validate_restore_target(self, target): + + if ( + not isinstance(target, str) + or re.fullmatch( + r"isolated_restore_[a-z0-9_]{1,45}", + target, + ) is None + ): + + raise DatabaseError( + "Only isolated restoration targets are permitted" + ) + + if target.lower() == self.database["name"].lower(): + + raise DatabaseError( + "Restoration into the configured database is prohibited" + ) + + return target + + +def get_adapter(config): + + try: + + validated = validate_config(config) + + except ConfigurationError as error: + + raise DatabaseError( + "Invalid database configuration" + ) from error + + driver = validated["database"]["driver"] + + if driver == "mysql": + + from adapters.mysql.adapter import MySQLAdapter + + return MySQLAdapter(validated) + + if driver == "pgsql": + + from adapters.postgresql.adapter import PostgreSQLAdapter + + return PostgreSQLAdapter(validated) + + raise DatabaseError("Unsupported database driver") diff --git a/core/deployment.py b/core/deployment.py new file mode 100644 index 0000000..d7c40eb --- /dev/null +++ b/core/deployment.py @@ -0,0 +1,363 @@ +"""Coordinated deployment with conservative failure containment. + +External service operations must be provided by trusted adapters. +This module does not directly execute Docker or database commands. +""" + +from pathlib import Path + +from core.compatibility import require_compatible +from core.backup_evidence import BackupEvidence +from core.operation_guard import OperationGuard +from core.locking import DeploymentLock + + +class DeploymentError(RuntimeError): + """Deployment failed or requires explicit recovery.""" + + +def require(condition, message): + + if not condition: + raise DeploymentError(message) + + +class DeploymentController: + + def __init__( + self, + *, + site, + lock_path, + releases, + provenance, + journal, + backup, + services, + health, + runtime_check, + stopped_check, + backup_evidence, + operation_guard, + ): + + self.site = site + self.lock_path = Path(lock_path) + self.releases = releases + self.provenance = provenance + self.journal = journal + self.backup = backup + self.services = services + self.health = health + self.runtime_check = runtime_check + self.stopped_check = stopped_check + + require( + isinstance(backup_evidence, BackupEvidence), + "A persistent backup evidence store is required", + ) + + self.backup_evidence = backup_evidence + + require( + isinstance(operation_guard, OperationGuard), + "A shared operation guard is required", + ) + + self.operation_guard = operation_guard + + def deploy(self, candidate): + + with DeploymentLock(self.lock_path): + + return self._deploy(candidate) + + def _deploy(self, candidate): + + transaction = None + quiesce_started = False + operation = "preflight" + + try: + + self.operation_guard.require_clear() + + require( + self.journal.load() is None, + "Existing transaction requires review", + ) + + previous = self.releases.current() + + require( + previous is not None, + "Initial deployment requires separate provisioning", + ) + + require( + previous != candidate, + "Candidate is already active", + ) + + old_path = self.releases.validate(previous) + + new_path = self.releases.validate(candidate) + + old_evidence = self.provenance.verify(old_path) + + new_evidence = self.provenance.verify(new_path) + + require_compatible( + old_evidence, + new_evidence, + ) + + require( + self.runtime_check() is True, + "Database runtime verification failed", + ) + + operation = "create transaction" + + transaction = self.journal.create( + site=self.site, + previous=previous, + candidate=candidate, + revision=new_evidence["revision"], + provenance=new_evidence["fingerprint"], + previous_revision=old_evidence["revision"], + previous_provenance=old_evidence["fingerprint"], + ) + + def advance(phase): + + nonlocal transaction + + transaction = self.journal.transition( + transaction["transaction_id"], + transaction["phase"], + phase, + ) + + operation = "database backup" + + backup = self.backup.create() + manifest = self.backup.verify(backup) + + operation = "persist backup evidence" + + evidence = self.backup_evidence.create( + transaction["transaction_id"], + manifest, + ) + + require( + self.backup_evidence.load( + transaction["transaction_id"] + ) == evidence, + "Backup evidence readback failed", + ) + + advance("BACKED_UP") + + operation = "quiesce background workers" + + quiesce_started = True + + self.services.quiesce() + + require( + self.stopped_check() is True, + "Worker shutdown could not be verified", + ) + + advance("QUIESCED") + + operation = "revalidate deployment" + + require( + self.releases.current() == previous, + "Active release changed during deployment", + ) + + require( + self.runtime_check() is True, + "Database runtime verification changed", + ) + + require( + self.provenance.verify( + self.releases.validate(previous) + ) == old_evidence, + "Previous release provenance changed", + ) + + require( + self.provenance.verify( + self.releases.validate(candidate) + ) == new_evidence, + "Candidate provenance changed", + ) + + operation = "activate candidate" + + advance("ACTIVATING") + + self.releases.activate(candidate) + + advance("ACTIVATED") + + operation = "refresh application services" + + self.services.refresh() + + operation = "restore background workers" + + self.services.resume() + + operation = "verify application health" + + report = self.health.verify(candidate) + + require( + isinstance(report, dict) + and report.get("healthy") is True + and report.get("release") == candidate, + "Application health verification failed", + ) + + require( + self.releases.current() == candidate, + "Active release changed after verification", + ) + + operation = "finalise deployment" + + advance("VERIFIED") + + return transaction + + except Exception: + + containment_ok = True + journal_ok = True + + if quiesce_started: + + try: + + self.services.quiesce() + + containment_ok = ( + self.stopped_check() is True + ) + + except Exception: + + containment_ok = False + + if transaction is not None: + + try: + + actual = self.journal.load() + + if ( + actual is None + or actual["transaction_id"] + != transaction["transaction_id"] + ): + + journal_ok = False + + elif actual["phase"] not in ( + "VERIFIED", + "FAILED", + ): + + self.journal.transition( + actual["transaction_id"], + actual["phase"], + "FAILED", + ) + + elif actual["phase"] == "VERIFIED": + + journal_ok = False + + except Exception: + + journal_ok = False + + raise DeploymentError( + f"Deployment failed during {operation}; " + f"containment={containment_ok}; " + f"journal={journal_ok}; " + "explicit inspection required" + ) from None + + def recovery_plan(self): + + with DeploymentLock(self.lock_path): + + transaction = self.journal.load() + + if transaction is None: + + return { + "status": "CLEAR", + "automatic_rollback_allowed": False, + } + + current = self.releases.current() + + transaction_id = transaction["transaction_id"] + + evidence_path = self.backup_evidence.path( + transaction_id + ) + + evidence_present = ( + evidence_path.exists() + or evidence_path.is_symlink() + ) + + backup_id = None + + if evidence_present: + + try: + evidence = self.backup_evidence.load( + transaction_id + ) + + backup_id = evidence["backup"]["backup_id"] + + except Exception: + raise DeploymentError( + "Invalid backup evidence; recovery blocked" + ) from None + + backup_required = any( + event["phase"] == "BACKED_UP" + for event in transaction["history"] + ) + + require( + not backup_required or evidence_present, + "Required backup evidence is missing", + ) + + return { + "backup_evidence_present": evidence_present, + "backup_id": backup_id, + "status": transaction["phase"], + "transaction_id": ( + transaction["transaction_id"] + ), + "previous": transaction["previous"], + "candidate": transaction["candidate"], + "current": current, + "automatic_rollback_allowed": False, + "explicit_review_required": True, + } diff --git a/core/execution.py b/core/execution.py new file mode 100644 index 0000000..a03edae --- /dev/null +++ b/core/execution.py @@ -0,0 +1,161 @@ +"""Explicitly authorised, non-interactive command execution.""" + +import os +import shutil +import signal +import subprocess +import tempfile + + +class ExecutionError(RuntimeError): + """Command execution failed or was prohibited.""" + + +def normalise_command(command): + + if ( + not isinstance(command, (tuple, list)) + or not command + ): + + raise ExecutionError( + "Invalid command" + ) + + if any( + not isinstance(argument, str) + or "\x00" in argument + for argument in command + ): + + raise ExecutionError( + "Invalid command argument" + ) + + if not command[0]: + + raise ExecutionError( + "Missing executable" + ) + + return tuple(command) + + +class CommandRunner: + + def __init__( + self, + allowed_commands, + timeout=300, + ): + + if ( + type(timeout) is not int + or not 1 <= timeout <= 3600 + ): + + raise ExecutionError( + "Invalid command timeout" + ) + + self.allowed = frozenset( + normalise_command(command) + for command in allowed_commands + ) + + if not self.allowed: + + raise ExecutionError( + "Command allowlist is empty" + ) + + self.timeout = timeout + + def __call__(self, command, output): + + command = normalise_command(command) + + if command not in self.allowed: + + raise ExecutionError( + "Command is not authorised" + ) + + if not callable( + getattr(output, "write", None) + ): + + raise ExecutionError( + "Invalid output destination" + ) + + # Stage output privately until the subprocess + # has completed successfully. No partial output + # is published on command failure. + + with tempfile.TemporaryFile( + mode="w+b" + ) as staged: + + try: + + process = subprocess.Popen( + command, + stdin=subprocess.DEVNULL, + stdout=staged, + stderr=subprocess.DEVNULL, + shell=False, + start_new_session=True, + ) + + except OSError: + + raise ExecutionError( + "Unable to start authorised command" + ) from None + + try: + + status = process.wait( + timeout=self.timeout + ) + + except BaseException as error: + + try: + + os.killpg( + process.pid, + signal.SIGKILL, + ) + + except ProcessLookupError: + + pass + + process.wait() + + if isinstance( + error, + subprocess.TimeoutExpired, + ): + + raise ExecutionError( + "Command execution timed out" + ) from None + + raise + + if status != 0: + + raise ExecutionError( + f"Command exited with status {status}" + ) + + staged.seek(0) + + shutil.copyfileobj( + staged, + output, + length=1024 * 1024, + ) diff --git a/core/health.py b/core/health.py new file mode 100644 index 0000000..a035cda --- /dev/null +++ b/core/health.py @@ -0,0 +1,246 @@ +"""Read-only application health assessment. + +All external operations are supplied through injected probes. +""" + +import re +import time + +from core.configuration import ( + ConfigurationError, + validate_config, +) + + +class HealthError(RuntimeError): + """Application health could not be established.""" + + +def require(condition, message): + + if not condition: + raise HealthError(message) + + +class HealthVerifier: + + def __init__( + self, + config, + *, + http_probe, + service_probe, + database_probe, + redis_probe, + asset_probe, + release_probe, + attempts=1, + retry_delay=2, + sleep=time.sleep, + ): + + try: + + validated = validate_config(config) + + except ConfigurationError: + + raise HealthError( + "Invalid health configuration" + ) from None + + require( + type(attempts) is int + and 1 <= attempts <= 10, + "Invalid health verification attempt count", + ) + + require( + type(retry_delay) is int + and 0 <= retry_delay <= 30, + "Invalid health retry delay", + ) + + for probe in ( + http_probe, + service_probe, + database_probe, + redis_probe, + asset_probe, + release_probe, + sleep, + ): + + require( + callable(probe), + "Invalid health probe", + ) + + site = validated["site"] + docker = validated["docker"] + health = validated["health"] + + self._origin = ( + "http://127.0.0.1:" + + str(site["origin_port"]) + ) + + self._domain = site["domain"] + + self._endpoints = tuple( + health["endpoints"] + ) + + self._timeout = health["timeout_seconds"] + + self._services = ( + docker["php_service"], + docker["web_service"], + docker["queue_service"], + docker["scheduler_service"], + ) + + self._http = http_probe + self._service = service_probe + self._database = database_probe + self._redis = redis_probe + self._assets = asset_probe + self._release = release_probe + + self._attempts = attempts + self._retry_delay = retry_delay + self._sleep = sleep + + def _invoke(self, label, probe, *args, **kwargs): + + try: + + return probe(*args, **kwargs) + + except Exception: + + raise HealthError( + f"Health probe failed: {label}" + ) from None + + def _check_release(self, expected): + + actual = self._invoke( + "active release", + self._release, + ) + + require( + isinstance(actual, str) + and actual == expected, + "Active release identity mismatch", + ) + + def _verify_once(self, expected, attempt): + + self._check_release(expected) + + result = { + "format_version": 1, + "release": expected, + "attempt": attempt, + "http": {}, + "services": {}, + "database": False, + "redis": False, + "assets": False, + "healthy": False, + } + + for endpoint in self._endpoints: + + status = self._invoke( + f"HTTP {endpoint}", + self._http, + self._origin + endpoint, + host=self._domain, + timeout=self._timeout, + ) + + require( + type(status) is int + and status == 200, + f"HTTP health check failed: {endpoint}", + ) + + result["http"][endpoint] = status + + for service in self._services: + + ready = self._invoke( + f"service {service}", + self._service, + service, + timeout=self._timeout, + ) + + require( + ready is True, + f"Service not ready: {service}", + ) + + result["services"][service] = True + + for name, probe in ( + ("database", self._database), + ("redis", self._redis), + ("assets", self._assets), + ): + + ready = self._invoke( + name, + probe, + timeout=self._timeout, + ) + + require( + ready is True, + f"Health check failed: {name}", + ) + + result[name] = True + + self._check_release(expected) + + result["healthy"] = True + + return result + + def verify(self, expected_release): + + require( + isinstance(expected_release, str) + and re.fullmatch( + r"[1-9][0-9]{0,19}", + expected_release, + ) is not None, + "Invalid expected release identifier", + ) + + for attempt in range( + 1, + self._attempts + 1, + ): + + try: + + return self._verify_once( + expected_release, + attempt, + ) + + except HealthError: + + if attempt == self._attempts: + raise + + self._sleep(self._retry_delay) + + raise HealthError( + "Application health verification failed" + ) diff --git a/core/inspection_cli.py b/core/inspection_cli.py new file mode 100644 index 0000000..e8e1e29 --- /dev/null +++ b/core/inspection_cli.py @@ -0,0 +1,323 @@ +"""Read-only framework inspection and provisioning planning.""" + +import argparse +import json +import os +import sys + +from pathlib import Path + +from core.configuration import load_config, validate_config +from core.compatibility import canonical_hash +from core.releases import ReleaseManager +from core.retention import plan_retention +from core.site_policy import validate_site, validate_registry +from core.preflight import site_preflight + + +class InspectionError(RuntimeError): + """Inspection failed or supplied data is unsafe.""" + + +def require(condition, message): + if not condition: + raise InspectionError(message) + + +def unique_keys(items): + result = {} + + for key, value in items: + require( + key not in result, + "Duplicate JSON field", + ) + result[key] = value + + return result + + +def read_json(path): + with Path(path).open("rb") as handle: + raw = handle.read(1024 * 1024 + 1) + + require( + len(raw) <= 1024 * 1024, + "JSON policy exceeds size limit", + ) + + return json.loads(raw, object_pairs_hook=unique_keys) + + +def capabilities(): + return { + "format_version": 1, + "production_ready": False, + "deployment_execution_enabled": False, + "migration_execution_enabled": False, + "provisioning_execution_enabled": False, + "database_restore_enabled": False, + "permanent_deletion_enabled": False, + "commands": [ + "validate", + "capabilities", + "inventory", + "retention-plan", + "provision-plan", + "site-policy", + "registry-validate", + "preflight", + ], + } + + +def inventory_report(app): + app = Path(app).absolute() + + require( + app.is_dir() + and not app.is_symlink() + and app.resolve() == app, + "Invalid application directory", + ) + + releases = ReleaseManager(app) + + inventory = releases.inventory() + current = releases.current() + + require( + current in inventory, + "Active release missing from inventory", + ) + + failed = [ + release + for release in inventory + if os.path.lexists( + releases.release_path(release) / "BAD_RELEASE" + ) + ] + + require( + current not in failed, + "Active release is marked failed", + ) + + require( + releases.current() == current + and releases.inventory() == inventory, + "Release inventory changed during inspection", + ) + + report = { + "format_version": 1, + "status": "INSPECTED", + "application_path": str(app), + "current": current, + "inventory": inventory, + "failed": failed, + "transaction_protections_verified": False, + "runtime_verified": False, + "execution_permitted": False, + } + + report["fingerprint"] = canonical_hash(report) + + return report + + +def provisioning_plan(config): + config = validate_config(config) + policy = validate_site(config) + + site = config["site"] + root = Path(site["root"]) + database = config["database"] + docker = config["docker"] + + result = { + "format_version": 1, + "status": "PLAN_ONLY", + "site": site["identifier"], + "domain": site["domain"], + "root": str(root), + "origin_port": site["origin_port"], + "repository": { + "url": config["repository"]["url"], + "branch": config["repository"]["branch"], + }, + "directories": [ + str(root), + str(root / "app"), + str(root / "app/releases"), + str(root / "app/shared"), + str(root / "deployment"), + str(root / "backups"), + str(root / "deployment/state"), + str(root / "deployment/approvals"), + str(root / "deployment/archives"), + ], + "database": { + "driver": database["driver"], + "container": database["container"], + "name": database["name"], + "username": database["username"], + }, + "docker": { + "project": docker["project"], + "services": [ + docker["php_service"], + docker["web_service"], + docker["queue_service"], + docker["scheduler_service"], + ], + "networks": [ + docker["backend_network"], + docker["proxy_network"], + ], + }, + "retention": config["retention"], + "configuration_fingerprint": canonical_hash(config), + "static_policy_verified": True, + "site_policy_fingerprint": policy["fingerprint"], + "resource_conflicts_checked": False, + "filesystem_permissions_verified": False, + "secrets_required": True, + "database_creation_permitted": False, + "execution_permitted": False, + } + + result["fingerprint"] = canonical_hash(result) + + return result + + +def parser(): + result = argparse.ArgumentParser( + prog="absdev-deploy", + description="ABSDEV deployment framework (inspection only)", + ) + + commands = result.add_subparsers( + dest="command", + required=True, + ) + + validate = commands.add_parser( + "validate", + help="Validate site configuration", + ) + validate.add_argument("--config", required=True) + + commands.add_parser( + "capabilities", + help="Show enabled framework capabilities", + ) + + inventory = commands.add_parser( + "inventory", + help="Inspect application release inventory", + ) + inventory.add_argument("--app", required=True) + + retention = commands.add_parser( + "retention-plan", + help="Evaluate a supplied retention policy", + ) + retention.add_argument("--policy", required=True) + + provision = commands.add_parser( + "provision-plan", + help="Generate a read-only provisioning plan", + ) + provision.add_argument("--config", required=True) + + policy = commands.add_parser( + "site-policy", + help="Validate static site isolation policy", + ) + policy.add_argument("--config", required=True) + + registry = commands.add_parser( + "registry-validate", + help="Validate supplied site registry", + ) + registry.add_argument("--registry", required=True) + + preflight = commands.add_parser( + "preflight", + help="Check prospective site against supplied registry", + ) + preflight.add_argument("--config", required=True) + preflight.add_argument("--registry", required=True) + + return result + + +def main(argv=None): + args = parser().parse_args(argv) + + try: + if args.command == "capabilities": + report = capabilities() + + elif args.command == "inventory": + report = inventory_report(args.app) + + elif args.command == "retention-plan": + report = plan_retention( + read_json(args.policy) + ) + + elif args.command == "provision-plan": + report = provisioning_plan( + load_config(args.config) + ) + + elif args.command == "site-policy": + report = validate_site( + load_config(args.config) + ) + + elif args.command == "registry-validate": + report = validate_registry( + read_json(args.registry) + ) + + elif args.command == "preflight": + report = site_preflight( + load_config(args.config), + read_json(args.registry), + ) + + elif args.command == "validate": + load_config(args.config) + + report = { + "status": "VALID", + "execution_permitted": False, + } + + else: + raise InspectionError("Unsupported command") + + print(json.dumps( + report, + indent=2, + sort_keys=True, + allow_nan=False, + )) + + return 0 + + except Exception as error: + # Avoid exposing configuration contents, + # credentials or external command output. + + print( + f"Inspection failed: {type(error).__name__}", + file=sys.stderr, + ) + + return 1 diff --git a/core/locking.py b/core/locking.py new file mode 100644 index 0000000..48529ab --- /dev/null +++ b/core/locking.py @@ -0,0 +1,202 @@ +"""Exclusive filesystem-based deployment locking.""" + +import fcntl +import os +import stat +from pathlib import Path + + +class LockError(RuntimeError): + """Deployment lock unavailable or unsafe.""" + + +class DeploymentLock: + + def __init__(self, path): + + self.path = Path(path) + self._fd = None + + if not self.path.is_absolute(): + + raise LockError( + "Deployment lock path must be absolute" + ) + + if ".." in self.path.parts: + + raise LockError( + "Unsafe deployment lock path" + ) + + @property + def acquired(self): + + return self._fd is not None + + def validate_parent(self): + + parent = self.path.parent + + if ( + not parent.is_dir() + or parent.is_symlink() + or parent.resolve() != parent + ): + + raise LockError( + "Invalid deployment lock directory" + ) + + def acquire(self): + + if self.acquired: + + raise LockError( + "Deployment lock already acquired" + ) + + fd = None + parent_fd = None + + try: + + self.validate_parent() + + parent_fd = os.open( + self.path.parent, + os.O_RDONLY + | os.O_DIRECTORY + | os.O_NOFOLLOW + | os.O_CLOEXEC, + ) + + parent = os.fstat(parent_fd) + + if ( + parent.st_uid != os.getuid() + or stat.S_IMODE(parent.st_mode) & 0o022 + ): + + raise LockError( + "Unsafe deployment lock directory permissions" + ) + + fd = os.open( + self.path.name, + os.O_RDWR + | os.O_CREAT + | os.O_NOFOLLOW + | os.O_NONBLOCK + | os.O_CLOEXEC, + 0o600, + dir_fd=parent_fd, + ) + + details = os.fstat(fd) + + if ( + not stat.S_ISREG(details.st_mode) + or details.st_uid != os.getuid() + or details.st_nlink != 1 + or stat.S_IMODE(details.st_mode) != 0o600 + ): + + raise LockError( + "Unsafe deployment lock file" + ) + + try: + + fcntl.flock( + fd, + fcntl.LOCK_EX | fcntl.LOCK_NB, + ) + + except BlockingIOError: + + raise LockError( + "Another deployment operation is active" + ) from None + + # Check that the directory entry still refers + # to the locked inode. + + entry = os.stat( + self.path.name, + dir_fd=parent_fd, + follow_symlinks=False, + ) + + locked = os.fstat(fd) + + if ( + entry.st_dev != locked.st_dev + or entry.st_ino != locked.st_ino + or locked.st_nlink != 1 + or not stat.S_ISREG(entry.st_mode) + ): + + raise LockError( + "Deployment lock identity changed" + ) + + self._fd = fd + fd = None + + return self + + except LockError: + + raise + + except OSError: + + raise LockError( + "Unable to acquire deployment lock" + ) from None + + finally: + + if fd is not None: + + os.close(fd) + + if parent_fd is not None: + + os.close(parent_fd) + + def release(self): + + if self._fd is None: + return + + fd = self._fd + + self._fd = None + + try: + + fcntl.flock( + fd, + fcntl.LOCK_UN, + ) + + finally: + + os.close(fd) + + def __enter__(self): + + return self.acquire() + + def __exit__( + self, + exc_type, + exc_value, + traceback, + ): + + self.release() + + return False diff --git a/core/migration.py b/core/migration.py new file mode 100644 index 0000000..91c7a64 --- /dev/null +++ b/core/migration.py @@ -0,0 +1,350 @@ +"""Migration coordination using injected trusted operations. + +No direct Docker, SQL, PHP or shell execution. +""" + +import copy +import os +import re + +from pathlib import Path + +from core.approval import verify_approval, timestamp +from core.rehearsal import approval_context +from core.compatibility import canonical_hash +from core.locking import DeploymentLock +from core.operation_guard import OperationGuard + + +class MigrationError(RuntimeError): + """Migration failed or requires explicit recovery.""" + + +def require(condition, message): + if not condition: + raise MigrationError(message) + + +def validate_history(history): + require( + isinstance(history, list) + and len(history) <= 100000, + "Invalid migration history", + ) + + for name in history: + require( + isinstance(name, str) + and re.fullmatch( + r"[A-Za-z0-9_][A-Za-z0-9_-]{0,254}", + name, + ) is not None, + "Invalid migration history entry", + ) + + require( + len(history) == len(set(history)), + "Duplicate migration history entries", + ) + + return list(history) + + +class MigrationCoordinator: + + def __init__( + self, + *, + store, + lock_path, + context_probe, + contain, + containment_probe, + backup_probe, + history_probe, + migration_runner, + application_probe, + clock, + ): + for callback in ( + context_probe, + contain, + containment_probe, + backup_probe, + history_probe, + migration_runner, + application_probe, + clock, + ): + require( + callable(callback), + "Missing migration operation adapter", + ) + + self.store = store + self.operation_guard = OperationGuard(store) + self.lock_path = Path(lock_path) + self.context_probe = context_probe + self.contain = contain + self.containment_probe = containment_probe + self.backup_probe = backup_probe + self.history_probe = history_probe + self.migration_runner = migration_runner + self.application_probe = application_probe + self.clock = clock + + def intent_path(self, identifier): + return self.store.path( + identifier, ".migration-intent.json" + ) + + def result_path(self, identifier): + return self.store.path( + identifier, ".migration-result.json" + ) + + def publish(self, path, data): + record = dict(data) + record["checksum"] = canonical_hash(record) + + return self.store.publish(path, record) + + def execute(self, identifier, rehearsal, *, confirmation): + with DeploymentLock(self.lock_path): + return self._execute( + identifier, rehearsal, confirmation + ) + + def _execute(self, identifier, rehearsal, confirmation): + operation = "preflight" + intent = None + containment_started = False + migration_started = False + + try: + self.operation_guard.require_clear() + + intent_path = self.intent_path(identifier) + result_path = self.result_path(identifier) + + for path in ( + intent_path, + result_path, + self.store.consumed_path(identifier), + ): + require( + not os.path.lexists(path), + "Existing execution evidence requires review", + ) + + rehearsal = copy.deepcopy(rehearsal) + base = copy.deepcopy(self.context_probe()) + current_time = timestamp(self.clock()) + + context = approval_context( + rehearsal, base, now=current_time + ) + + approval = self.store.load(identifier) + + verify_approval( + approval, + context, + confirmation=confirmation, + now=current_time, + ) + + require( + self.backup_probe() is True, + "Backup verification failed", + ) + + before = validate_history(self.history_probe()) + pending = tuple(context["pending_migrations"]) + + require( + not set(before).intersection(pending), + "Pending migration already applied", + ) + + operation = "persist migration intent" + + intent = self.publish( + intent_path, + { + "format_version": 1, + "status": "MIGRATION_INTENT", + "approval_id": identifier, + "approval_checksum": approval["checksum"], + "context_fingerprint": canonical_hash(context), + "site": context["site"], + "release": context["release"], + "revision": context["revision"], + "database_identity": context["database_identity"], + "backup_sha256": context["backup_sha256"], + "rehearsal_fingerprint": + context["rehearsal_fingerprint"], + "history_before": before, + "pending_migrations": list(pending), + "created_at": current_time.isoformat(), + }, + ) + + operation = "establish containment" + containment_started = True + + require( + self.contain() is True, + "Write containment failed", + ) + + require( + self.containment_probe() is True, + "Write containment not verified", + ) + + operation = "revalidate migration context" + + require( + self.context_probe() == base, + "Migration context changed", + ) + + require( + self.backup_probe() is True, + "Backup verification changed", + ) + + require( + validate_history(self.history_probe()) == before, + "Migration history changed", + ) + + require( + self.store.load(identifier) == approval, + "Stored approval changed", + ) + + operation = "consume single-use approval" + + consumed = self.store.consume( + identifier, + base, + rehearsal, + confirmation=confirmation, + now=self.clock(), + ) + + require( + consumed["approval_checksum"] == approval["checksum"], + "Consumed approval mismatch", + ) + + operation = "execute approved migrations" + + require( + self.containment_probe() is True, + "Write containment lost", + ) + + migration_started = True + result = self.migration_runner(pending) + + require( + type(result) is int and result == 0, + "Migration command failed", + ) + + operation = "verify migration history" + + after = validate_history(self.history_probe()) + + require( + after == before + list(pending), + "Migration history differs from approval", + ) + + require( + self.containment_probe() is True, + "Containment lost after migration", + ) + + operation = "verify migrated application" + + require( + self.application_probe() is True, + "Application verification failed", + ) + + require( + self.containment_probe() is True, + "Containment lost during verification", + ) + + operation = "persist migration result" + + return self.publish( + result_path, + { + "format_version": 1, + "status": "MIGRATED", + "approval_id": identifier, + "intent_checksum": intent["checksum"], + "consumption_checksum": consumed["checksum"], + "site": context["site"], + "release": context["release"], + "revision": context["revision"], + "database_identity": context["database_identity"], + "history_after": after, + "applied_migrations": list(pending), + "automatic_database_rollback": False, + "application_activated": False, + "containment_required": True, + "completed_at": timestamp(self.clock()).isoformat(), + }, + ) + + except Exception: + containment_ok = None + evidence_ok = None + + if containment_started: + try: + containment_ok = ( + self.contain() is True + and self.containment_probe() is True + ) + except Exception: + containment_ok = False + + if intent is not None: + try: + if not os.path.lexists(result_path): + self.publish( + result_path, + { + "format_version": 1, + "status": "FAILED", + "approval_id": identifier, + "intent_checksum": intent["checksum"], + "operation": operation, + "migration_may_have_executed": + migration_started, + "manual_recovery_required": True, + "automatic_database_rollback": False, + "containment_verified": containment_ok, + }, + ) + evidence_ok = True + else: + evidence_ok = False + + except Exception: + evidence_ok = False + + raise MigrationError( + f"Migration failed during {operation}; " + f"containment={containment_ok}; " + f"failure_evidence={evidence_ok}; " + "explicit inspection required" + ) from None diff --git a/core/migration_archive.py b/core/migration_archive.py new file mode 100644 index 0000000..a0e8c64 --- /dev/null +++ b/core/migration_archive.py @@ -0,0 +1,474 @@ +"""Logical archival of completed migration transactions. + +Original approvals, consumption records and execution +evidence are retained permanently. +""" + +import os + +from datetime import datetime, timezone +from pathlib import Path + +from core.approval import validate_context +from core.compatibility import canonical_hash +from core.locking import DeploymentLock + + +class MigrationArchiveError(RuntimeError): + """Migration archival evidence is unsafe or incomplete.""" + + +SUFFIXES = ( + ".approval.json", + ".migration-intent.json", + ".consumed.json", + ".migration-result.json", + ".activation-intent.json", + ".activation-result.json", +) + +ARCHIVE_SUFFIX = ".migration-archive.json" + + +def require(condition, message): + + if not condition: + raise MigrationArchiveError(message) + + +def digest(record): + + return canonical_hash({ + key: value + for key, value in record.items() + if key != "checksum" + }) + + +def read_record(store, path): + + record = store.read(path) + + require( + isinstance(record, dict) + and type(record.get("format_version")) is int + and record["format_version"] == 1 + and record.get("checksum") == digest(record), + "Invalid migration archival evidence", + ) + + return record + + +def read_chain(store, identifier): + + approval = store.load(identifier) + + context = approval["context"] + + validate_context(context) + + records = { + suffix: read_record( + store, + store.path(identifier, suffix), + ) + for suffix in SUFFIXES + if suffix != ".approval.json" + } + + records[".approval.json"] = approval + + intent = records[".migration-intent.json"] + consumed = records[".consumed.json"] + migration = records[".migration-result.json"] + activation = records[".activation-intent.json"] + result = records[".activation-result.json"] + + require( + intent["status"] == "MIGRATION_INTENT" + and consumed["status"] == "CONSUMED" + and migration["status"] == "MIGRATED" + and activation["status"] == "ACTIVATION_INTENT" + and result["status"] == "VERIFIED", + "Migration is not fully completed", + ) + + for suffix, record in records.items(): + + require( + record["approval_id"] == identifier, + "Approval identity mismatch", + ) + + if suffix != ".approval.json": + + require( + record["site"] == context["site"], + "Migration site mismatch", + ) + + for record in (intent, consumed, migration): + + for field in ( + "release", + "revision", + "database_identity", + ): + + require( + record[field] == context[field], + "Migration context mismatch", + ) + + for record in (intent, consumed): + + require( + record["approval_checksum"] + == approval["checksum"] + and record["backup_sha256"] + == context["backup_sha256"] + and record["rehearsal_fingerprint"] + == context["rehearsal_fingerprint"], + "Approval evidence mismatch", + ) + + require( + intent["context_fingerprint"] + == canonical_hash(context) + and migration["intent_checksum"] + == intent["checksum"] + and migration["consumption_checksum"] + == consumed["checksum"] + and activation["migration_checksum"] + == migration["checksum"] + and result["intent_checksum"] + == activation["checksum"] + and result["plan_fingerprint"] + == activation["plan_fingerprint"], + "Migration evidence chain mismatch", + ) + + before = intent["history_before"] + pending = context["pending_migrations"] + + require( + isinstance(before, list) + and all( + isinstance(name, str) + for name in before + ) + and len(before) == len(set(before)) + and not set(before).intersection(pending) + and intent["pending_migrations"] == pending + and migration["applied_migrations"] == pending + and migration["history_after"] == before + pending, + "Migration history evidence mismatch", + ) + + require( + consumed["migration_executed"] is False + and migration["automatic_database_rollback"] is False + and migration["application_activated"] is False + and migration["containment_required"] is True + and activation["target"] == context["release"] + and result["active_release"] == context["release"] + and result["health_verified"] is True + and result["database_restored"] is False + and result["migration_reexecuted"] is False, + "Invalid migration completion evidence", + ) + + return records + + +def archive_path(store, identifier): + + return store.path( + identifier, + ARCHIVE_SUFFIX, + ) + + +def verify_archived_group(store, identifier): + + """Validate a historical archive without live probes.""" + + try: + + record = read_record( + store, + archive_path(store, identifier), + ) + + records = read_chain(store, identifier) + + context = records[".approval.json"]["context"] + + require( + set(record) == { + "format_version", + "status", + "approval_id", + "site", + "release", + "record_checksums", + "plan_fingerprint", + "database_restored", + "archived_at", + "checksum", + } + and record["status"] == "ARCHIVED" + and record["approval_id"] == identifier + and record["site"] == context["site"] + and record["release"] == context["release"] + and record["database_restored"] is False, + "Invalid migration archive marker", + ) + + require( + record["record_checksums"] == { + suffix: item["checksum"] + for suffix, item in records.items() + }, + "Archived migration evidence changed", + ) + + return { + identifier + suffix + for suffix in (*SUFFIXES, ARCHIVE_SUFFIX) + } + + except MigrationArchiveError: + raise + + except Exception: + + raise MigrationArchiveError( + "Historical migration archive validation failed" + ) from None + + +class MigrationArchive: + + def __init__( + self, + *, + site, + store, + lock_path, + identity_probe, + history_probe, + provenance_probe, + backup_probe, + current_probe, + health_probe, + writes_enabled_probe, + ): + + self.site = site + self.store = store + self.lock_path = Path(lock_path) + + callbacks = { + "identity_probe": identity_probe, + "history_probe": history_probe, + "provenance_probe": provenance_probe, + "backup_probe": backup_probe, + "current_probe": current_probe, + "health_probe": health_probe, + "writes_enabled_probe": writes_enabled_probe, + } + + for name, callback in callbacks.items(): + + require( + callable(callback), + "Missing archival verification adapter", + ) + + setattr(self, name, callback) + + def path(self, identifier): + + return archive_path( + self.store, + identifier, + ) + + def _plan(self, identifier): + + require( + not os.path.lexists( + self.path(identifier) + ), + "Migration archive already exists", + ) + + records = read_chain( + self.store, + identifier, + ) + + context = records[".approval.json"]["context"] + + migration = records[".migration-result.json"] + + release = context["release"] + + require( + context["site"] == self.site, + "Migration belongs to another site", + ) + + require( + self.current_probe() == release, + "Unexpected active release", + ) + + require( + self.identity_probe() + == context["database_identity"] + and self.history_probe() + == migration["history_after"], + "Database state changed", + ) + + provenance = self.provenance_probe(release) + + require( + isinstance(provenance, dict) + and provenance.get("revision") + == context["revision"] + and provenance.get("fingerprint") + == context["provenance"], + "Release provenance changed", + ) + + require( + self.backup_probe() is True, + "Backup verification failed", + ) + + require( + self.writes_enabled_probe() is True, + "Application remains contained", + ) + + health = self.health_probe(release) + + require( + isinstance(health, dict) + and health.get("healthy") is True + and health.get("release") == release, + "Application health verification failed", + ) + + require( + self.current_probe() == release + and read_chain( + self.store, + identifier, + ) == records, + "Migration evidence changed during planning", + ) + + plan = { + "format_version": 1, + "status": "ARCHIVE_READY", + "approval_id": identifier, + "site": self.site, + "release": release, + "record_checksums": { + suffix: item["checksum"] + for suffix, item in records.items() + }, + "confirmation": ( + "ARCHIVE-MIGRATION-" + identifier + ), + } + + plan["fingerprint"] = canonical_hash(plan) + + return plan + + def plan(self, identifier): + + with DeploymentLock(self.lock_path): + + try: + + return self._plan(identifier) + + except MigrationArchiveError: + raise + + except Exception: + + raise MigrationArchiveError( + "Migration archival preflight failed" + ) from None + + def execute( + self, + identifier, + *, + confirmation, + fingerprint, + ): + + with DeploymentLock(self.lock_path): + + with DeploymentLock( + self.store.directory / ".approval.lock" + ): + + try: + + plan = self._plan(identifier) + + require( + confirmation == plan["confirmation"] + and fingerprint == plan["fingerprint"], + "Archive confirmation or fingerprint changed", + ) + + record = { + "format_version": 1, + "status": "ARCHIVED", + "approval_id": identifier, + "site": self.site, + "release": plan["release"], + "record_checksums": ( + plan["record_checksums"] + ), + "plan_fingerprint": fingerprint, + "database_restored": False, + "archived_at": datetime.now( + timezone.utc + ).isoformat(), + } + + record["checksum"] = digest(record) + + self.store.publish( + self.path(identifier), + record, + ) + + verify_archived_group( + self.store, + identifier, + ) + + return record + + except MigrationArchiveError: + raise + + except Exception: + + raise MigrationArchiveError( + "Migration archival failed; " + "inspect preserved evidence" + ) from None diff --git a/core/migration_recovery.py b/core/migration_recovery.py new file mode 100644 index 0000000..5ae0dff --- /dev/null +++ b/core/migration_recovery.py @@ -0,0 +1,521 @@ +"""Conservative migration recovery and forward activation. + +External operations must be supplied by trusted adapters. +No direct database, Docker or shell execution. +""" + +import os + +from datetime import datetime, timezone +from pathlib import Path + +from core.approval import validate_context +from core.compatibility import canonical_hash +from core.locking import DeploymentLock +from core.migration import validate_history + + +class MigrationRecoveryError(RuntimeError): + """Migration recovery is unsafe or incomplete.""" + + +def require(condition, message): + + if not condition: + raise MigrationRecoveryError(message) + + +class MigrationRecovery: + + def __init__( + self, + *, + site, + store, + lock_path, + identity_probe, + history_probe, + provenance_probe, + backup_probe, + contain, + containment_probe, + current_probe, + activate, + refresh, + readiness_probe, + release_containment, + writes_enabled_probe, + health_probe, + ): + + self.site = site + self.store = store + self.lock_path = Path(lock_path) + + callbacks = { + "identity_probe": identity_probe, + "history_probe": history_probe, + "provenance_probe": provenance_probe, + "backup_probe": backup_probe, + "contain": contain, + "containment_probe": containment_probe, + "current_probe": current_probe, + "activate": activate, + "refresh": refresh, + "readiness_probe": readiness_probe, + "release_containment": release_containment, + "writes_enabled_probe": writes_enabled_probe, + "health_probe": health_probe, + } + + for name, callback in callbacks.items(): + + require( + callable(callback), + "Missing recovery adapter", + ) + + setattr(self, name, callback) + + def intent_path(self, identifier): + + return self.store.path( + identifier, + ".activation-intent.json", + ) + + def result_path(self, identifier): + + return self.store.path( + identifier, + ".activation-result.json", + ) + + def read_record(self, path): + + record = self.store.read(path) + + require( + isinstance(record, dict) + and "checksum" in record + and type(record.get("format_version")) is int + and record["format_version"] == 1, + "Invalid recovery evidence", + ) + + expected = canonical_hash({ + key: value + for key, value in record.items() + if key != "checksum" + }) + + require( + expected == record["checksum"], + "Recovery evidence checksum mismatch", + ) + + return record + + def publish(self, path, record): + + data = dict(record) + data["checksum"] = canonical_hash(data) + + return self.store.publish(path, data) + + def inspect(self, identifier): + + with DeploymentLock(self.lock_path): + + try: + return self._inspect(identifier) + + except Exception: + + raise MigrationRecoveryError( + "Migration recovery verification failed" + ) from None + + def _inspect(self, identifier): + + approval = self.store.load(identifier) + + context = approval["context"] + validate_context(context) + + intent = self.read_record( + self.store.path( + identifier, + ".migration-intent.json", + ) + ) + + consumed = self.read_record( + self.store.consumed_path(identifier) + ) + + result = self.read_record( + self.store.path( + identifier, + ".migration-result.json", + ) + ) + + require( + intent["status"] == "MIGRATION_INTENT" + and consumed["status"] == "CONSUMED" + and result["status"] == "MIGRATED", + "Successful migration evidence required", + ) + + for record in (intent, consumed, result): + + require( + record["approval_id"] == identifier + and record["site"] == self.site + and record["site"] == context["site"] + and record["release"] == context["release"] + and record["revision"] == context["revision"] + and record["database_identity"] + == context["database_identity"], + "Migration evidence identity mismatch", + ) + + require( + intent["approval_checksum"] == approval["checksum"] + and consumed["approval_checksum"] + == approval["checksum"] + and result["intent_checksum"] == intent["checksum"] + and result["consumption_checksum"] + == consumed["checksum"], + "Migration evidence chain mismatch", + ) + + require( + intent["context_fingerprint"] + == canonical_hash(context), + "Migration context fingerprint mismatch", + ) + + for field in ( + "backup_sha256", + "rehearsal_fingerprint", + ): + + require( + intent[field] == context[field] + and consumed[field] == context[field], + "Migration evidence context mismatch", + ) + + require( + result["automatic_database_rollback"] is False + and result["application_activated"] is False + and result["containment_required"] is True + and consumed["migration_executed"] is False, + "Unexpected migration state", + ) + + before = validate_history( + intent["history_before"] + ) + + pending = validate_history( + context["pending_migrations"] + ) + + require( + not set(before).intersection(pending) + and intent["pending_migrations"] == pending + and result["applied_migrations"] == pending + and result["history_after"] == before + pending, + "Migration history evidence mismatch", + ) + + require( + self.identity_probe() + == context["database_identity"], + "Database identity changed", + ) + + require( + validate_history( + self.history_probe() + ) == result["history_after"], + "Live migration history changed", + ) + + release = context["release"] + + evidence = self.provenance_probe(release) + + require( + isinstance(evidence, dict) + and evidence.get("revision") + == context["revision"] + and evidence.get("fingerprint") + == context["provenance"], + "Candidate provenance changed", + ) + + require( + self.backup_probe() is True, + "Backup integrity could not be verified", + ) + + current = self.current_probe() + + require( + isinstance(current, str) + and current.isascii() + and current.isdecimal() + and not current.startswith("0") + and len(current) <= 20, + "Invalid active release", + ) + + for path in ( + self.intent_path(identifier), + self.result_path(identifier), + ): + + require( + not os.path.lexists(path), + "Existing activation evidence requires inspection", + ) + + plan = { + "format_version": 1, + "status": "FORWARD_ACTIVATION_READY", + "site": self.site, + "approval_id": identifier, + "current": current, + "target": release, + "revision": context["revision"], + "provenance": context["provenance"], + "database_identity": context["database_identity"], + "backup_sha256": context["backup_sha256"], + "history_after": result["history_after"], + "migration_checksum": result["checksum"], + "approval_checksum": approval["checksum"], + "confirmation": "ACTIVATE-" + identifier, + "automatic_database_rollback": False, + "migration_reexecution_allowed": False, + } + + plan["plan_fingerprint"] = canonical_hash(plan) + + return plan + + def execute( + self, + identifier, + *, + confirmation, + fingerprint, + ): + + with DeploymentLock(self.lock_path): + + return self._execute( + identifier, + confirmation, + fingerprint, + ) + + def _execute( + self, + identifier, + confirmation, + fingerprint, + ): + + operation = "preflight" + intent = None + containment_started = False + + try: + + plan = self._inspect(identifier) + + require( + confirmation == plan["confirmation"] + and fingerprint == plan["plan_fingerprint"], + "Activation confirmation or fingerprint changed", + ) + + operation = "establish containment" + containment_started = True + + require( + self.contain() is True + and self.containment_probe() is True, + "Write containment failed", + ) + + operation = "revalidate recovery evidence" + + require( + self._inspect(identifier) == plan, + "Migration recovery plan changed", + ) + + operation = "persist activation intent" + + intent = self.publish( + self.intent_path(identifier), + { + "format_version": 1, + "status": "ACTIVATION_INTENT", + "approval_id": identifier, + "site": self.site, + "target": plan["target"], + "plan_fingerprint": fingerprint, + "migration_checksum": ( + plan["migration_checksum"] + ), + "created_at": datetime.now( + timezone.utc + ).isoformat(), + }, + ) + + operation = "activate migrated release" + + require( + self.containment_probe() is True, + "Containment lost before activation", + ) + + target = plan["target"] + + require( + self.activate(target) is True + and self.current_probe() == target, + "Candidate activation failed", + ) + + operation = "refresh application" + + require( + self.refresh() is True, + "Application refresh failed", + ) + + operation = "verify contained application" + + require( + self.readiness_probe() is True + and self.containment_probe() is True, + "Contained application is not ready", + ) + + require( + self.identity_probe() + == plan["database_identity"] + and validate_history( + self.history_probe() + ) == plan["history_after"], + "Database state changed during activation", + ) + + evidence = self.provenance_probe(target) + + require( + isinstance(evidence, dict) + and evidence.get("revision") + == plan["revision"] + and evidence.get("fingerprint") + == plan["provenance"] + and self.current_probe() == target, + "Candidate changed during activation", + ) + + operation = "release containment" + + require( + self.release_containment() is True + and self.writes_enabled_probe() is True, + "Application reopening failed", + ) + + operation = "verify application health" + + report = self.health_probe(target) + + require( + isinstance(report, dict) + and report.get("healthy") is True + and report.get("release") == target + and self.current_probe() == target, + "Application health verification failed", + ) + + operation = "persist activation result" + + return self.publish( + self.result_path(identifier), + { + "format_version": 1, + "status": "VERIFIED", + "approval_id": identifier, + "site": self.site, + "active_release": target, + "intent_checksum": intent["checksum"], + "plan_fingerprint": fingerprint, + "health_verified": True, + "database_restored": False, + "migration_reexecuted": False, + "completed_at": datetime.now( + timezone.utc + ).isoformat(), + }, + ) + + except Exception: + + containment_ok = None + + if containment_started: + + try: + + containment_ok = ( + self.contain() is True + and self.containment_probe() is True + ) + + except Exception: + + containment_ok = False + + if intent is not None: + + try: + + path = self.result_path(identifier) + + if not os.path.lexists(path): + + self.publish( + path, + { + "format_version": 1, + "status": "FAILED", + "approval_id": identifier, + "intent_checksum": intent["checksum"], + "operation": operation, + "containment_verified": containment_ok, + "manual_recovery_required": True, + }, + ) + + except Exception: + + pass + + raise MigrationRecoveryError( + f"Forward activation failed during {operation}; " + f"containment={containment_ok}; " + "explicit inspection required" + ) from None diff --git a/core/operation_guard.py b/core/operation_guard.py new file mode 100644 index 0000000..21274b7 --- /dev/null +++ b/core/operation_guard.py @@ -0,0 +1,100 @@ +"""Conservative unfinished-operation protection. + +The approval store must be dedicated to one site. +Callers must hold the shared deployment lock. +""" + +import re + +from core.migration_archive import ( + ARCHIVE_SUFFIX, + verify_archived_group, +) + + +class OperationBlocked(RuntimeError): + """Existing evidence prevents a new operation.""" + + +class OperationGuard: + + def __init__(self, store): + self.store = store + + def inspect(self): + blockers = [] + + try: + self.store.validate_directory() + + entries = list(self.store.directory.iterdir()) + + archived_names = set() + + for path in entries: + + name = path.name + + if ( + name.endswith(ARCHIVE_SUFFIX) + and re.fullmatch( + r"[a-f0-9]{32}", + name[:-len(ARCHIVE_SUFFIX)], + ) is not None + ): + + archived_names.update( + verify_archived_group( + self.store, + name[:32], + ) + ) + + for path in entries: + + name = path.name + + if name in archived_names: + continue + + if name == ".approval.lock": + continue + + if name == ".deployment.lock": + continue + + if re.fullmatch( + r"[a-f0-9]{32}\.approval\.json", + name, + ): + + # An unused approval is not an + # unfinished migration. + + self.store.load(name[:32]) + continue + + blockers.append(name) + + except Exception: + + raise OperationBlocked( + "Approval store cannot be safely inspected" + ) from None + + return { + "format_version": 1, + "status": "BLOCKED" if blockers else "CLEAR", + "blockers": sorted(blockers), + "automatic_cleanup": False, + } + + def require_clear(self): + report = self.inspect() + + if report["status"] != "CLEAR": + raise OperationBlocked( + "Unfinished migration evidence requires review" + ) + + return report diff --git a/core/preflight.py b/core/preflight.py new file mode 100644 index 0000000..882972a --- /dev/null +++ b/core/preflight.py @@ -0,0 +1,68 @@ +"""Static preflight for prospective site provisioning. + +No live infrastructure operations are permitted. +""" + +from core.configuration import validate_config +from core.site_policy import validate_site, validate_registry +from core.compatibility import canonical_hash + + +class PreflightError(RuntimeError): + """Site configuration or preflight is unsafe.""" + + +def site_preflight(config, existing_registry): + + if ( + not isinstance(existing_registry, list) + or len(existing_registry) > 9999 + ): + raise PreflightError("Invalid existing site registry") + + try: + candidate = validate_config(config) + + policy = validate_site(candidate) + + registry = validate_registry([ + *existing_registry, + candidate, + ]) + + except Exception: + + raise PreflightError( + "Static configuration or resource conflict" + ) from None + + report = { + "format_version": 1, + "status": "STATIC_PREFLIGHT_PASSED", + "site": candidate["site"]["identifier"], + "configuration_fingerprint": canonical_hash(candidate), + "policy_fingerprint": policy["fingerprint"], + "registry_fingerprint": registry["fingerprint"], + "site_count": registry["site_count"], + "static_policy_verified": True, + "registry_conflicts_checked": True, + "registry_completeness_verified": False, + "runtime_verified": False, + "execution_permitted": False, + "outstanding_runtime_checks": [ + "trusted_filesystem_paths", + "filesystem_ownership", + "live_port_availability", + "docker_project_identity", + "docker_network_isolation", + "database_server_identity", + "database_permissions", + "repository_authorisation", + "secret_availability", + "transaction_state_binding", + ], + } + + report["fingerprint"] = canonical_hash(report) + + return report diff --git a/core/provenance.py b/core/provenance.py new file mode 100644 index 0000000..0ee0ebf --- /dev/null +++ b/core/provenance.py @@ -0,0 +1,284 @@ +"""Git-backed verification of release-critical files.""" + +import hashlib +import json +import os +import re +import stat +import subprocess +from pathlib import Path + + +class ProvenanceError(RuntimeError): + """Release provenance could not be established.""" + + +DEPENDENCIES = ( + "composer.json", + "composer.lock", + "package.json", + "package-lock.json", +) + + +def require(condition, message): + + if not condition: + raise ProvenanceError(message) + + +def digest(data): + + return hashlib.sha256(data).hexdigest() + + +class ProvenanceVerifier: + + def __init__(self, repository): + + self.repository = Path(repository).absolute() + + require( + self.repository.is_dir() + and self.repository.resolve() == self.repository, + "Invalid Git repository path", + ) + + self.git("rev-parse", "--git-dir") + + def git(self, *args): + + try: + + # Prevent inherited Git environment variables + # from redirecting commands to another repository. + + environment = { + key: value + for key, value in os.environ.items() + if not key.startswith("GIT_") + } + + environment["GIT_TERMINAL_PROMPT"] = "0" + environment["GIT_NO_REPLACE_OBJECTS"] = "1" + + return subprocess.check_output( + [ + "git", + "-C", + str(self.repository), + *args, + ], + stdin=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=environment, + timeout=30, + ) + + except ( + OSError, + subprocess.SubprocessError, + ): + + raise ProvenanceError( + "Git provenance command failed" + ) from None + + def safe_file(self, root, relative): + + relative = Path(relative) + + require( + not relative.is_absolute() + and ".." not in relative.parts, + "Unsafe release file path", + ) + + path = root + + for part in relative.parts: + + path = path / part + + require( + not path.is_symlink(), + "Symbolic links prohibited in provenance files", + ) + + try: + + details = path.lstat() + + except OSError: + + raise ProvenanceError( + f"Missing release file: {relative}" + ) from None + + require( + stat.S_ISREG(details.st_mode), + f"Invalid release file: {relative}", + ) + + require( + path.resolve().is_relative_to(root), + "Release file escaped its directory", + ) + + return path + + def migration_inventory(self, root): + + directory = root / "database/migrations" + + require( + directory.is_dir() + and directory.resolve() == directory, + "Invalid migration directory", + ) + + result = [] + + for path in directory.rglob("*"): + + require( + not path.is_symlink(), + "Symbolic link in migration directory", + ) + + if path.suffix == ".php": + + require( + path.is_file(), + "Invalid migration file", + ) + + result.append( + path.relative_to(root).as_posix() + ) + + return sorted(result) + + def verify(self, release): + + root = Path(release).absolute() + + require( + root.is_dir() + and root.resolve() == root, + "Invalid release directory", + ) + + revision = self.safe_file( + root, "REVISION" + ).read_text().strip() + + require( + re.fullmatch( + r"[a-f0-9]{40}", revision + ) is not None, + "Invalid release revision", + ) + + require( + self.git( + "cat-file", + "-t", + revision, + ).strip() == b"commit", + "Release revision is not a Git commit", + ) + + raw = self.git( + "ls-tree", + "-r", + "-z", + revision, + ) + + entries = {} + + for entry in raw.split(b"\x00"): + + if not entry: + continue + + metadata, name = entry.split(b"\t", 1) + + mode, kind, object_id = metadata.decode().split() + + name = name.decode("utf-8") + + entries[name] = { + "mode": mode, + "kind": kind, + "object_id": object_id, + } + + migrations = sorted( + name for name in entries + if name.startswith("database/migrations/") + and name.endswith(".php") + ) + + require( + self.migration_inventory(root) == migrations, + "Migration inventory differs from Git revision", + ) + + verified = {} + + for name in (*migrations, *DEPENDENCIES): + + require( + name in entries, + f"File missing from Git revision: {name}", + ) + + entry = entries[name] + + require( + entry["kind"] == "blob" + and entry["mode"] in ("100644", "100755"), + f"Unsafe Git file type: {name}", + ) + + expected = self.git( + "cat-file", + "blob", + entry["object_id"], + ) + + path = self.safe_file(root, name) + + actual = path.read_bytes() + + require( + digest(actual) == digest(expected), + f"Release file differs from Git revision: {name}", + ) + + verified[name] = digest(actual) + + result = { + "format_version": 1, + "revision": revision, + "migrations": { + name: verified[name] + for name in migrations + }, + "dependencies": { + name: verified[name] + for name in DEPENDENCIES + }, + } + + canonical = json.dumps( + result, + sort_keys=True, + separators=(",", ":"), + ).encode() + + result["fingerprint"] = digest(canonical) + + return result diff --git a/core/recovery.py b/core/recovery.py new file mode 100644 index 0000000..d41daec --- /dev/null +++ b/core/recovery.py @@ -0,0 +1,242 @@ +"""Conservative read-only deployment recovery planning.""" + +from pathlib import Path + +from core.backup_evidence import FIELDS +from core.compatibility import ( + canonical_hash, + require_compatible, + validate_provenance, +) +from core.locking import DeploymentLock + + +class RecoveryError(RuntimeError): + """Recovery safety could not be established.""" + + +def require(condition, message): + + if not condition: + raise RecoveryError(message) + + +class RecoveryPlanner: + + def __init__( + self, + *, + site, + lock_path, + releases, + provenance, + journal, + backup_evidence, + backup_verify, + runtime_check, + ): + + self.site = site + self.lock_path = Path(lock_path) + self.releases = releases + self.provenance = provenance + self.journal = journal + self.backup_evidence = backup_evidence + self.backup_verify = backup_verify + self.runtime_check = runtime_check + + def inspect(self): + + with DeploymentLock(self.lock_path): + + try: + + return self._inspect() + + except RecoveryError: + raise + + except Exception: + + raise RecoveryError( + "Recovery verification failed" + ) from None + + def _inspect(self): + + transaction = self.journal.load() + + result = { + "format_version": 1, + "site": self.site, + "automatic_rollback_allowed": False, + "database_restore_allowed": False, + "execution_permitted": False, + } + + if transaction is None: + + result["status"] = "CLEAR" + + return result + + require( + transaction["site"] == self.site, + "Transaction belongs to another site", + ) + + current = self.releases.current() + + previous = transaction["previous"] + candidate = transaction["candidate"] + + require( + current in (previous, candidate), + "Unexpected active release", + ) + + result.update({ + "transaction_id": transaction["transaction_id"], + "transaction_checksum": transaction["checksum"], + "phase": transaction["phase"], + "current": current, + "previous": previous, + "candidate": candidate, + "target": None, + "confirmation": None, + }) + + if transaction["phase"] == "VERIFIED": + + require( + current == candidate, + "Verified transaction has inconsistent active release", + ) + + result["status"] = "VERIFIED" + + return result + + if current == previous: + + result["status"] = ( + "PREVIOUS_ACTIVE_REVIEW_REQUIRED" + ) + + return result + + history = { + event["phase"] + for event in transaction["history"] + } + + require( + { + "BACKED_UP", + "QUIESCED", + "ACTIVATING", + } <= history, + "Activation evidence is incomplete", + ) + + require( + transaction["phase"] in ( + "ACTIVATING", + "ACTIVATED", + "FAILED", + ), + "Transaction phase does not permit rollback review", + ) + + old = self.provenance.verify( + self.releases.validate(previous) + ) + + new = self.provenance.verify( + self.releases.validate(candidate) + ) + + validate_provenance(old) + validate_provenance(new) + + require( + new["revision"] == transaction["revision"] + and new["fingerprint"] == transaction["provenance"], + "Candidate provenance differs from transaction", + ) + + require( + transaction["previous_revision"] is not None + and transaction["previous_provenance"] is not None + and old["revision"] + == transaction["previous_revision"] + and old["fingerprint"] + == transaction["previous_provenance"], + "Previous release provenance differs from transaction", + ) + + compatibility = require_compatible( + new, + old, + ) + + evidence = self.backup_evidence.load( + transaction["transaction_id"] + ) + + recorded = evidence["backup"] + + manifest = self.backup_verify( + recorded["backup_id"] + ) + + require( + isinstance(manifest, dict) + and FIELDS <= set(manifest), + "Invalid verified backup manifest", + ) + + verified = { + field: manifest[field] + for field in FIELDS + } + + require( + verified == recorded, + "Verified backup differs from transaction evidence", + ) + + require( + self.runtime_check() is True, + "Database runtime verification failed", + ) + + require( + self.releases.current() == current, + "Active release changed during inspection", + ) + + require( + self.journal.load() == transaction, + "Transaction changed during inspection", + ) + + result.update({ + "status": "ROLLBACK_REVIEW_READY", + "target": previous, + "backup_id": recorded["backup_id"], + "backup_sha256": recorded["sha256"], + "backup_evidence_checksum": evidence["checksum"], + "previous_provenance": old["fingerprint"], + "candidate_provenance": new["fingerprint"], + "compatibility_fingerprint": ( + compatibility["fingerprint"] + ), + "confirmation": ( + "ROLLBACK-" + transaction["transaction_id"] + ), + }) + + result["plan_fingerprint"] = canonical_hash(result) + + return result diff --git a/core/rehearsal.py b/core/rehearsal.py new file mode 100644 index 0000000..321bdfd --- /dev/null +++ b/core/rehearsal.py @@ -0,0 +1,304 @@ +"""Migration rehearsal evidence validation. + +This module does not create databases, restore backups +or execute migrations. It validates supplied evidence. +""" + +import copy +import re +import uuid + +from datetime import timedelta + +from core.approval import ( + ApprovalError, + CONTEXT_FIELDS, + validate_context, + timestamp, + parse_timestamp, +) + +from core.compatibility import canonical_hash + + +class RehearsalError(RuntimeError): + """Invalid or insufficient migration rehearsal evidence.""" + + +BASE_FIELDS = CONTEXT_FIELDS - { + "rehearsal_fingerprint", +} + +EXECUTION_FIELDS = { + "driver", + "source_database", + "target_database", + "target_identity", + "applied_migrations", + "checks", +} + +CHECK_FIELDS = { + "isolation_verified", + "backup_restored", + "migration_succeeded", + "migration_history_verified", + "application_verified", + "cleanup_verified", +} + +RECORD_FIELDS = { + "format_version", + "rehearsal_id", + "context", + "execution", + "completed_at", + "fingerprint", +} + + +def require(condition, message): + + if not condition: + raise RehearsalError(message) + + +def matches(value, pattern): + + return ( + isinstance(value, str) + and re.fullmatch(pattern, value) is not None + ) + + +def validate_base_context(context): + + require( + isinstance(context, dict) + and set(context) == BASE_FIELDS, + "Invalid rehearsal context", + ) + + try: + + validate_context({ + **context, + "rehearsal_fingerprint": "0" * 64, + }) + + except ApprovalError: + + raise RehearsalError( + "Invalid rehearsal approval context" + ) from None + + +def validate_execution(context, execution): + + require( + isinstance(execution, dict) + and set(execution) == EXECUTION_FIELDS, + "Invalid rehearsal execution evidence", + ) + + require( + execution["driver"] in ( + "mysql", + "postgresql", + ), + "Unsupported rehearsal database driver", + ) + + source = execution["source_database"] + target = execution["target_database"] + + require( + matches(source, r"[A-Za-z_][A-Za-z0-9_]{0,62}"), + "Invalid source database", + ) + + require( + matches( + target, + r"isolated_restore_[a-z0-9_]{1,45}", + ), + "Invalid isolated database name", + ) + + require( + source.lower() != target.lower(), + "Rehearsal must not target the source database", + ) + + require( + matches( + execution["target_identity"], + r"[a-f0-9]{64}", + ), + "Invalid rehearsal database identity", + ) + + require( + execution["target_identity"] + != context["database_identity"], + "Rehearsal database identity matches source", + ) + + require( + isinstance(execution["applied_migrations"], list) + and execution["applied_migrations"] + == context["pending_migrations"], + "Applied migrations differ from approved inventory", + ) + + checks = execution["checks"] + + require( + isinstance(checks, dict) + and set(checks) == CHECK_FIELDS, + "Incomplete rehearsal verification checks", + ) + + for name, status in checks.items(): + + require( + status is True, + f"Rehearsal check failed: {name}", + ) + + +def fingerprint(record): + + return canonical_hash({ + key: value + for key, value in record.items() + if key != "fingerprint" + }) + + +def create_rehearsal( + context, + execution, + *, + completed_at, +): + + validate_base_context(context) + + validate_execution( + context, + execution, + ) + + try: + + completed = timestamp(completed_at) + + except ApprovalError: + + raise RehearsalError( + "Invalid rehearsal completion timestamp" + ) from None + + record = { + "format_version": 1, + "rehearsal_id": uuid.uuid4().hex, + "context": copy.deepcopy(context), + "execution": copy.deepcopy(execution), + "completed_at": completed.isoformat(), + } + + record["fingerprint"] = fingerprint(record) + + return record + + +def verify_rehearsal( + record, + context, + *, + now, +): + + validate_base_context(context) + + require( + isinstance(record, dict) + and set(record) == RECORD_FIELDS, + "Invalid rehearsal record", + ) + + require( + type(record["format_version"]) is int + and record["format_version"] == 1, + "Unsupported rehearsal format", + ) + + require( + matches( + record["rehearsal_id"], + r"[a-f0-9]{32}", + ), + "Invalid rehearsal identifier", + ) + + validate_base_context(record["context"]) + + require( + record["context"] == context, + "Rehearsal context changed", + ) + + validate_execution( + context, + record["execution"], + ) + + require( + matches( + record["fingerprint"], + r"[a-f0-9]{64}", + ) + and fingerprint(record) == record["fingerprint"], + "Rehearsal fingerprint mismatch", + ) + + try: + + completed = parse_timestamp( + record["completed_at"] + ) + + current = timestamp(now) + + except ApprovalError: + + raise RehearsalError( + "Invalid rehearsal timestamp" + ) from None + + require( + timedelta(0) + <= current - completed + < timedelta(hours=24), + "Rehearsal expired or not yet valid", + ) + + return True + + +def approval_context(record, context, *, now): + + verify_rehearsal( + record, + context, + now=now, + ) + + result = copy.deepcopy(context) + + result["rehearsal_fingerprint"] = ( + record["fingerprint"] + ) + + return result diff --git a/core/releases.py b/core/releases.py new file mode 100644 index 0000000..1c55b21 --- /dev/null +++ b/core/releases.py @@ -0,0 +1,231 @@ +"""Filesystem release management without service side effects.""" + +import json +import os +import re +import stat +import uuid +from pathlib import Path + + +class ReleaseError(RuntimeError): + """Invalid or unsafe release operation.""" + + +def require(condition, message): + + if not condition: + raise ReleaseError(message) + + +def valid_number(value): + + return ( + isinstance(value, str) + and re.fullmatch( + r"[1-9][0-9]*", value + ) is not None + ) + + +def exists(path): + return path.exists() or path.is_symlink() + + +def regular_file(path): + + try: + details = path.lstat() + return stat.S_ISREG(details.st_mode) + + except OSError: + return False + + +class ReleaseManager: + + def __init__(self, app): + + self.app = Path(app).absolute() + self.releases = self.app / "releases" + + self.validate_layout() + + def validate_layout(self): + + for path in (self.app, self.releases): + + require( + path.is_dir() + and not path.is_symlink(), + "Invalid application directory layout", + ) + + def inventory(self): + + self.validate_layout() + + result = [] + + for path in self.releases.iterdir(): + + require( + valid_number(path.name) + and path.is_dir() + and not path.is_symlink(), + "Unexpected release inventory entry", + ) + + result.append(path.name) + + return sorted(result, key=int) + + def release_path(self, release): + + require( + valid_number(release), + "Invalid release identifier", + ) + + self.validate_layout() + + root = self.releases / release + + require( + root.is_dir() + and not root.is_symlink(), + "Release does not exist", + ) + + return root + + def validate(self, release): + + root = self.release_path(release) + + require( + not exists(root / "BAD_RELEASE"), + "Release marked as rejected", + ) + + required = ( + "vendor/autoload.php", + "public/build/manifest.json", + "REVISION", + ) + + for relative in required: + + path = root / relative + + require( + regular_file(path) + and path.resolve().is_relative_to( + root.resolve() + ), + f"Missing or unsafe release file: {relative}", + ) + + revision = ( + root / "REVISION" + ).read_text().strip() + + require( + re.fullmatch( + r"[a-f0-9]{40}", revision + ) is not None, + "Invalid Git revision", + ) + + try: + + manifest = json.loads( + (root / "public/build/manifest.json") + .read_text() + ) + + except (ValueError, OSError) as error: + + raise ReleaseError( + "Invalid frontend manifest" + ) from error + + require( + isinstance(manifest, dict), + "Invalid frontend manifest structure", + ) + + return root + + def current(self): + + self.validate_layout() + + link = self.app / "current" + + if not exists(link): + return None + + require( + link.is_symlink(), + "Current release must be a symbolic link", + ) + + match = re.fullmatch( + r"releases/([1-9][0-9]*)", + os.readlink(link), + ) + + require( + match is not None, + "Invalid current release target", + ) + + release = match.group(1) + + self.release_path(release) + + return release + + def activate(self, release): + + self.current() + self.validate(release) + + link = self.app / "current" + + temporary = self.app / ( + ".activation-" + uuid.uuid4().hex + ) + + try: + + temporary.symlink_to( + f"releases/{release}" + ) + + os.replace(temporary, link) + + fd = os.open( + self.app, + os.O_RDONLY + | os.O_DIRECTORY + | os.O_NOFOLLOW, + ) + + try: + os.fsync(fd) + finally: + os.close(fd) + + finally: + + if temporary.is_symlink(): + temporary.unlink() + + require( + self.current() == release, + "Activation verification failed", + ) + + return release diff --git a/core/retention.py b/core/retention.py new file mode 100644 index 0000000..7924a5a --- /dev/null +++ b/core/retention.py @@ -0,0 +1,191 @@ +"""Read-only release retention planning. + +The caller must supply a complete and trustworthy +inventory of releases and transaction protections. + +No filesystem modification is performed. +""" + +import re + +from core.compatibility import canonical_hash + + +class RetentionError(RuntimeError): + """Invalid or unsafe release retention policy.""" + + +FIELDS = { + "inventory", + "current", + "keep", + "protected", + "failed", + "unresolved", +} + + +def require(condition, message): + if not condition: + raise RetentionError(message) + + +def validate_release(value): + require( + isinstance(value, str) + and re.fullmatch( + r"[1-9][0-9]{0,19}", + value, + ) is not None, + "Invalid release identifier", + ) + + +def validate_inventory(values): + require( + isinstance(values, list) + and len(values) <= 100000, + "Invalid release inventory", + ) + + for value in values: + validate_release(value) + + require( + len(values) == len(set(values)), + "Duplicate release identifiers", + ) + + return sorted(values, key=int) + + +def plan_retention(policy): + require( + isinstance(policy, dict) + and set(policy) == FIELDS, + "Invalid retention policy structure", + ) + + inventory = validate_inventory( + policy["inventory"] + ) + + require( + bool(inventory), + "Release inventory is empty", + ) + + current = policy["current"] + + validate_release(current) + + available = set(inventory) + + require( + current in available, + "Active release missing from inventory", + ) + + keep = policy["keep"] + + require( + type(keep) is int + and 2 <= keep <= 1000, + "Retention count must be between 2 and 1000", + ) + + protections = {} + + for field in ( + "protected", + "failed", + "unresolved", + ): + values = validate_inventory( + policy[field] + ) + + require( + set(values) <= available, + f"Unknown release in {field} inventory", + ) + + protections[field] = values + + failed = set(protections["failed"]) + + require( + current not in failed, + "Active release is marked failed", + ) + + reasons = {} + + def protect(release, reason): + reasons.setdefault(release, set()).add(reason) + + protect(current, "active") + + for release in inventory[-keep:]: + protect(release, "recent_release") + + for release in protections["protected"]: + protect(release, "explicitly_protected") + + for release in protections["failed"]: + protect(release, "failed_release") + + for release in protections["unresolved"]: + protect(release, "unresolved_transaction") + + previous = [ + release + for release in inventory + if int(release) < int(current) + and release not in failed + ] + + if previous: + protect(previous[-1], "previous_available") + + blocked = bool(protections["unresolved"]) + + if blocked: + for release in inventory: + protect(release, "operation_unresolved") + + retained = [ + release + for release in inventory + if release in reasons + ] + + candidates = [ + release + for release in inventory + if release not in reasons + ] + + plan = { + "format_version": 1, + "status": "BLOCKED" if blocked else "READY", + "current": current, + "keep": keep, + "inventory": inventory, + "protected": protections["protected"], + "failed": protections["failed"], + "unresolved": protections["unresolved"], + "retained": retained, + "archive_candidates": candidates, + "reasons": { + release: sorted(reasons[release]) + for release in retained + }, + "automatic_archival": False, + "automatic_deletion": False, + "execution_permitted": False, + } + + plan["fingerprint"] = canonical_hash(plan) + + return plan diff --git a/core/rollback.py b/core/rollback.py new file mode 100644 index 0000000..be10514 --- /dev/null +++ b/core/rollback.py @@ -0,0 +1,377 @@ +"""Explicit application rollback with persistent intent. + +Database restoration is intentionally unsupported. +External operations must use trusted service adapters. +""" + +import json +import os +import re +import stat +import uuid + +from datetime import datetime, timezone + +from core.compatibility import canonical_hash +from core.locking import DeploymentLock + + +class RollbackError(RuntimeError): + """Rollback failed or requires explicit inspection.""" + + +def require(condition, message): + + if not condition: + raise RollbackError(message) + + +def now(): + + return datetime.now(timezone.utc).isoformat() + + +class RollbackExecutor: + + def __init__( + self, + *, + planner, + services, + health, + stopped_check, + ): + + require( + callable(stopped_check), + "Worker state verification is required", + ) + + self.planner = planner + self.services = services + self.health = health + self.stopped_check = stopped_check + + self.directory = planner.journal.directory + + self.validate_directory() + + def validate_directory(self): + + directory = self.directory + + require( + directory.is_dir() + and not directory.is_symlink() + and directory.resolve() == directory, + "Invalid rollback evidence directory", + ) + + details = directory.stat() + + require( + details.st_uid == os.getuid() + and stat.S_IMODE(details.st_mode) == 0o700, + "Unsafe rollback evidence directory permissions", + ) + + def evidence_path(self, transaction_id, suffix): + + require( + isinstance(transaction_id, str) + and re.fullmatch( + r"[a-f0-9]{32}", + transaction_id, + ) is not None, + "Invalid rollback transaction identifier", + ) + + return self.directory / ( + transaction_id + suffix + ) + + def intent_path(self, transaction_id): + + return self.evidence_path( + transaction_id, + ".rollback-intent.json", + ) + + def result_path(self, transaction_id): + + return self.evidence_path( + transaction_id, + ".rollback-result.json", + ) + + def publish(self, path, data): + + self.validate_directory() + + require( + path.parent == self.directory, + "Invalid rollback evidence path", + ) + + data = dict(data) + + data["checksum"] = canonical_hash(data) + + temporary = self.directory / ( + ".rollback-" + uuid.uuid4().hex + ) + + fd = None + created = False + + try: + + fd = os.open( + temporary, + os.O_WRONLY + | os.O_CREAT + | os.O_EXCL + | os.O_NOFOLLOW + | os.O_CLOEXEC, + 0o600, + ) + + created = True + + with os.fdopen(fd, "w") as handle: + + fd = None + + json.dump( + data, + handle, + sort_keys=True, + indent=2, + allow_nan=False, + ) + + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + + os.link( + temporary, + path, + follow_symlinks=False, + ) + + temporary.unlink() + created = False + + directory_fd = os.open( + self.directory, + os.O_RDONLY + | os.O_DIRECTORY + | os.O_NOFOLLOW, + ) + + try: + os.fsync(directory_fd) + finally: + os.close(directory_fd) + + require( + json.loads(path.read_text()) == data, + "Rollback evidence readback failed", + ) + + return data + + except OSError: + + raise RollbackError( + "Rollback evidence persistence failed" + ) from None + + finally: + + if fd is not None: + os.close(fd) + + if created: + temporary.unlink(missing_ok=True) + + def execute(self, confirmation, fingerprint): + + with DeploymentLock(self.planner.lock_path): + + return self._execute( + confirmation, + fingerprint, + ) + + def _execute(self, confirmation, fingerprint): + + operation = "preflight" + quiesce_started = False + intent = None + result_path = None + + try: + + # The deployment lock is already held. + # Do not call inspect(), which reacquires it. + + plan = self.planner._inspect() + + require( + plan["status"] == "ROLLBACK_REVIEW_READY", + "Transaction is not eligible for rollback", + ) + + require( + isinstance(confirmation, str) + and confirmation == plan["confirmation"], + "Rollback confirmation mismatch", + ) + + require( + isinstance(fingerprint, str) + and fingerprint == plan["plan_fingerprint"], + "Rollback plan changed", + ) + + transaction_id = plan["transaction_id"] + + intent_path = self.intent_path(transaction_id) + result_path = self.result_path(transaction_id) + + for path in (intent_path, result_path): + + require( + not os.path.lexists(path), + "Existing rollback evidence requires review", + ) + + operation = "persist rollback intent" + + intent = self.publish( + intent_path, + { + "format_version": 1, + "status": "ROLLBACK_INTENT", + "transaction_id": transaction_id, + "site": plan["site"], + "source": plan["current"], + "target": plan["target"], + "transaction_checksum": ( + plan["transaction_checksum"] + ), + "plan_fingerprint": fingerprint, + "backup_id": plan["backup_id"], + "backup_sha256": plan["backup_sha256"], + "created_at": now(), + }, + ) + + operation = "quiesce workers" + + quiesce_started = True + + self.services.quiesce() + + require( + self.stopped_check() is True, + "Background workers remain active", + ) + + operation = "revalidate recovery plan" + + require( + self.planner._inspect() == plan, + "Recovery evidence changed after shutdown", + ) + + operation = "activate previous release" + + target = plan["target"] + + self.planner.releases.activate(target) + + require( + self.planner.releases.current() == target, + "Rollback activation verification failed", + ) + + operation = "refresh application" + + self.services.refresh() + + operation = "restore workers" + + self.services.resume() + + operation = "verify application health" + + health = self.health.verify(target) + + require( + isinstance(health, dict) + and health.get("healthy") is True + and health.get("release") == target, + "Rollback health verification failed", + ) + + require( + self.planner.releases.current() == target, + "Active release changed during rollback", + ) + + require( + self.planner.journal.load()["checksum"] + == plan["transaction_checksum"], + "Original transaction changed", + ) + + operation = "persist rollback result" + + return self.publish( + result_path, + { + "format_version": 1, + "status": "ROLLED_BACK", + "site": plan["site"], + "transaction_id": transaction_id, + "intent_checksum": intent["checksum"], + "plan_fingerprint": fingerprint, + "previous_active_release": ( + plan["current"] + ), + "active_release": target, + "health_verified": True, + "database_restored": False, + "completed_at": now(), + }, + ) + + except Exception: + + containment = None + + if quiesce_started: + + try: + + self.services.quiesce() + + containment = ( + self.stopped_check() is True + ) + + except Exception: + + containment = False + + # Preserve the original transaction and intent. + # Never automatically activate another release. + + raise RollbackError( + f"Rollback failed during {operation}; " + f"workers_contained={containment}; " + "explicit inspection required" + ) from None diff --git a/core/rollback_archive.py b/core/rollback_archive.py new file mode 100644 index 0000000..ca18343 --- /dev/null +++ b/core/rollback_archive.py @@ -0,0 +1,457 @@ +"""Archival of successfully rolled-back transactions. + +Preserve original evidence and quarantine failed candidates. +Never restore databases or automatically repeat a rollback. +""" + +import os +import re + +from datetime import datetime, timezone + +from core.approval_store import ApprovalStore +from core.archive import ArchiveError, require, digest, sync_directory +from core.backup_evidence import FIELDS +from core.compatibility import ( + canonical_hash, + require_compatible, + validate_provenance, +) +from core.locking import DeploymentLock + + +class RollbackArchive: + + def __init__(self, *, planner, directory, health_probe): + require( + callable(health_probe), + "Health verification is required", + ) + + self.planner = planner + self.journal = planner.journal + self.releases = planner.releases + self.health_probe = health_probe + + self.source = ApprovalStore(self.journal.directory) + self.destination = ApprovalStore(directory) + + require( + self.source.directory != self.destination.directory, + "Archive directory must be separate", + ) + + def path(self, identifier): + return self.destination.path( + identifier, + ".rollback-archive.json", + ) + + def read_record(self, suffix, identifier): + record = self.source.read( + self.source.path(identifier, suffix) + ) + + require( + isinstance(record, dict) + and type(record.get("format_version")) is int + and record["format_version"] == 1 + and record.get("checksum") == digest(record), + "Invalid rollback evidence", + ) + + return record + + def read_chain(self, transaction): + identifier = transaction["transaction_id"] + + intent = self.read_record( + ".rollback-intent.json", + identifier, + ) + + result = self.read_record( + ".rollback-result.json", + identifier, + ) + + require( + transaction["phase"] == "FAILED" + and intent["status"] == "ROLLBACK_INTENT" + and result["status"] == "ROLLED_BACK", + "Completed failed-transaction rollback required", + ) + + phases = { + event["phase"] + for event in transaction["history"] + } + + require( + {"BACKED_UP", "QUIESCED", "ACTIVATING"} <= phases, + "Incomplete deployment transaction history", + ) + + for record in (intent, result): + require( + record["transaction_id"] == identifier + and record["site"] == transaction["site"], + "Rollback identity mismatch", + ) + + require( + intent["transaction_checksum"] + == transaction["checksum"] + and result["intent_checksum"] + == intent["checksum"] + and result["plan_fingerprint"] + == intent["plan_fingerprint"], + "Rollback evidence chain mismatch", + ) + + require( + isinstance(intent["plan_fingerprint"], str) + and re.fullmatch( + r"[a-f0-9]{64}", + intent["plan_fingerprint"], + ) is not None, + "Invalid rollback plan fingerprint", + ) + + require( + intent["source"] == transaction["candidate"] + and intent["target"] == transaction["previous"] + and result["previous_active_release"] + == transaction["candidate"] + and result["active_release"] + == transaction["previous"] + and result["health_verified"] is True + and result["database_restored"] is False, + "Rollback result mismatch", + ) + + evidence = self.planner.backup_evidence.load( + identifier + ) + + require( + evidence["backup"]["backup_id"] + == intent["backup_id"] + and evidence["backup"]["sha256"] + == intent["backup_sha256"], + "Rollback backup evidence mismatch", + ) + + return intent, result, evidence + + def load(self, identifier): + try: + record = self.destination.read( + self.path(identifier) + ) + + require( + isinstance(record, dict) + and record.get("status") == "ARCHIVED" + and record.get("site") == self.planner.site + and record.get("database_restored") is False + and record.get("checksum") == digest(record), + "Invalid rollback archive", + ) + + transaction = record["transaction"] + + self.journal.validate(transaction) + + require( + transaction["transaction_id"] == identifier + and transaction["site"] == self.planner.site, + "Archived transaction identity mismatch", + ) + + intent, result, evidence = self.read_chain( + transaction + ) + + require( + record["rollback_intent"] == intent + and record["rollback_result"] == result + and record["backup_evidence"] == evidence, + "Archived evidence mismatch", + ) + + return record + + except ArchiveError: + raise + + except Exception: + raise ArchiveError( + "Rollback archive validation failed" + ) from None + + def _plan(self): + self.destination.validate_directory() + + transaction = self.journal.load() + + require( + transaction is not None + and transaction["phase"] == "FAILED" + and transaction["site"] == self.planner.site, + "Failed deployment transaction required", + ) + + identifier = transaction["transaction_id"] + + require( + not os.path.lexists(self.path(identifier)), + "Existing archive requires inspection", + ) + + intent, result, evidence = self.read_chain( + transaction + ) + + previous = transaction["previous"] + candidate = transaction["candidate"] + + require( + self.releases.current() == previous, + "Previous release is not active", + ) + + old = self.planner.provenance.verify( + self.releases.validate(previous) + ) + + new = self.planner.provenance.verify( + self.releases.validate(candidate) + ) + + validate_provenance(old) + validate_provenance(new) + + require( + old["revision"] == transaction["previous_revision"] + and old["fingerprint"] + == transaction["previous_provenance"] + and new["revision"] == transaction["revision"] + and new["fingerprint"] == transaction["provenance"], + "Release provenance changed", + ) + + require_compatible(new, old) + + backup = evidence["backup"] + + manifest = self.planner.backup_verify( + backup["backup_id"] + ) + + require( + isinstance(manifest, dict) + and FIELDS <= set(manifest) + and { + field: manifest[field] + for field in FIELDS + } == backup, + "Backup verification failed", + ) + + require( + self.planner.runtime_check() is True, + "Database runtime verification failed", + ) + + health = self.health_probe(previous) + + require( + isinstance(health, dict) + and health.get("healthy") is True + and health.get("release") == previous, + "Rolled-back application is unhealthy", + ) + + marker = ( + self.releases.release_path(candidate) + / "BAD_RELEASE" + ) + + require( + not os.path.lexists(marker), + "Existing failed-release marker requires review", + ) + + require( + self.journal.load() == transaction + and self.releases.current() == previous + and self.read_chain(transaction) + == (intent, result, evidence), + "Rollback state changed", + ) + + plan = { + "format_version": 1, + "status": "ARCHIVE_READY", + "site": transaction["site"], + "transaction_id": identifier, + "transaction_checksum": transaction["checksum"], + "intent_checksum": intent["checksum"], + "result_checksum": result["checksum"], + "backup_evidence_checksum": evidence["checksum"], + "active_release": previous, + "failed_release": candidate, + "confirmation": "ARCHIVE-ROLLBACK-" + identifier, + } + + plan["fingerprint"] = canonical_hash(plan) + + return plan + + def plan(self): + with DeploymentLock(self.planner.lock_path): + try: + return self._plan() + + except ArchiveError: + raise + + except Exception: + raise ArchiveError( + "Rollback archival preflight failed" + ) from None + + def execute(self, *, confirmation, fingerprint): + with DeploymentLock(self.planner.lock_path): + with DeploymentLock(self.journal.lock_path): + try: + return self._execute( + confirmation, + fingerprint, + ) + + except ArchiveError: + raise + + except Exception: + raise ArchiveError( + "Rollback archival interrupted; " + "inspect preserved evidence" + ) from None + + def _execute(self, confirmation, fingerprint): + plan = self._plan() + + require( + confirmation == plan["confirmation"] + and fingerprint == plan["fingerprint"], + "Rollback archival confirmation mismatch", + ) + + transaction = self.journal.load() + identifier = plan["transaction_id"] + + require( + transaction["checksum"] + == plan["transaction_checksum"], + "Transaction changed", + ) + + intent, result, evidence = self.read_chain( + transaction + ) + + require( + intent["checksum"] == plan["intent_checksum"] + and result["checksum"] == plan["result_checksum"] + and evidence["checksum"] + == plan["backup_evidence_checksum"], + "Rollback evidence changed", + ) + + record = { + "format_version": 1, + "status": "ARCHIVED", + "site": plan["site"], + "transaction": transaction, + "rollback_intent": intent, + "rollback_result": result, + "backup_evidence": evidence, + "plan_fingerprint": fingerprint, + "database_restored": False, + "archived_at": datetime.now( + timezone.utc + ).isoformat(), + } + + record["checksum"] = digest(record) + + # Preserve all transaction evidence before modifying + # the failed release or retiring the active journal. + + self.destination.publish( + self.path(identifier), + record, + ) + + require( + self.load(identifier) == record, + "Archive readback failed", + ) + + require( + self.releases.current() + == plan["active_release"] + and self.journal.load() == transaction + and self.planner.runtime_check() is True, + "Runtime state changed before retirement", + ) + + candidate = self.releases.validate( + plan["failed_release"] + ) + + marker = candidate / "BAD_RELEASE" + + fd = os.open( + marker, + os.O_WRONLY + | os.O_CREAT + | os.O_EXCL + | os.O_NOFOLLOW + | os.O_CLOEXEC, + 0o600, + ) + + with os.fdopen(fd, "w") as handle: + handle.write( + identifier + "\n" + + record["checksum"] + "\n" + ) + + handle.flush() + os.fsync(handle.fileno()) + + sync_directory(candidate) + + require( + self.releases.current() + == plan["active_release"] + and self.journal.load() == transaction, + "Deployment state changed during retirement", + ) + + # Only retire the journal once the durable archive + # and failed-release marker are present. + + self.journal.path.unlink() + + sync_directory(self.journal.directory) + + require( + self.journal.load() is None, + "Journal retirement failed", + ) + + return record diff --git a/core/services.py b/core/services.py new file mode 100644 index 0000000..57b93db --- /dev/null +++ b/core/services.py @@ -0,0 +1,182 @@ +"""Controlled Docker Compose application lifecycle. + +The command runner must be supplied by the caller. +This module does not execute subprocesses directly. +""" + +from pathlib import PurePosixPath + +from core.configuration import ( + ConfigurationError, + validate_config, +) + + +class ServiceError(RuntimeError): + """Application service lifecycle operation failed.""" + + +def require(condition, message): + + if not condition: + raise ServiceError(message) + + +class ServiceLifecycle: + + def __init__( + self, + config, + runner, + stop_timeout=90, + ): + + require( + callable(runner), + "A command runner is required", + ) + + require( + type(stop_timeout) is int + and 1 <= stop_timeout <= 300, + "Invalid graceful shutdown timeout", + ) + + try: + + validated = validate_config(config) + + except ConfigurationError: + + raise ServiceError( + "Invalid service configuration" + ) from None + + docker = validated["docker"] + + root = PurePosixPath( + validated["site"]["root"] + ) + + self._prefix = ( + "docker", + "compose", + "--project-name", + docker["project"], + "--project-directory", + str(root), + "--file", + str(root / "compose.yaml"), + ) + + self._php = docker["php_service"] + self._web = docker["web_service"] + self._queue = docker["queue_service"] + self._scheduler = docker["scheduler_service"] + + self._runner = runner + self._stop_timeout = stop_timeout + + def _execute(self, operation, args, timeout): + + command = ( + *self._prefix, + *args, + ) + + try: + + result = self._runner( + command, + timeout=timeout, + ) + + except Exception: + + raise ServiceError( + f"Service operation failed: {operation}" + ) from None + + require( + type(result) is int and result == 0, + f"Service operation failed: {operation}", + ) + + def quiesce(self): + + self._execute( + "quiesce workers", + ( + "stop", + "--timeout", + str(self._stop_timeout), + self._queue, + self._scheduler, + ), + timeout=self._stop_timeout + 30, + ) + + def restart_php(self): + + self._execute( + "restart PHP", + ( + "restart", + "--timeout", + str(self._stop_timeout), + self._php, + ), + timeout=self._stop_timeout + 30, + ) + + def validate_nginx(self): + + self._execute( + "validate nginx", + ( + "exec", + "-T", + "--interactive=false", + self._web, + "nginx", + "-t", + ), + timeout=30, + ) + + def reload_nginx(self): + + self.validate_nginx() + + self._execute( + "reload nginx", + ( + "exec", + "-T", + "--interactive=false", + self._web, + "nginx", + "-s", + "reload", + ), + timeout=30, + ) + + def refresh(self): + + self.restart_php() + self.reload_nginx() + + def resume(self): + + self._execute( + "resume workers", + ( + "up", + "-d", + "--no-deps", + self._queue, + self._scheduler, + ), + timeout=120, + ) diff --git a/core/site_policy.py b/core/site_policy.py new file mode 100644 index 0000000..7dfad35 --- /dev/null +++ b/core/site_policy.py @@ -0,0 +1,186 @@ +"""Static ABSDEV site isolation and registry validation. + +This module does not inspect or modify live infrastructure. +""" + +from core.configuration import validate_config +from core.compatibility import canonical_hash + + +class SitePolicyError(RuntimeError): + """Unsafe site configuration or resource conflict.""" + + +SITE_BASE = "/opt/laravel-sites" + +RESERVED_USERS = { + "root", + "postgres", + "mysql", + "admin", + "administrator", + "mariadb.sys", + "mysql.sys", + "mysql.session", + "mysql.infoschema", +} + +RESERVED_DATABASES = { + "mysql", + "postgres", + "template0", + "template1", + "information_schema", + "performance_schema", + "sys", +} + + +def require(condition, message): + if not condition: + raise SitePolicyError(message) + + +def validated(config): + try: + return validate_config(config) + except Exception: + raise SitePolicyError( + "Invalid site configuration" + ) from None + + +def validate_site(config): + config = validated(config) + + site = config["site"] + docker = config["docker"] + database = config["database"] + + identifier = site["identifier"] + + require( + site["root"] == SITE_BASE + "/" + identifier, + "Site root must match the trusted site directory", + ) + + require( + docker["project"] == "site-" + identifier, + "Docker project must match site identity", + ) + + require( + 1024 <= site["origin_port"] <= 65535, + "Privileged or invalid origin port", + ) + + require( + database["username"].lower() not in RESERVED_USERS, + "Reserved database username", + ) + + require( + database["name"].lower() not in RESERVED_DATABASES, + "Reserved database name", + ) + + services = [ + docker["php_service"], + docker["web_service"], + docker["queue_service"], + docker["scheduler_service"], + ] + + require( + len(set(services)) == len(services), + "Application service names must be distinct", + ) + + require( + docker["backend_network"] != docker["proxy_network"], + "Backend and proxy networks must be distinct", + ) + + result = { + "format_version": 1, + "status": "VALID", + "site": identifier, + "configuration_fingerprint": canonical_hash(config), + "static_policy_verified": True, + "runtime_verified": False, + "execution_permitted": False, + } + + result["fingerprint"] = canonical_hash(result) + + return result + + +def validate_registry(configurations): + require( + isinstance(configurations, list) + and 1 <= len(configurations) <= 10000, + "Invalid site registry", + ) + + resources = { + "identifier": set(), + "domain": set(), + "root": set(), + "origin_port": set(), + "docker_project": set(), + "database": set(), + "database_username": set(), + } + + reports = [] + + for item in configurations: + config = validated(item) + + report = validate_site(config) + + site = config["site"] + docker = config["docker"] + database = config["database"] + + # Conservatively reject duplicate database names + # and users across the registry, even when the + # database containers differ. + + keys = { + "identifier": site["identifier"], + "domain": site["domain"].lower(), + "root": site["root"], + "origin_port": site["origin_port"], + "docker_project": docker["project"].lower(), + "database": database["name"].lower(), + "database_username": database["username"].lower(), + } + + for category, value in keys.items(): + require( + value not in resources[category], + f"Duplicate site resource: {category}", + ) + + resources[category].add(value) + + reports.append(report) + + result = { + "format_version": 1, + "status": "VALID", + "site_count": len(reports), + "sites": sorted( + reports, + key=lambda item: item["site"], + ), + "registry_conflicts_checked": True, + "runtime_verified": False, + "execution_permitted": False, + } + + result["fingerprint"] = canonical_hash(result) + + return result diff --git a/core/transactions.py b/core/transactions.py new file mode 100644 index 0000000..afa4439 --- /dev/null +++ b/core/transactions.py @@ -0,0 +1,491 @@ +"""Persistent deployment transaction state journal.""" + +import hashlib +import json +import os +import re +import stat +import uuid + +from datetime import datetime, timezone +from pathlib import Path + +from core.locking import DeploymentLock + + +class TransactionError(RuntimeError): + """Invalid or unsafe deployment transaction.""" + + +TRANSITIONS = { + "PREPARED": {"BACKED_UP", "FAILED"}, + "BACKED_UP": {"QUIESCED", "FAILED"}, + "QUIESCED": {"ACTIVATING", "FAILED"}, + "ACTIVATING": {"ACTIVATED", "FAILED"}, + "ACTIVATED": {"VERIFIED", "FAILED"}, + "VERIFIED": set(), + "FAILED": set(), +} + + +def require(condition, message): + if not condition: + raise TransactionError(message) + + +def matches(value, pattern): + return ( + isinstance(value, str) + and re.fullmatch(pattern, value) is not None + ) + + +def now(): + return datetime.now(timezone.utc).isoformat() + + +def checksum(data): + payload = { + key: value + for key, value in data.items() + if key != "checksum" + } + + return hashlib.sha256( + json.dumps( + payload, + sort_keys=True, + separators=(",", ":"), + allow_nan=False, + ).encode() + ).hexdigest() + + +def unique_keys(items): + result = {} + + for key, value in items: + require( + key not in result, + "Duplicate transaction JSON key", + ) + + result[key] = value + + return result + + +def validate_timestamp(value): + require( + isinstance(value, str), + "Invalid transaction timestamp", + ) + + try: + parsed = datetime.fromisoformat(value) + + require( + parsed.utcoffset() is not None + and parsed.utcoffset().total_seconds() == 0, + "Transaction timestamp must use UTC", + ) + + except ValueError as error: + raise TransactionError( + "Invalid transaction timestamp" + ) from error + + +class TransactionJournal: + + MAX_BYTES = 65536 + + def __init__(self, directory): + self.directory = Path(directory).absolute() + + self.path = ( + self.directory / "transaction.json" + ) + + self.lock_path = ( + self.directory / ".journal.lock" + ) + + self.validate_directory() + + def validate_directory(self): + directory = self.directory + + require( + directory.is_dir() + and not directory.is_symlink() + and directory.resolve() == directory, + "Invalid transaction directory", + ) + + details = directory.stat() + + require( + details.st_uid == os.getuid() + and not ( + stat.S_IMODE(details.st_mode) & 0o022 + ), + "Unsafe transaction directory permissions", + ) + + def validate(self, data): + require( + isinstance(data, dict) + and set(data) == { + "format_version", + "transaction_id", + "site", + "previous", + "candidate", + "revision", + "provenance", + "previous_revision", + "previous_provenance", + "phase", + "history", + "checksum", + }, + "Invalid transaction structure", + ) + + require( + type(data["format_version"]) is int + and data["format_version"] == 1, + "Unsupported transaction format", + ) + + require( + matches( + data["transaction_id"], + r"[a-f0-9]{32}", + ), + "Invalid transaction identifier", + ) + + require( + matches( + data["site"], + r"[a-z0-9][a-z0-9-]{0,62}", + ), + "Invalid transaction site", + ) + + for key in ("previous", "candidate"): + require( + matches( + data[key], + r"[1-9][0-9]{0,19}", + ), + "Invalid release identifier", + ) + + require( + data["previous"] != data["candidate"], + "Candidate and previous release are identical", + ) + + require( + matches(data["revision"], r"[a-f0-9]{40}"), + "Invalid Git revision", + ) + + require( + matches( + data["provenance"], + r"[a-f0-9]{64}", + ), + "Invalid provenance fingerprint", + ) + + require( + isinstance(data["phase"], str) + and data["phase"] in TRANSITIONS, + "Invalid transaction phase", + ) + + previous_revision = data["previous_revision"] + previous_provenance = data["previous_provenance"] + + require( + ( + previous_revision is None + and previous_provenance is None + ) + or ( + matches( + previous_revision, + r"[a-f0-9]{40}", + ) + and matches( + previous_provenance, + r"[a-f0-9]{64}", + ) + ), + "Invalid previous release evidence", + ) + + history = data["history"] + + require( + isinstance(history, list) + and 1 <= len(history) <= 6, + "Invalid transaction history", + ) + + previous = None + + for event in history: + require( + isinstance(event, dict) + and set(event) == {"phase", "timestamp"} + and isinstance(event["phase"], str) + and event["phase"] in TRANSITIONS, + "Invalid transaction event", + ) + + validate_timestamp(event["timestamp"]) + + phase = event["phase"] + + if previous is None: + require( + phase == "PREPARED", + "Invalid initial transaction phase", + ) + else: + require( + phase in TRANSITIONS[previous], + "Invalid transaction history transition", + ) + + previous = phase + + require( + previous == data["phase"], + "Transaction history does not match phase", + ) + + require( + matches(data["checksum"], r"[a-f0-9]{64}") + and checksum(data) == data["checksum"], + "Transaction checksum mismatch", + ) + + def load(self): + self.validate_directory() + + fd = None + + try: + fd = os.open( + self.path, + os.O_RDONLY + | os.O_NOFOLLOW + | os.O_NONBLOCK + | os.O_CLOEXEC, + ) + + details = os.fstat(fd) + + require( + stat.S_ISREG(details.st_mode) + and details.st_uid == os.getuid() + and details.st_nlink == 1 + and stat.S_IMODE(details.st_mode) == 0o600 + and details.st_size <= self.MAX_BYTES, + "Unsafe transaction file", + ) + + with os.fdopen(fd, "rb") as handle: + fd = None + + raw = handle.read(self.MAX_BYTES + 1) + + require( + len(raw) <= self.MAX_BYTES, + "Transaction exceeds size limit", + ) + + data = json.loads( + raw, + object_pairs_hook=unique_keys, + ) + + self.validate(data) + + return data + + except FileNotFoundError: + return None + + except TransactionError: + raise + + except (OSError, ValueError, TypeError) as error: + raise TransactionError( + "Unable to read transaction journal" + ) from error + + finally: + if fd is not None: + os.close(fd) + + def _write(self, data): + self.validate_directory() + + data["checksum"] = checksum(data) + + self.validate(data) + + temporary = self.directory / ( + ".transaction-" + uuid.uuid4().hex + ) + + fd = None + created = False + + try: + fd = os.open( + temporary, + os.O_WRONLY + | os.O_CREAT + | os.O_EXCL + | os.O_NOFOLLOW + | os.O_CLOEXEC, + 0o600, + ) + + created = True + + with os.fdopen(fd, "w") as handle: + fd = None + + json.dump( + data, + handle, + sort_keys=True, + indent=2, + allow_nan=False, + ) + + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + + os.replace(temporary, self.path) + + directory_fd = os.open( + self.directory, + os.O_RDONLY + | os.O_DIRECTORY + | os.O_NOFOLLOW, + ) + + try: + os.fsync(directory_fd) + finally: + os.close(directory_fd) + + except OSError as error: + raise TransactionError( + "Unable to persist transaction; inspect journal" + ) from error + + finally: + if fd is not None: + os.close(fd) + + if created: + temporary.unlink(missing_ok=True) + + require( + self.load() == data, + "Transaction persistence verification failed", + ) + + return data + + def create( + self, + site, + previous, + candidate, + revision, + provenance, + *, + previous_revision=None, + previous_provenance=None, + ): + with DeploymentLock(self.lock_path): + + require( + self.load() is None, + "Existing transaction requires review", + ) + + data = { + "format_version": 1, + "transaction_id": uuid.uuid4().hex, + "site": site, + "previous": previous, + "candidate": candidate, + "revision": revision, + "provenance": provenance, + "previous_revision": previous_revision, + "previous_provenance": previous_provenance, + "phase": "PREPARED", + "history": [ + { + "phase": "PREPARED", + "timestamp": now(), + } + ], + } + + return self._write(data) + + def transition( + self, + transaction_id, + expected_phase, + next_phase, + ): + with DeploymentLock(self.lock_path): + + data = self.load() + + require( + data is not None, + "No active transaction", + ) + + require( + data["transaction_id"] == transaction_id, + "Transaction identity mismatch", + ) + + require( + data["phase"] == expected_phase, + "Transaction phase changed", + ) + + require( + isinstance(next_phase, str) + and next_phase + in TRANSITIONS[data["phase"]], + "Invalid transaction phase transition", + ) + + data["phase"] = next_phase + + data["history"].append({ + "phase": next_phase, + "timestamp": now(), + }) + + return self._write(data) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..b07cacf --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,69 @@ +# Framework Architecture + +## Configuration + +- configuration.py +- site_policy.py +- preflight.py +- inspection_cli.py + +## Database and backup + +- database.py +- adapters/mysql +- adapters/postgresql +- execution.py +- backup.py +- backup_evidence.py + +## Deployment + +- releases.py +- locking.py +- provenance.py +- compatibility.py +- services.py +- health.py +- deployment.py + +## Transaction and recovery + +- transactions.py +- recovery.py +- rollback.py +- archive.py +- rollback_archive.py + +## Migration + +- approval.py +- rehearsal.py +- approval_store.py +- migration.py +- migration_recovery.py +- migration_archive.py +- operation_guard.py + +## Retention + +- retention.py + +## Ordinary deployment lifecycle + +PREPARED -> BACKED_UP -> QUIESCED -> ACTIVATING +-> ACTIVATED -> VERIFIED + +## Migration lifecycle + +Rehearsal -> Approval -> Intent -> Consumption +-> Migration -> Forward activation -> Archive + +## Trust boundary + +External operations require trusted runtime adapters. + +Checksums provide consistency checking, not operator +authentication or protection against privileged modification. + +Automatic database restoration is prohibited. +Permanent release deletion is disabled. diff --git a/docs/PRODUCTION-READINESS.md b/docs/PRODUCTION-READINESS.md new file mode 100644 index 0000000..ac937d0 --- /dev/null +++ b/docs/PRODUCTION-READINESS.md @@ -0,0 +1,42 @@ +# Production Readiness + +Status: DEVELOPMENT PREVIEW + +## Verified baseline + +- 853 passing unit tests +- 66 Python sources validated +- Eight inspection and planning commands +- Local CI validation passed +- Reference integrity preserved + +## Outstanding production gates + +- [ ] MySQL integration qualification +- [ ] PostgreSQL integration qualification +- [ ] Trusted runtime adapters +- [ ] Database identity and privilege verification +- [ ] Docker project and network isolation +- [ ] Secret management +- [ ] Complete modular migration inventory +- [ ] Full candidate source integrity +- [ ] Repository and revision authorisation +- [ ] HTTP and worker containment +- [ ] Persistent restart protection +- [ ] Shared transaction-state and lock bindings +- [ ] Ordinary journal protection during migrations +- [ ] Original release binding during migration recovery +- [ ] Trusted rehearsal execution +- [ ] Operator authentication and authorisation +- [ ] Interrupted-operation reconciliation +- [ ] Power-loss recovery qualification +- [ ] Trusted release retention inventory +- [ ] Isolated Gitea runner +- [ ] Immutable CI dependency pinning +- [ ] Remote CI verification +- [ ] End-to-end non-production deployment + +Production execution must remain disabled until +the applicable gates have been satisfied. + +Do not run database integration tests on ABSDEV. diff --git a/scripts/build-release.py b/scripts/build-release.py new file mode 100755 index 0000000..db5d314 --- /dev/null +++ b/scripts/build-release.py @@ -0,0 +1,226 @@ +#!/usr/bin/env python3 + +"""Reproducible development-preview source packaging.""" + +import argparse +import gzip +import hashlib +import io +import os +import re +import subprocess +import tarfile + +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + +DIRECTORIES = { + "core", "adapters", "tests", "config", + "bin", "scripts", "docs", ".gitea", +} + +TOP_LEVEL = { + "README.md", "CHANGELOG.md", + "VERSION", ".gitignore", +} + +EXTENSIONS = { + ".py", ".sh", ".json", + ".md", ".yaml", ".yml", +} + +DENIED = { + "runtime", "reference", "__pycache__", + ".git", "backups", "secrets", + ".env", "credentials", "credentials.json", + "secrets.json", "auth.json", + "id_rsa", "id_ed25519", +} + + +def require(condition, message): + if not condition: + raise RuntimeError(message) + + +def source_files(): + raw = subprocess.check_output([ + "git", "ls-files", "-z", + "--cached", "--others", + "--exclude-standard", + ], cwd=ROOT) + + names = sorted(set( + os.fsdecode(item) + for item in raw.split(b"\0") + if item + )) + + files = [] + + for name in names: + relative = Path(name) + + require( + not relative.is_absolute() + and ".." not in relative.parts + and not any( + part.lower() in DENIED + for part in relative.parts + ), + f"Unsafe source path: {name}", + ) + + require( + all( + re.fullmatch(r"[A-Za-z0-9_.-]+", part) + for part in relative.parts + ), + f"Invalid filename: {name}", + ) + + require( + name in TOP_LEVEL + or ( + relative.parts[0] in DIRECTORIES + and ( + relative.suffix in EXTENSIONS + or name == "bin/absdev-deploy" + ) + ), + f"Unapproved source: {name}", + ) + + path = ROOT / relative + + require( + path.is_file() + and not path.is_symlink() + and path.resolve() == path + and path.stat().st_size <= 10485760, + f"Unsafe source file: {name}", + ) + + files.append((name, path)) + + for required in ( + "README.md", + "CHANGELOG.md", + "VERSION", + "bin/absdev-deploy", + "config/site.example.json", + "scripts/ci-check.sh", + "scripts/build-release.py", + "docs/ARCHITECTURE.md", + "docs/PRODUCTION-READINESS.md", + ".gitea/workflows/framework-ci.yaml", + ): + require( + required in names, + f"Missing source: {required}", + ) + + return files + + +def build(output): + version = (ROOT / "VERSION").read_text().strip() + + require( + re.fullmatch( + r"[0-9]+\.[0-9]+\.[0-9]+-dev\.[0-9]+", + version, + ) is not None, + "Development-preview version required", + ) + + prefix = "absdev-deployment-" + version + target = output / (prefix + ".tar.gz") + + require( + not os.path.lexists(target) + and not os.path.lexists(output / "SHA256SUMS"), + "Release already exists", + ) + + files = source_files() + payloads = [] + + for name, path in files: + content = path.read_bytes() + mode = 0o755 if path.stat().st_mode & 0o111 else 0o644 + payloads.append((name, content, mode)) + + manifest = "".join( + hashlib.sha256(content).hexdigest() + + " " + name + "\n" + for name, content, mode in payloads + ).encode() + + payloads.append( + ("SOURCE.sha256", manifest, 0o644) + ) + + with target.open("xb") as raw: + with gzip.GzipFile( + filename="", + fileobj=raw, + mode="wb", + mtime=0, + compresslevel=9, + ) as compressed: + + with tarfile.open( + fileobj=compressed, + mode="w", + format=tarfile.PAX_FORMAT, + ) as archive: + + for name, content, mode in payloads: + entry = tarfile.TarInfo( + prefix + "/" + name + ) + + entry.size = len(content) + entry.mode = mode + entry.uid = 0 + entry.gid = 0 + entry.uname = "" + entry.gname = "" + entry.mtime = 0 + + archive.addfile( + entry, io.BytesIO(content) + ) + + with target.open("rb") as handle: + checksum = hashlib.file_digest( + handle, "sha256" + ).hexdigest() + + with (output / "SHA256SUMS").open("x") as handle: + handle.write( + checksum + " " + target.name + "\n" + ) + + print(f"Source files: {len(files)}") + print(f"Package: {target}") + print(f"SHA256: {checksum}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + + parser.add_argument( + "--output", required=True, type=Path + ) + + args = parser.parse_args() + + require( + args.output.is_dir(), + "Output directory must exist", + ) + + build(args.output) diff --git a/scripts/ci-check.sh b/scripts/ci-check.sh new file mode 100755 index 0000000..7097600 --- /dev/null +++ b/scripts/ci-check.sh @@ -0,0 +1,146 @@ +#!/usr/bin/env bash + +set -Eeuo pipefail +umask 077 + +ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P)" + +cd "$ROOT" + +export PYTHONDONTWRITEBYTECODE=1 +export PYTHONUNBUFFERED=1 +export ABSDEV_INTEGRATION_TESTS=0 + +echo "=== ABSDEV FRAMEWORK CI ===" + +python3 --version + +echo +echo "=== PYTHON SYNTAX VALIDATION ===" + +python3 -B <<'PY' +from pathlib import Path + +files = [] + +for directory in ("core", "adapters", "tests"): + files.extend( + sorted(Path(directory).rglob("*.py")) + ) + +files.extend([ + Path("bin/absdev-deploy"), + Path("bin/absdev-deploy-validate.py"), +]) + +for path in files: + if path.is_symlink() or not path.is_file(): + raise SystemExit( + f"Unsafe Python source: {path}" + ) + + compile( + path.read_bytes(), + str(path), + "exec", + ) + +print(f"PASS: {len(files)} Python sources compiled") +PY + +echo +echo "=== COMPLETE UNIT REGRESSION SUITE ===" + +python3 -B -m unittest discover -s tests/unit + +echo +echo "=== VERIFY PRODUCTION CAPABILITY RESTRICTIONS ===" + +python3 -B <<'PY' +import json +import subprocess +import sys + +result = subprocess.run( + [ + sys.executable, + "bin/absdev-deploy", + "capabilities", + ], + capture_output=True, + text=True, + timeout=15, + check=True, +) + +report = json.loads(result.stdout) + +for field in ( + "production_ready", + "deployment_execution_enabled", + "migration_execution_enabled", + "provisioning_execution_enabled", + "database_restore_enabled", + "permanent_deletion_enabled", +): + if report.get(field) is not False: + raise SystemExit( + f"FAIL: Unsafe capability: {field}" + ) + + print(f"PASS: {field}=false") + +for command in ( + "deploy", + "migrate", + "rollback", + "restore", + "provision", + "delete", +): + result = subprocess.run( + [ + sys.executable, + "bin/absdev-deploy", + command, + ], + capture_output=True, + timeout=15, + ) + + if result.returncode == 0: + raise SystemExit( + f"FAIL: Unexpected command: {command}" + ) + + print(f"PASS: Unsupported command rejected: {command}") +PY + +echo +echo "=== EXAMPLE CONFIGURATION ===" + +bin/absdev-deploy validate \ + --config config/site.example.json + +bin/absdev-deploy site-policy \ + --config config/site.example.json + +bin/absdev-deploy provision-plan \ + --config config/site.example.json + +echo +echo "=== REFERENCE INTEGRITY ===" + +if [[ -e REFERENCE.sha256 ]]; then + sha256sum -c REFERENCE.sha256 >/dev/null + echo "PASS: Reference implementation unchanged" +else + echo "SKIP: Private reference excluded from checkout" +fi + +echo +echo "========================================" +echo "PASS: FRAMEWORK CI" +echo "UNIT TESTS AND STATIC VALIDATION ONLY" +echo "DATABASE INTEGRATION NOT EXECUTED" +echo "========================================" diff --git a/tests/integration/test_mysql.py b/tests/integration/test_mysql.py new file mode 100644 index 0000000..77cde33 --- /dev/null +++ b/tests/integration/test_mysql.py @@ -0,0 +1,768 @@ +"""Disposable MySQL backup and restoration integration test.""" + +import copy +import hashlib +import io +import json +import os +import secrets +import subprocess +import tempfile +import time +import unittest + +from datetime import datetime, timezone +from pathlib import Path + +from core.database import get_adapter +from core.backup import BackupEngine +from core.execution import CommandRunner + + +ROOT = Path.cwd() + +IMAGE = ( + "sha256:" + "8c233bad33d520a7aae1c1e619c3a9775" + "f4a1ba2d463d692fada04ec7f40be00" +) + +LABEL = "absdev.framework.integration" + +SOURCE_DATABASE = "example_db" +RESTORE_DATABASE = "isolated_restore_mysql" + + +def require(condition, message): + + if not condition: + raise RuntimeError(message) + + +def command(*args, input_data=None, timeout=120): + + result = subprocess.run( + args, + input=input_data, + stdin=( + subprocess.DEVNULL + if input_data is None + else None + ), + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + timeout=timeout, + ) + + require( + result.returncode == 0, + f"Command failed with status {result.returncode}", + ) + + return result.stdout + + +def inspect(cid): + + return json.loads( + command("docker", "inspect", cid) + )[0] + + +def production_inventory(): + + inventory = {} + + for cid in command( + "docker", "ps", "-aq", "--no-trunc" + ).decode().splitlines(): + + details = inspect(cid) + + if ( + details["Config"]["Labels"] or {} + ).get(LABEL) == "true": + + continue + + inventory[cid] = { + "name": details["Name"], + "running": details["State"]["Running"], + "started": details["State"]["StartedAt"], + "restart_policy": ( + details["HostConfig"]["RestartPolicy"] + ), + } + + return inventory + + +class MySQLIntegrationTests(unittest.TestCase): + + def test_backup_and_restore(self): + + import socket + + if socket.gethostname().split(".")[0].lower() == "absdev": + self.skipTest( + "Database integration tests prohibited on ABSDEV" + ) + + if os.environ.get("ABSDEV_INTEGRATION_TESTS") != "1": + self.skipTest( + "Explicit integration test authorisation required" + ) + + + before = production_inventory() + + token = secrets.token_hex(8) + + name = f"absdev-integration-mysql-{token}" + + password = secrets.token_hex(32) + + cid = None + + evidence = { + "driver": "mysql", + "image": IMAGE, + "started_at": datetime.now( + timezone.utc + ).isoformat(), + "result": "INCOMPLETE", + } + + runtime = ( + ROOT / "runtime/integration" + ) + + work = runtime / name + work.mkdir(mode=0o700) + + backup_root = work / "backups" + backup_root.mkdir(mode=0o700) + + try: + + available = int( + next( + line.split()[1] + for line in Path( + "/proc/meminfo" + ).read_text().splitlines() + if line.startswith("MemAvailable:") + ) + ) + + require( + available >= 786432, + "Insufficient available memory", + ) + + require( + not command( + "docker", "ps", "-aq", + "--filter", f"label={LABEL}=true", + ).strip(), + "Existing integration container requires review", + ) + + image = json.loads( + command( + "docker", "image", "inspect", IMAGE + ) + )[0] + + require( + image["Id"] == IMAGE, + "Unexpected database image", + ) + + print("\n=== CREATE DISPOSABLE MYSQL ===") + + with tempfile.TemporaryDirectory( + dir=work + ) as directory: + + secret_dir = Path(directory) + + envfile = secret_dir / "mysql.env" + + envfile.write_text( + f"MYSQL_ROOT_PASSWORD={password}\n" + f"MYSQL_DATABASE={SOURCE_DATABASE}\n" + ) + + envfile.chmod(0o600) + + # Create before starting so isolation + # can be independently verified. + + cid = command( + "docker", "create", + "--pull=never", + "--name", name, + "--label", f"{LABEL}=true", + "--label", f"absdev.integration.token={token}", + "--network", "none", + "--restart", "no", + "--memory", "512m", + "--memory-swap", "768m", + "--cpus", "0.5", + "--pids-limit", "256", + "--security-opt", + "no-new-privileges=true", + "--env-file", str(envfile), + IMAGE, + "--innodb-buffer-pool-size=64M", + "--max-connections=20", + "--performance-schema=OFF", + "--skip-log-bin", + ).decode().strip() + + def verify_isolation(): + + item = inspect(cid) + + labels = item["Config"]["Labels"] + + host = item["HostConfig"] + + require( + item["Id"] == cid + and item["Name"] == "/" + name + and item["Image"] == IMAGE, + "Unexpected test container identity", + ) + + require( + labels.get(LABEL) == "true" + and labels.get( + "absdev.integration.token" + ) == token, + "Invalid integration ownership", + ) + + require( + host["NetworkMode"] == "none" + and not host["PortBindings"] + and not host["Privileged"] + and not host["Binds"] + and not host.get("VolumesFrom") + and host["RestartPolicy"]["Name"] == "no", + "Container isolation failed", + ) + + require( + host["Memory"] == 512 * 1024 * 1024 + and host["MemorySwap"] + == 768 * 1024 * 1024, + "Resource limits changed", + ) + + production_sources = set() + + for original in before: + + for mount in inspect(original)["Mounts"]: + + production_sources.add( + mount["Source"] + ) + + for mount in item["Mounts"]: + + require( + mount["Type"] == "volume" + and mount["Source"] + not in production_sources, + "Unexpected or shared database mount", + ) + + return item + + verify_isolation() + + command("docker", "start", cid) + + print("PASS: Disposable container started") + + deadline = time.monotonic() + 180 + + while time.monotonic() < deadline: + + state = verify_isolation()["State"] + + require( + state["Running"] + and not state["OOMKilled"], + "Test database stopped unexpectedly", + ) + + try: + + result = command( + "docker", "exec", cid, + "mysqladmin", + "--protocol=TCP", + "--host=127.0.0.1", + "--silent", + "ping", + timeout=10, + ) + + if b"mysqld is alive" in result: + break + + except RuntimeError: + pass + + time.sleep(2) + + else: + + raise RuntimeError( + "MySQL readiness timed out" + ) + + print("PASS: MySQL TCP service ready") + + # Install credentials inside the disposable + # container without displaying their values. + + client = ( + "[client]\n" + "user=root\n" + f"password={password}\n" + "host=127.0.0.1\n" + "protocol=TCP\n" + ).encode() + + command( + "docker", "exec", "-i", cid, + "sh", "-c", + "umask 077; " + "mkdir -p /run/secrets; " + "cat > /run/secrets/absdev-client.cnf", + input_data=client, + ) + + def sql(statement, database=None): + + verify_isolation() + + args = [ + "docker", "exec", cid, + "timeout", "-k", "5s", "60s", + "mysql", + "--defaults-file=" + "/run/secrets/absdev-client.cnf", + "--batch", + "--skip-column-names", + ] + + if database is not None: + + require( + database in ( + SOURCE_DATABASE, + RESTORE_DATABASE, + ), + "Invalid integration database target", + ) + + args.append( + f"--database={database}" + ) + + args.extend([ + "--execute", + statement, + ]) + + return command(*args) + + print("\n=== CREATE SYNTHETIC TEST DATABASE ===") + + sql( + """ + CREATE TABLE users ( + id BIGINT UNSIGNED PRIMARY KEY, + name VARCHAR(255) NOT NULL, + email VARCHAR(255) NOT NULL, + UNIQUE KEY users_email_unique (email) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + + CREATE TABLE orders ( + id BIGINT UNSIGNED PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL, + amount DECIMAL(12,2) NOT NULL, + payload BLOB, + CONSTRAINT orders_user_fk + FOREIGN KEY (user_id) + REFERENCES users(id) + ) ENGINE=InnoDB; + + CREATE TABLE migrations ( + id INT UNSIGNED PRIMARY KEY, + migration VARCHAR(255) NOT NULL, + batch INT NOT NULL + ) ENGINE=InnoDB; + + INSERT INTO users VALUES + (1, 'Alice', 'alice@example.invalid'), + (2, 'José', 'jose@example.invalid'); + + INSERT INTO orders VALUES + (1, 1, 12.50, UNHEX('000102FF')), + (2, 2, 99.95, UNHEX('AABBCCDD')); + + INSERT INTO migrations VALUES + (1, 'create_users_table', 1), + (2, 'create_orders_table', 1), + (3, 'add_payload_column', 2); + """, + SOURCE_DATABASE, + ) + + print("PASS: Synthetic database created") + + config = json.loads( + (ROOT / "config/site.example.json") + .read_text() + ) + + config["database"].update({ + "driver": "mysql", + "container": name, + "host": "127.0.0.1", + "port": 3306, + "name": SOURCE_DATABASE, + "username": "root", + }) + + adapter = get_adapter(config) + + # Bind execution to the exact disposable + # container ID rather than its mutable name. + # Enforce a timeout inside the container too. + + def bounded(args): + + result = list(args) + + require( + result[:2] == ["docker", "exec"], + "Unexpected adapter command", + ) + + index = 3 if result[2] == "-i" else 2 + + require( + result[index] == name, + "Unexpected database target", + ) + + result[index] = cid + + result[index + 1:index + 1] = [ + "timeout", + "-k", "5s", + "60s", + ] + + return result + + allowed = [ + bounded(adapter.identity_command()), + bounded(adapter.backup_command()), + bounded(adapter.ping_command()), + bounded(adapter.version_command()), + ] + + runner = CommandRunner( + allowed_commands=allowed, + timeout=75, + ) + + def guarded_runner(args, output): + + verify_isolation() + + runner( + bounded(args), + output, + ) + + output = io.BytesIO() + + guarded_runner( + adapter.ping_command(), + output, + ) + + self.assertEqual( + output.getvalue().strip(), + b"1", + ) + + print("PASS: Authenticated connectivity") + + output = io.BytesIO() + + guarded_runner( + adapter.version_command(), + output, + ) + + version = output.getvalue().decode().strip() + + print("MySQL version:", version) + + evidence["database_version"] = version + + print("\n=== EXECUTE FRAMEWORK BACKUP ===") + + engine = BackupEngine( + adapter, + backup_root, + guarded_runner, + ) + + backup = engine.create() + manifest = engine.verify(backup) + + print("PASS: Real MySQL backup created") + print("Backup bytes:", manifest["bytes"]) + print("SHA-256:", manifest["sha256"]) + + evidence["backup"] = str( + backup.relative_to(ROOT) + ) + + evidence["backup_sha256"] = manifest["sha256"] + + evidence["backup_bytes"] = manifest["bytes"] + + print("\n=== CREATE ISOLATED RESTORE TARGET ===") + + sql( + "CREATE DATABASE isolated_restore_mysql " + "CHARACTER SET utf8mb4" + ) + + self.assertEqual( + sql( + "SELECT COUNT(*) FROM " + "information_schema.tables " + "WHERE table_schema = " + "'isolated_restore_mysql'" + ).strip(), + b"0", + ) + + print("PASS: Restore target is empty") + + restore = bounded( + adapter.restore_command( + RESTORE_DATABASE + ) + ) + + verify_isolation() + + engine.verify(backup) + + # The restore path is intentionally + # separate from the backup-only runner. + + with (backup / "database.sql").open("rb") as handle: + + result = subprocess.run( + restore, + stdin=handle, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=75, + ) + + require( + result.returncode == 0, + "MySQL restoration failed", + ) + + print("PASS: Real MySQL restoration completed") + + print("\n=== COMPARE SOURCE AND RESTORED DATA ===") + + queries = { + "users": ( + "SELECT id, name, email " + "FROM users ORDER BY id" + ), + "orders": ( + "SELECT id, user_id, amount, " + "HEX(payload) FROM orders ORDER BY id" + ), + "migrations": ( + "SELECT id, migration, batch " + "FROM migrations ORDER BY id" + ), + "table_columns": ( + "SELECT TABLE_NAME, COLUMN_NAME, " + "COLUMN_TYPE, IS_NULLABLE " + "FROM information_schema.COLUMNS " + "WHERE TABLE_SCHEMA=DATABASE() " + "ORDER BY TABLE_NAME, ORDINAL_POSITION" + ), + "indexes": ( + "SELECT TABLE_NAME, INDEX_NAME, " + "NON_UNIQUE, SEQ_IN_INDEX, COLUMN_NAME " + "FROM information_schema.STATISTICS " + "WHERE TABLE_SCHEMA=DATABASE() " + "ORDER BY TABLE_NAME, INDEX_NAME, " + "SEQ_IN_INDEX" + ), + "foreign_keys": ( + "SELECT TABLE_NAME, CONSTRAINT_NAME, " + "COLUMN_NAME, REFERENCED_TABLE_NAME, " + "REFERENCED_COLUMN_NAME " + "FROM information_schema.KEY_COLUMN_USAGE " + "WHERE TABLE_SCHEMA=DATABASE() " + "AND REFERENCED_TABLE_NAME IS NOT NULL " + "ORDER BY TABLE_NAME, CONSTRAINT_NAME, " + "ORDINAL_POSITION" + ), + } + + for label, query in queries.items(): + + original = sql( + query, + SOURCE_DATABASE, + ) + + restored = sql( + query, + RESTORE_DATABASE, + ) + + self.assertTrue(original) + + self.assertEqual( + original, + restored, + f"Restoration mismatch: {label}", + ) + + print("PASS:", label) + + self.assertEqual( + sql( + "SELECT COUNT(*) FROM users", + RESTORE_DATABASE, + ).strip(), + b"2", + ) + + self.assertEqual( + sql( + "SELECT COUNT(*) FROM orders", + RESTORE_DATABASE, + ).strip(), + b"2", + ) + + self.assertEqual( + sql( + "SELECT COUNT(*) FROM migrations", + RESTORE_DATABASE, + ).strip(), + b"3", + ) + + print("PASS: Expected record counts verified") + + print("\n=== VERIFY FOREIGN KEY ENFORCEMENT ===") + + with self.assertRaises(RuntimeError): + + sql( + "INSERT INTO orders VALUES " + "(999, 999, 1.00, NULL)", + RESTORE_DATABASE, + ) + + print("PASS: Invalid foreign key rejected") + + print("\n=== VERIFY BACKUP INTEGRITY AGAIN ===") + + engine.verify(backup) + + evidence["verified_checks"] = list(queries) + + evidence["result"] = "MYSQL_RESTORE_VERIFIED" + + finally: + + print("\n=== REMOVE DISPOSABLE DATABASE ===") + + if cid is not None: + + item = inspect(cid) + + labels = item["Config"]["Labels"] + + require( + item["Id"] == cid + and labels.get(LABEL) == "true" + and labels.get( + "absdev.integration.token" + ) == token, + "Unsafe cleanup target", + ) + + command( + "docker", "rm", "-f", "-v", cid + ) + + print("PASS: Test container removed") + + after = production_inventory() + + evidence["production_inventory_unchanged"] = ( + before == after + ) + + evidence["completed_at"] = datetime.now( + timezone.utc + ).isoformat() + + report = work / "result.json" + + with report.open("x") as handle: + + json.dump( + evidence, + handle, + indent=2, + ) + + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + + print("Integration evidence:", report) + + self.assertEqual( + before, + after, + "Production container inventory changed", + ) + + print("PASS: Production container uptime preserved") + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/unit/test_approval.py b/tests/unit/test_approval.py new file mode 100644 index 0000000..9621a21 --- /dev/null +++ b/tests/unit/test_approval.py @@ -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() diff --git a/tests/unit/test_approval_store.py b/tests/unit/test_approval_store.py new file mode 100644 index 0000000..b24ed93 --- /dev/null +++ b/tests/unit/test_approval_store.py @@ -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() diff --git a/tests/unit/test_archive.py b/tests/unit/test_archive.py new file mode 100644 index 0000000..2c4c78f --- /dev/null +++ b/tests/unit/test_archive.py @@ -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() diff --git a/tests/unit/test_backup.py b/tests/unit/test_backup.py new file mode 100644 index 0000000..b7225a9 --- /dev/null +++ b/tests/unit/test_backup.py @@ -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() diff --git a/tests/unit/test_backup_evidence.py b/tests/unit/test_backup_evidence.py new file mode 100644 index 0000000..871dc5d --- /dev/null +++ b/tests/unit/test_backup_evidence.py @@ -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() diff --git a/tests/unit/test_ci_policy.py b/tests/unit/test_ci_policy.py new file mode 100644 index 0000000..6ee0f15 --- /dev/null +++ b/tests/unit/test_ci_policy.py @@ -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() diff --git a/tests/unit/test_compatibility.py b/tests/unit/test_compatibility.py new file mode 100644 index 0000000..e0ce9eb --- /dev/null +++ b/tests/unit/test_compatibility.py @@ -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() diff --git a/tests/unit/test_configuration.py b/tests/unit/test_configuration.py new file mode 100644 index 0000000..c3419ba --- /dev/null +++ b/tests/unit/test_configuration.py @@ -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": "git@example.invalid: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:secret@example.invalid/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() diff --git a/tests/unit/test_database.py b/tests/unit/test_database.py new file mode 100644 index 0000000..376b515 --- /dev/null +++ b/tests/unit/test_database.py @@ -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() diff --git a/tests/unit/test_deployment.py b/tests/unit/test_deployment.py new file mode 100644 index 0000000..30a687e --- /dev/null +++ b/tests/unit/test_deployment.py @@ -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( + "