Initial ABSDEV deployment framework development preview
This commit is contained in:
@@ -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
|
||||||
+49
@@ -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
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -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}",
|
||||||
|
]
|
||||||
|
)
|
||||||
@@ -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}",
|
||||||
|
]
|
||||||
|
)
|
||||||
Executable
+22
@@ -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())
|
||||||
Executable
+75
@@ -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())
|
||||||
@@ -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": "[email protected]:example/application.git",
|
||||||
|
"branch": "main"
|
||||||
|
},
|
||||||
|
"database": {
|
||||||
|
"driver": "mysql",
|
||||||
|
"container": "platform-mysql",
|
||||||
|
"host": "platform-mysql",
|
||||||
|
"port": 3306,
|
||||||
|
"name": "example_db",
|
||||||
|
"username": "example_app"
|
||||||
|
},
|
||||||
|
"docker": {
|
||||||
|
"project": "site-example-absdev-net",
|
||||||
|
"application_path": "/var/www/html",
|
||||||
|
"php_service": "php",
|
||||||
|
"web_service": "web",
|
||||||
|
"queue_service": "queue",
|
||||||
|
"scheduler_service": "scheduler",
|
||||||
|
"backend_network": "laravel_backend",
|
||||||
|
"proxy_network": "laravel_proxy"
|
||||||
|
},
|
||||||
|
"retention": {
|
||||||
|
"keep_releases": 5,
|
||||||
|
"automatic_deletion": false
|
||||||
|
},
|
||||||
|
"migration": {
|
||||||
|
"require_approval": true,
|
||||||
|
"require_rehearsal": true,
|
||||||
|
"approval_ttl_hours": 24
|
||||||
|
},
|
||||||
|
"backup": {
|
||||||
|
"required": true,
|
||||||
|
"verify_checksum": true
|
||||||
|
},
|
||||||
|
"health": {
|
||||||
|
"endpoints": [
|
||||||
|
"/",
|
||||||
|
"/up",
|
||||||
|
"/login"
|
||||||
|
],
|
||||||
|
"timeout_seconds": 30
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
@@ -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)
|
||||||
+465
@@ -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
|
||||||
+450
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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)
|
||||||
@@ -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")
|
||||||
@@ -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,
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
)
|
||||||
+246
@@ -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"
|
||||||
|
)
|
||||||
@@ -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
|
||||||
+202
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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,
|
||||||
|
)
|
||||||
@@ -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
|
||||||
@@ -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)
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
Executable
+226
@@ -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)
|
||||||
Executable
+146
@@ -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 "========================================"
|
||||||
@@ -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', '[email protected]'),
|
||||||
|
(2, 'José', '[email protected]');
|
||||||
|
|
||||||
|
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)
|
||||||
@@ -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()
|
||||||
@@ -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()
|
||||||
@@ -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()
|
||||||
@@ -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()
|
||||||
@@ -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()
|
||||||
@@ -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()
|
||||||
@@ -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()
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
import copy
|
||||||
|
import json
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from core.configuration import (
|
||||||
|
ConfigurationError,
|
||||||
|
validate_config,
|
||||||
|
load_config,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def example():
|
||||||
|
|
||||||
|
return {
|
||||||
|
"schema_version": 1,
|
||||||
|
"site": {
|
||||||
|
"identifier": "example-absdev-net",
|
||||||
|
"domain": "example.absdev.net",
|
||||||
|
"root": "/opt/laravel-sites/example-absdev-net",
|
||||||
|
"origin_port": 8199,
|
||||||
|
},
|
||||||
|
"repository": {
|
||||||
|
"url": "[email protected]:example/application.git",
|
||||||
|
"branch": "main",
|
||||||
|
},
|
||||||
|
"database": {
|
||||||
|
"driver": "mysql",
|
||||||
|
"container": "platform-mysql",
|
||||||
|
"host": "platform-mysql",
|
||||||
|
"port": 3306,
|
||||||
|
"name": "example_db",
|
||||||
|
"username": "example_app",
|
||||||
|
},
|
||||||
|
"docker": {
|
||||||
|
"project": "site-example-absdev-net",
|
||||||
|
"application_path": "/var/www/html",
|
||||||
|
"php_service": "php",
|
||||||
|
"web_service": "web",
|
||||||
|
"queue_service": "queue",
|
||||||
|
"scheduler_service": "scheduler",
|
||||||
|
"backend_network": "laravel_backend",
|
||||||
|
"proxy_network": "laravel_proxy",
|
||||||
|
},
|
||||||
|
"retention": {
|
||||||
|
"keep_releases": 5,
|
||||||
|
"automatic_deletion": False,
|
||||||
|
},
|
||||||
|
"migration": {
|
||||||
|
"require_approval": True,
|
||||||
|
"require_rehearsal": True,
|
||||||
|
"approval_ttl_hours": 24,
|
||||||
|
},
|
||||||
|
"backup": {
|
||||||
|
"required": True,
|
||||||
|
"verify_checksum": True,
|
||||||
|
},
|
||||||
|
"health": {
|
||||||
|
"endpoints": ["/", "/up", "/login"],
|
||||||
|
"timeout_seconds": 30,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ConfigurationTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def invalid(self, section, key, value):
|
||||||
|
|
||||||
|
data = example()
|
||||||
|
data[section][key] = value
|
||||||
|
|
||||||
|
with self.assertRaises(ConfigurationError):
|
||||||
|
validate_config(data)
|
||||||
|
|
||||||
|
def test_valid_mysql_configuration(self):
|
||||||
|
self.assertEqual(
|
||||||
|
validate_config(example())["database"]["driver"],
|
||||||
|
"mysql",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_valid_postgresql_configuration(self):
|
||||||
|
|
||||||
|
data = example()
|
||||||
|
|
||||||
|
data["database"].update({
|
||||||
|
"driver": "pgsql",
|
||||||
|
"port": 5432,
|
||||||
|
"host": "platform-postgres",
|
||||||
|
"container": "platform-postgres",
|
||||||
|
})
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
validate_config(data)["database"]["driver"],
|
||||||
|
"pgsql",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invalid_site_identifier(self):
|
||||||
|
self.invalid("site", "identifier", "../other")
|
||||||
|
|
||||||
|
def test_invalid_domain(self):
|
||||||
|
self.invalid("site", "domain", "https://example.net")
|
||||||
|
|
||||||
|
def test_invalid_domain_labels(self):
|
||||||
|
self.invalid("site", "domain", "a..example.net")
|
||||||
|
|
||||||
|
def test_invalid_port(self):
|
||||||
|
self.invalid("site", "origin_port", 65536)
|
||||||
|
|
||||||
|
def test_boolean_port_rejected(self):
|
||||||
|
self.invalid("site", "origin_port", True)
|
||||||
|
|
||||||
|
def test_relative_site_path(self):
|
||||||
|
self.invalid("site", "root", "../example")
|
||||||
|
|
||||||
|
def test_parent_path_rejected(self):
|
||||||
|
self.invalid(
|
||||||
|
"site", "root",
|
||||||
|
"/opt/laravel-sites/../example",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_root_directory_rejected(self):
|
||||||
|
self.invalid("site", "root", "/")
|
||||||
|
|
||||||
|
def test_invalid_database_driver(self):
|
||||||
|
self.invalid("database", "driver", "unknown")
|
||||||
|
|
||||||
|
def test_invalid_database_name(self):
|
||||||
|
self.invalid("database", "name", "db; DROP DATABASE x")
|
||||||
|
|
||||||
|
def test_invalid_database_username(self):
|
||||||
|
self.invalid("database", "username", "root; command")
|
||||||
|
|
||||||
|
def test_invalid_database_port(self):
|
||||||
|
self.invalid("database", "port", 0)
|
||||||
|
|
||||||
|
def test_database_password_rejected(self):
|
||||||
|
self.invalid("database", "password", "example-secret")
|
||||||
|
|
||||||
|
def test_unknown_field_rejected(self):
|
||||||
|
self.invalid("site", "unexpected", "value")
|
||||||
|
|
||||||
|
def test_unknown_section_rejected(self):
|
||||||
|
|
||||||
|
data = example()
|
||||||
|
data["unknown"] = {}
|
||||||
|
|
||||||
|
with self.assertRaises(ConfigurationError):
|
||||||
|
validate_config(data)
|
||||||
|
|
||||||
|
def test_missing_section_rejected(self):
|
||||||
|
|
||||||
|
data = example()
|
||||||
|
del data["database"]
|
||||||
|
|
||||||
|
with self.assertRaises(ConfigurationError):
|
||||||
|
validate_config(data)
|
||||||
|
|
||||||
|
def test_missing_field_rejected(self):
|
||||||
|
|
||||||
|
data = example()
|
||||||
|
del data["site"]["domain"]
|
||||||
|
|
||||||
|
with self.assertRaises(ConfigurationError):
|
||||||
|
validate_config(data)
|
||||||
|
|
||||||
|
def test_invalid_branch(self):
|
||||||
|
self.invalid("repository", "branch", "main; command")
|
||||||
|
|
||||||
|
def test_invalid_branch_component(self):
|
||||||
|
self.invalid("repository", "branch", "feature/.hidden")
|
||||||
|
|
||||||
|
def test_invalid_repository(self):
|
||||||
|
self.invalid("repository", "url", "file:///etc")
|
||||||
|
|
||||||
|
def test_embedded_credentials_rejected(self):
|
||||||
|
self.invalid(
|
||||||
|
"repository",
|
||||||
|
"url",
|
||||||
|
"https://user:[email protected]/app.git",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invalid_service(self):
|
||||||
|
self.invalid("docker", "php_service", "../php")
|
||||||
|
|
||||||
|
def test_duplicate_service_rejected(self):
|
||||||
|
self.invalid("docker", "web_service", "php")
|
||||||
|
|
||||||
|
def test_invalid_network(self):
|
||||||
|
self.invalid("docker", "backend_network", "net; command")
|
||||||
|
|
||||||
|
def test_invalid_retention_count(self):
|
||||||
|
self.invalid("retention", "keep_releases", 0)
|
||||||
|
|
||||||
|
def test_destructive_cleanup_rejected(self):
|
||||||
|
self.invalid("retention", "automatic_deletion", True)
|
||||||
|
|
||||||
|
def test_migration_approval_required(self):
|
||||||
|
self.invalid("migration", "require_approval", False)
|
||||||
|
|
||||||
|
def test_rehearsal_required(self):
|
||||||
|
self.invalid("migration", "require_rehearsal", False)
|
||||||
|
|
||||||
|
def test_invalid_approval_ttl(self):
|
||||||
|
self.invalid("migration", "approval_ttl_hours", 0)
|
||||||
|
|
||||||
|
def test_backup_required(self):
|
||||||
|
self.invalid("backup", "required", False)
|
||||||
|
|
||||||
|
def test_checksum_required(self):
|
||||||
|
self.invalid("backup", "verify_checksum", False)
|
||||||
|
|
||||||
|
def test_invalid_health_endpoint(self):
|
||||||
|
self.invalid("health", "endpoints", ["https://other.net"])
|
||||||
|
|
||||||
|
def test_external_health_endpoint_rejected(self):
|
||||||
|
self.invalid("health", "endpoints", ["//other.net"])
|
||||||
|
|
||||||
|
def test_invalid_timeout(self):
|
||||||
|
self.invalid("health", "timeout_seconds", 0)
|
||||||
|
|
||||||
|
def test_invalid_schema_version(self):
|
||||||
|
|
||||||
|
data = example()
|
||||||
|
data["schema_version"] = 999
|
||||||
|
|
||||||
|
with self.assertRaises(ConfigurationError):
|
||||||
|
validate_config(data)
|
||||||
|
|
||||||
|
def test_no_input_mutation(self):
|
||||||
|
|
||||||
|
data = example()
|
||||||
|
original = copy.deepcopy(data)
|
||||||
|
|
||||||
|
result = validate_config(data)
|
||||||
|
result["site"]["domain"] = "changed.invalid"
|
||||||
|
|
||||||
|
self.assertEqual(data, original)
|
||||||
|
|
||||||
|
def test_load_configuration_file(self):
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
|
||||||
|
path = Path(directory) / "site.json"
|
||||||
|
path.write_text(json.dumps(example()))
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
load_config(path)["schema_version"], 1
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invalid_json_rejected(self):
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
|
||||||
|
path = Path(directory) / "site.json"
|
||||||
|
path.write_text("{invalid")
|
||||||
|
|
||||||
|
with self.assertRaises(ConfigurationError):
|
||||||
|
load_config(path)
|
||||||
|
|
||||||
|
def test_duplicate_json_keys_rejected(self):
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
|
||||||
|
path = Path(directory) / "site.json"
|
||||||
|
path.write_text(
|
||||||
|
'{"schema_version":1,"schema_version":2}'
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(ConfigurationError):
|
||||||
|
load_config(path)
|
||||||
|
|
||||||
|
def test_missing_file_rejected(self):
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
|
||||||
|
with self.assertRaises(ConfigurationError):
|
||||||
|
load_config(Path(directory) / "missing.json")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -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()
|
||||||
@@ -0,0 +1,660 @@
|
|||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import Mock
|
||||||
|
|
||||||
|
from core.compatibility import provenance_fingerprint
|
||||||
|
from core.backup_evidence import BackupEvidence
|
||||||
|
from core.approval_store import ApprovalStore
|
||||||
|
from core.operation_guard import OperationGuard
|
||||||
|
from core.deployment import DeploymentController, DeploymentError
|
||||||
|
from core.locking import DeploymentLock, LockError
|
||||||
|
from core.releases import ReleaseManager
|
||||||
|
from core.transactions import TransactionJournal
|
||||||
|
|
||||||
|
|
||||||
|
def evidence(revision):
|
||||||
|
|
||||||
|
data = {
|
||||||
|
"format_version": 1,
|
||||||
|
"revision": revision,
|
||||||
|
"migrations": {
|
||||||
|
"database/migrations/0001_users.php": "a" * 64,
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"composer.json": "b" * 64,
|
||||||
|
"composer.lock": "c" * 64,
|
||||||
|
"package.json": "d" * 64,
|
||||||
|
"package-lock.json": "e" * 64,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
data["fingerprint"] = provenance_fingerprint(data)
|
||||||
|
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
class DeploymentTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
|
||||||
|
self.temp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.temp.cleanup)
|
||||||
|
|
||||||
|
self.root = Path(self.temp.name)
|
||||||
|
self.app = self.root / "app"
|
||||||
|
self.app.mkdir()
|
||||||
|
|
||||||
|
(self.app / "releases").mkdir()
|
||||||
|
|
||||||
|
self.state = self.root / "state"
|
||||||
|
self.state.mkdir(mode=0o700)
|
||||||
|
|
||||||
|
self.releases = ReleaseManager(self.app)
|
||||||
|
self.journal = TransactionJournal(self.state)
|
||||||
|
|
||||||
|
for number, revision in (
|
||||||
|
("1", "a" * 40),
|
||||||
|
("2", "b" * 40),
|
||||||
|
):
|
||||||
|
|
||||||
|
release = self.app / "releases" / number
|
||||||
|
|
||||||
|
(release / "vendor").mkdir(parents=True)
|
||||||
|
(release / "public/build").mkdir(parents=True)
|
||||||
|
|
||||||
|
(release / "vendor/autoload.php").write_text(
|
||||||
|
"<?php\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
(release / "public/build/manifest.json").write_text(
|
||||||
|
"{}"
|
||||||
|
)
|
||||||
|
|
||||||
|
(release / "REVISION").write_text(
|
||||||
|
revision + "\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.releases.activate("1")
|
||||||
|
|
||||||
|
self.old = evidence("a" * 40)
|
||||||
|
self.new = evidence("b" * 40)
|
||||||
|
|
||||||
|
self.provenance = Mock()
|
||||||
|
|
||||||
|
self.provenance.verify.side_effect = (
|
||||||
|
lambda path: self.old
|
||||||
|
if path.name == "1"
|
||||||
|
else self.new
|
||||||
|
)
|
||||||
|
|
||||||
|
self.services = Mock()
|
||||||
|
self.backup = Mock()
|
||||||
|
self.backup.create.return_value = "fixture-backup"
|
||||||
|
self.manifest = {
|
||||||
|
"backup_id": "fixture-backup",
|
||||||
|
"driver": "mysql",
|
||||||
|
"database": "example_db",
|
||||||
|
"username": "example_app",
|
||||||
|
"container": "example-mysql",
|
||||||
|
"identity": "example-server",
|
||||||
|
"filename": "database.sql",
|
||||||
|
"sha256": "c" * 64,
|
||||||
|
"bytes": 100,
|
||||||
|
}
|
||||||
|
|
||||||
|
self.backup.verify.return_value = self.manifest
|
||||||
|
|
||||||
|
self.evidence = BackupEvidence(self.state)
|
||||||
|
|
||||||
|
self.approvals = self.root / "approvals"
|
||||||
|
self.approvals.mkdir(mode=0o700)
|
||||||
|
|
||||||
|
self.approval_store = ApprovalStore(self.approvals)
|
||||||
|
self.operation_guard = OperationGuard(self.approval_store)
|
||||||
|
|
||||||
|
self.health = Mock()
|
||||||
|
self.health.verify.side_effect = (
|
||||||
|
lambda release: {
|
||||||
|
"healthy": True,
|
||||||
|
"release": release,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
self.runtime_check = Mock(return_value=True)
|
||||||
|
self.stopped_check = Mock(return_value=True)
|
||||||
|
|
||||||
|
self.controller = DeploymentController(
|
||||||
|
site="example-absdev-net",
|
||||||
|
lock_path=self.root / ".deployment.lock",
|
||||||
|
releases=self.releases,
|
||||||
|
provenance=self.provenance,
|
||||||
|
journal=self.journal,
|
||||||
|
backup=self.backup,
|
||||||
|
services=self.services,
|
||||||
|
health=self.health,
|
||||||
|
runtime_check=self.runtime_check,
|
||||||
|
stopped_check=self.stopped_check,
|
||||||
|
backup_evidence=self.evidence,
|
||||||
|
operation_guard=self.operation_guard,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def deploy(self):
|
||||||
|
|
||||||
|
return self.controller.deploy("2")
|
||||||
|
|
||||||
|
def test_successful_deployment(self):
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.deploy()["phase"],
|
||||||
|
"VERIFIED",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(self.releases.current(), "2")
|
||||||
|
|
||||||
|
def test_backup_created(self):
|
||||||
|
|
||||||
|
self.deploy()
|
||||||
|
self.backup.create.assert_called_once()
|
||||||
|
|
||||||
|
def test_backup_verified(self):
|
||||||
|
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.backup.verify.assert_called_once_with(
|
||||||
|
"fixture-backup"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_services_quiesced(self):
|
||||||
|
|
||||||
|
self.deploy()
|
||||||
|
self.services.quiesce.assert_called_once()
|
||||||
|
|
||||||
|
def test_services_refreshed(self):
|
||||||
|
|
||||||
|
self.deploy()
|
||||||
|
self.services.refresh.assert_called_once()
|
||||||
|
|
||||||
|
def test_workers_restored(self):
|
||||||
|
|
||||||
|
self.deploy()
|
||||||
|
self.services.resume.assert_called_once()
|
||||||
|
|
||||||
|
def test_health_verified(self):
|
||||||
|
|
||||||
|
self.deploy()
|
||||||
|
self.health.verify.assert_called_once_with("2")
|
||||||
|
|
||||||
|
def test_persistent_verified_transaction(self):
|
||||||
|
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.journal.load()["phase"],
|
||||||
|
"VERIFIED",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_previous_release_preserved(self):
|
||||||
|
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.assertTrue(
|
||||||
|
self.releases.release_path("1").is_dir()
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_existing_transaction_blocks_deployment(self):
|
||||||
|
|
||||||
|
self.journal.create(
|
||||||
|
"example-absdev-net",
|
||||||
|
"1",
|
||||||
|
"2",
|
||||||
|
"b" * 40,
|
||||||
|
self.new["fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.backup.create.assert_not_called()
|
||||||
|
|
||||||
|
def test_concurrent_deployment_rejected(self):
|
||||||
|
|
||||||
|
with DeploymentLock(
|
||||||
|
self.root / ".deployment.lock"
|
||||||
|
):
|
||||||
|
|
||||||
|
with self.assertRaises(LockError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
def test_same_release_rejected(self):
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.controller.deploy("1")
|
||||||
|
|
||||||
|
def test_missing_release_rejected(self):
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.controller.deploy("99")
|
||||||
|
|
||||||
|
self.assertEqual(self.releases.current(), "1")
|
||||||
|
|
||||||
|
def test_provenance_failure_blocks_deployment(self):
|
||||||
|
|
||||||
|
self.provenance.verify.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.backup.create.assert_not_called()
|
||||||
|
|
||||||
|
def test_migration_change_blocks_deployment(self):
|
||||||
|
|
||||||
|
self.new["migrations"][
|
||||||
|
"database/migrations/0002_orders.php"
|
||||||
|
] = "f" * 64
|
||||||
|
|
||||||
|
self.new["fingerprint"] = (
|
||||||
|
provenance_fingerprint(self.new)
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.backup.create.assert_not_called()
|
||||||
|
self.assertEqual(self.releases.current(), "1")
|
||||||
|
|
||||||
|
def test_database_readiness_required(self):
|
||||||
|
|
||||||
|
self.runtime_check.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.backup.create.assert_not_called()
|
||||||
|
|
||||||
|
def test_backup_failure_blocks_activation(self):
|
||||||
|
|
||||||
|
self.backup.create.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.assertEqual(self.releases.current(), "1")
|
||||||
|
self.services.quiesce.assert_not_called()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.journal.load()["phase"],
|
||||||
|
"FAILED",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_backup_verification_failure(self):
|
||||||
|
|
||||||
|
self.backup.verify.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.services.quiesce.assert_not_called()
|
||||||
|
|
||||||
|
def test_worker_shutdown_failure(self):
|
||||||
|
|
||||||
|
self.services.quiesce.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.assertEqual(self.releases.current(), "1")
|
||||||
|
|
||||||
|
def test_worker_state_verification_required(self):
|
||||||
|
|
||||||
|
self.stopped_check.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.assertEqual(self.releases.current(), "1")
|
||||||
|
|
||||||
|
def test_refresh_failure_preserves_transaction(self):
|
||||||
|
|
||||||
|
self.services.refresh.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.journal.load()["phase"],
|
||||||
|
"FAILED",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(self.releases.current(), "2")
|
||||||
|
|
||||||
|
def test_health_failure_requires_explicit_recovery(self):
|
||||||
|
|
||||||
|
self.health.verify.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.journal.load()["phase"],
|
||||||
|
"FAILED",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(self.releases.current(), "2")
|
||||||
|
|
||||||
|
def test_false_health_result_rejected(self):
|
||||||
|
|
||||||
|
self.health.verify.side_effect = None
|
||||||
|
|
||||||
|
self.health.verify.return_value = {
|
||||||
|
"healthy": False,
|
||||||
|
"release": "2",
|
||||||
|
}
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
def test_wrong_health_release_rejected(self):
|
||||||
|
|
||||||
|
self.health.verify.side_effect = None
|
||||||
|
|
||||||
|
self.health.verify.return_value = {
|
||||||
|
"healthy": True,
|
||||||
|
"release": "1",
|
||||||
|
}
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
def test_failed_transaction_blocks_retry(self):
|
||||||
|
|
||||||
|
self.health.verify.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.backup.create.assert_called_once()
|
||||||
|
|
||||||
|
def test_lock_released_after_failure(self):
|
||||||
|
|
||||||
|
self.backup.create.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
with DeploymentLock(
|
||||||
|
self.root / ".deployment.lock"
|
||||||
|
) as lock:
|
||||||
|
|
||||||
|
self.assertTrue(lock.acquired)
|
||||||
|
|
||||||
|
def test_runtime_rechecked_before_activation(self):
|
||||||
|
|
||||||
|
self.runtime_check.side_effect = [True, False]
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.assertEqual(self.releases.current(), "1")
|
||||||
|
|
||||||
|
def test_failure_after_worker_resume_quiesces_again(self):
|
||||||
|
|
||||||
|
self.health.verify.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.services.quiesce.call_count,
|
||||||
|
2,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_recovery_plan_is_read_only(self):
|
||||||
|
|
||||||
|
self.health.verify.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
before = self.journal.load()
|
||||||
|
|
||||||
|
plan = self.controller.recovery_plan()
|
||||||
|
|
||||||
|
self.assertEqual(plan["previous"], "1")
|
||||||
|
self.assertEqual(plan["candidate"], "2")
|
||||||
|
self.assertEqual(plan["current"], "2")
|
||||||
|
|
||||||
|
self.assertFalse(
|
||||||
|
plan["automatic_rollback_allowed"]
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(self.journal.load(), before)
|
||||||
|
|
||||||
|
def test_clear_recovery_plan(self):
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.controller.recovery_plan()["status"],
|
||||||
|
"CLEAR",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def test_backup_evidence_persisted(self):
|
||||||
|
|
||||||
|
result = self.deploy()
|
||||||
|
|
||||||
|
evidence = self.evidence.load(
|
||||||
|
result["transaction_id"]
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
evidence["backup"],
|
||||||
|
self.manifest,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_evidence_exists_before_worker_shutdown(self):
|
||||||
|
|
||||||
|
def check():
|
||||||
|
|
||||||
|
transaction = self.journal.load()
|
||||||
|
|
||||||
|
evidence = self.evidence.load(
|
||||||
|
transaction["transaction_id"]
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
evidence["backup"]["sha256"],
|
||||||
|
self.manifest["sha256"],
|
||||||
|
)
|
||||||
|
|
||||||
|
self.services.quiesce.side_effect = check
|
||||||
|
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
def test_evidence_persistence_failure_blocks_deploy(self):
|
||||||
|
|
||||||
|
self.evidence.create = Mock(
|
||||||
|
side_effect=RuntimeError("write failure")
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.assertEqual(self.releases.current(), "1")
|
||||||
|
self.services.quiesce.assert_not_called()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.journal.load()["phase"],
|
||||||
|
"FAILED",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invalid_manifest_blocks_deploy(self):
|
||||||
|
|
||||||
|
self.manifest["sha256"] = "invalid"
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.services.quiesce.assert_not_called()
|
||||||
|
self.assertEqual(self.releases.current(), "1")
|
||||||
|
|
||||||
|
def test_evidence_readback_failure_blocks_deploy(self):
|
||||||
|
|
||||||
|
self.evidence.load = Mock(
|
||||||
|
side_effect=RuntimeError("read failure")
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.services.quiesce.assert_not_called()
|
||||||
|
|
||||||
|
def test_evidence_survives_health_failure(self):
|
||||||
|
|
||||||
|
self.health.verify.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
transaction = self.journal.load()
|
||||||
|
|
||||||
|
evidence = self.evidence.load(
|
||||||
|
transaction["transaction_id"]
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
evidence["backup"]["backup_id"],
|
||||||
|
"fixture-backup",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_failed_backup_creates_no_evidence(self):
|
||||||
|
|
||||||
|
self.backup.create.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.assertFalse(
|
||||||
|
list(self.state.glob("*.backup.json"))
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_failed_verification_creates_no_evidence(self):
|
||||||
|
|
||||||
|
self.backup.verify.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.assertFalse(
|
||||||
|
list(self.state.glob("*.backup.json"))
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_recovery_plan_contains_backup_evidence(self):
|
||||||
|
|
||||||
|
self.health.verify.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
plan = self.controller.recovery_plan()
|
||||||
|
|
||||||
|
self.assertTrue(plan["backup_evidence_present"])
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
plan["backup_id"],
|
||||||
|
"fixture-backup",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_missing_backup_evidence_reported(self):
|
||||||
|
|
||||||
|
self.backup.create.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
plan = self.controller.recovery_plan()
|
||||||
|
|
||||||
|
self.assertFalse(plan["backup_evidence_present"])
|
||||||
|
self.assertIsNone(plan["backup_id"])
|
||||||
|
|
||||||
|
def test_corrupt_backup_evidence_blocks_recovery(self):
|
||||||
|
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
transaction = self.journal.load()
|
||||||
|
|
||||||
|
self.evidence.path(
|
||||||
|
transaction["transaction_id"]
|
||||||
|
).write_text("{invalid")
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.controller.recovery_plan()
|
||||||
|
|
||||||
|
def test_recovery_does_not_restore_database(self):
|
||||||
|
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.controller.recovery_plan()
|
||||||
|
|
||||||
|
self.backup.restore.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def test_previous_release_revision_bound(self):
|
||||||
|
|
||||||
|
result = self.deploy()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
result["previous_revision"],
|
||||||
|
self.old["revision"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_previous_release_provenance_bound(self):
|
||||||
|
|
||||||
|
result = self.deploy()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
result["previous_provenance"],
|
||||||
|
self.old["fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_previous_evidence_survives_failure(self):
|
||||||
|
|
||||||
|
self.health.verify.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
result = self.journal.load()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
result["previous_provenance"],
|
||||||
|
self.old["fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def test_unfinished_migration_blocks_deployment(self):
|
||||||
|
|
||||||
|
path = self.approvals / (
|
||||||
|
"a" * 32 + ".migration-intent.json"
|
||||||
|
)
|
||||||
|
|
||||||
|
path.touch(mode=0o600)
|
||||||
|
|
||||||
|
with self.assertRaises(DeploymentError):
|
||||||
|
self.deploy()
|
||||||
|
|
||||||
|
self.backup.create.assert_not_called()
|
||||||
|
self.services.quiesce.assert_not_called()
|
||||||
|
|
||||||
|
self.assertEqual(self.releases.current(), "1")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,300 @@
|
|||||||
|
import io
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from core.execution import (
|
||||||
|
ExecutionError,
|
||||||
|
CommandRunner,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ExecutionTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def command(self, source):
|
||||||
|
|
||||||
|
return [
|
||||||
|
sys.executable,
|
||||||
|
"-I",
|
||||||
|
"-c",
|
||||||
|
source,
|
||||||
|
]
|
||||||
|
|
||||||
|
def runner(self, command, timeout=10):
|
||||||
|
|
||||||
|
return CommandRunner(
|
||||||
|
allowed_commands=[command],
|
||||||
|
timeout=timeout,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_successful_execution(self):
|
||||||
|
|
||||||
|
command = self.command(
|
||||||
|
"print('SUCCESS')"
|
||||||
|
)
|
||||||
|
|
||||||
|
output = io.BytesIO()
|
||||||
|
|
||||||
|
self.runner(command)(command, output)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
output.getvalue(),
|
||||||
|
b"SUCCESS\n",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_binary_output_preserved(self):
|
||||||
|
|
||||||
|
command = self.command(
|
||||||
|
"import sys; "
|
||||||
|
"sys.stdout.buffer.write(bytes(range(256)))"
|
||||||
|
)
|
||||||
|
|
||||||
|
output = io.BytesIO()
|
||||||
|
|
||||||
|
self.runner(command)(command, output)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
output.getvalue(),
|
||||||
|
bytes(range(256)),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_large_output_preserved(self):
|
||||||
|
|
||||||
|
command = self.command(
|
||||||
|
"import sys; "
|
||||||
|
"sys.stdout.buffer.write(b'x' * 1048576)"
|
||||||
|
)
|
||||||
|
|
||||||
|
output = io.BytesIO()
|
||||||
|
|
||||||
|
self.runner(command)(command, output)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
len(output.getvalue()),
|
||||||
|
1048576,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_output_to_file(self):
|
||||||
|
|
||||||
|
command = self.command(
|
||||||
|
"print('DATABASE BACKUP')"
|
||||||
|
)
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
|
||||||
|
path = Path(directory) / "backup.sql"
|
||||||
|
|
||||||
|
with path.open("wb") as handle:
|
||||||
|
|
||||||
|
self.runner(command)(
|
||||||
|
command,
|
||||||
|
handle,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
path.read_bytes(),
|
||||||
|
b"DATABASE BACKUP\n",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_nonzero_exit_rejected(self):
|
||||||
|
|
||||||
|
command = self.command(
|
||||||
|
"raise SystemExit(7)"
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(ExecutionError):
|
||||||
|
|
||||||
|
self.runner(command)(
|
||||||
|
command,
|
||||||
|
io.BytesIO(),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_timeout_rejected(self):
|
||||||
|
|
||||||
|
command = self.command(
|
||||||
|
"import time; time.sleep(10)"
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(ExecutionError):
|
||||||
|
|
||||||
|
self.runner(command, timeout=1)(
|
||||||
|
command,
|
||||||
|
io.BytesIO(),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_unauthorised_command_rejected(self):
|
||||||
|
|
||||||
|
allowed = self.command("print('allowed')")
|
||||||
|
denied = self.command("print('denied')")
|
||||||
|
|
||||||
|
with self.assertRaises(ExecutionError):
|
||||||
|
|
||||||
|
self.runner(allowed)(
|
||||||
|
denied,
|
||||||
|
io.BytesIO(),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_modified_arguments_rejected(self):
|
||||||
|
|
||||||
|
command = self.command("print('allowed')")
|
||||||
|
|
||||||
|
runner = self.runner(command)
|
||||||
|
|
||||||
|
modified = command + ["unexpected"]
|
||||||
|
|
||||||
|
with self.assertRaises(ExecutionError):
|
||||||
|
|
||||||
|
runner(modified, io.BytesIO())
|
||||||
|
|
||||||
|
def test_command_string_rejected(self):
|
||||||
|
|
||||||
|
command = self.command("print('allowed')")
|
||||||
|
|
||||||
|
with self.assertRaises(ExecutionError):
|
||||||
|
|
||||||
|
self.runner(command)(
|
||||||
|
"echo unsafe",
|
||||||
|
io.BytesIO(),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_empty_command_rejected(self):
|
||||||
|
|
||||||
|
with self.assertRaises(ExecutionError):
|
||||||
|
|
||||||
|
CommandRunner(
|
||||||
|
allowed_commands=[[]],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_empty_allowlist_rejected(self):
|
||||||
|
|
||||||
|
with self.assertRaises(ExecutionError):
|
||||||
|
|
||||||
|
CommandRunner(allowed_commands=[])
|
||||||
|
|
||||||
|
def test_invalid_argument_rejected(self):
|
||||||
|
|
||||||
|
with self.assertRaises(ExecutionError):
|
||||||
|
|
||||||
|
CommandRunner(
|
||||||
|
allowed_commands=[["echo", 123]]
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_null_argument_rejected(self):
|
||||||
|
|
||||||
|
with self.assertRaises(ExecutionError):
|
||||||
|
|
||||||
|
CommandRunner(
|
||||||
|
allowed_commands=[
|
||||||
|
["echo", "bad\x00argument"]
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invalid_timeout_rejected(self):
|
||||||
|
|
||||||
|
command = self.command("print('test')")
|
||||||
|
|
||||||
|
for timeout in (0, -1, True, 100000):
|
||||||
|
|
||||||
|
with self.subTest(timeout=timeout):
|
||||||
|
|
||||||
|
with self.assertRaises(ExecutionError):
|
||||||
|
|
||||||
|
self.runner(command, timeout)
|
||||||
|
|
||||||
|
def test_stdin_is_disabled(self):
|
||||||
|
|
||||||
|
command = self.command(
|
||||||
|
"import sys; "
|
||||||
|
"print(len(sys.stdin.read()))"
|
||||||
|
)
|
||||||
|
|
||||||
|
output = io.BytesIO()
|
||||||
|
|
||||||
|
self.runner(command)(command, output)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
output.getvalue(),
|
||||||
|
b"0\n",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_shell_metacharacters_not_interpreted(self):
|
||||||
|
|
||||||
|
command = self.command(
|
||||||
|
"import sys; print(sys.argv[1])"
|
||||||
|
) + ["$(echo unsafe); echo unsafe"]
|
||||||
|
|
||||||
|
output = io.BytesIO()
|
||||||
|
|
||||||
|
self.runner(command)(command, output)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
output.getvalue(),
|
||||||
|
b"$(echo unsafe); echo unsafe\n",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_sensitive_stderr_not_disclosed(self):
|
||||||
|
|
||||||
|
command = self.command(
|
||||||
|
"import sys; "
|
||||||
|
"sys.stderr.write('PRIVATE_TEST_VALUE'); "
|
||||||
|
"raise SystemExit(1)"
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(ExecutionError) as error:
|
||||||
|
|
||||||
|
self.runner(command)(
|
||||||
|
command,
|
||||||
|
io.BytesIO(),
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertNotIn(
|
||||||
|
"PRIVATE_TEST_VALUE",
|
||||||
|
str(error.exception),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_allowlist_copied(self):
|
||||||
|
|
||||||
|
command = self.command("print('original')")
|
||||||
|
runner = self.runner(command)
|
||||||
|
|
||||||
|
command[-1] = "print('modified')"
|
||||||
|
|
||||||
|
with self.assertRaises(ExecutionError):
|
||||||
|
|
||||||
|
runner(command, io.BytesIO())
|
||||||
|
|
||||||
|
def test_missing_executable_rejected(self):
|
||||||
|
|
||||||
|
command = [
|
||||||
|
"/nonexistent/absdev-test-executable"
|
||||||
|
]
|
||||||
|
|
||||||
|
with self.assertRaises(ExecutionError):
|
||||||
|
|
||||||
|
self.runner(command)(
|
||||||
|
command,
|
||||||
|
io.BytesIO(),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_failed_output_not_published(self):
|
||||||
|
|
||||||
|
command = self.command(
|
||||||
|
"print('partial backup'); "
|
||||||
|
"raise SystemExit(1)"
|
||||||
|
)
|
||||||
|
|
||||||
|
output = io.BytesIO()
|
||||||
|
|
||||||
|
with self.assertRaises(ExecutionError):
|
||||||
|
|
||||||
|
self.runner(command)(command, output)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
output.getvalue(),
|
||||||
|
b"",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,416 @@
|
|||||||
|
import copy
|
||||||
|
import json
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import Mock
|
||||||
|
|
||||||
|
from core.health import (
|
||||||
|
HealthError,
|
||||||
|
HealthVerifier,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class HealthTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
|
||||||
|
self.config = json.loads(
|
||||||
|
Path("config/site.example.json").read_text()
|
||||||
|
)
|
||||||
|
|
||||||
|
self.http = Mock(return_value=200)
|
||||||
|
self.service = Mock(return_value=True)
|
||||||
|
self.database = Mock(return_value=True)
|
||||||
|
self.redis = Mock(return_value=True)
|
||||||
|
self.assets = Mock(return_value=True)
|
||||||
|
self.release = Mock(return_value="2")
|
||||||
|
self.sleep = Mock()
|
||||||
|
|
||||||
|
def verifier(self, **options):
|
||||||
|
|
||||||
|
return HealthVerifier(
|
||||||
|
self.config,
|
||||||
|
http_probe=self.http,
|
||||||
|
service_probe=self.service,
|
||||||
|
database_probe=self.database,
|
||||||
|
redis_probe=self.redis,
|
||||||
|
asset_probe=self.assets,
|
||||||
|
release_probe=self.release,
|
||||||
|
sleep=self.sleep,
|
||||||
|
**options,
|
||||||
|
)
|
||||||
|
|
||||||
|
def verify(self, **options):
|
||||||
|
|
||||||
|
return self.verifier(**options).verify("2")
|
||||||
|
|
||||||
|
def test_healthy_application(self):
|
||||||
|
|
||||||
|
self.assertTrue(self.verify()["healthy"])
|
||||||
|
|
||||||
|
def test_expected_release(self):
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.verify()["release"], "2"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_all_http_endpoints_checked(self):
|
||||||
|
|
||||||
|
result = self.verify()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
set(result["http"]),
|
||||||
|
{"/", "/up", "/login"},
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.http.call_count, 3
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_all_services_checked(self):
|
||||||
|
|
||||||
|
result = self.verify()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
set(result["services"]),
|
||||||
|
{"php", "web", "queue", "scheduler"},
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.service.call_count, 4
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_database_checked(self):
|
||||||
|
|
||||||
|
self.assertTrue(
|
||||||
|
self.verify()["database"]
|
||||||
|
)
|
||||||
|
|
||||||
|
self.database.assert_called_once()
|
||||||
|
|
||||||
|
def test_redis_checked(self):
|
||||||
|
|
||||||
|
self.assertTrue(
|
||||||
|
self.verify()["redis"]
|
||||||
|
)
|
||||||
|
|
||||||
|
self.redis.assert_called_once()
|
||||||
|
|
||||||
|
def test_assets_checked(self):
|
||||||
|
|
||||||
|
self.assertTrue(
|
||||||
|
self.verify()["assets"]
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assets.assert_called_once()
|
||||||
|
|
||||||
|
def test_origin_is_loopback(self):
|
||||||
|
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
expected = (
|
||||||
|
"http://127.0.0.1:"
|
||||||
|
+ str(self.config["site"]["origin_port"])
|
||||||
|
)
|
||||||
|
|
||||||
|
for call in self.http.call_args_list:
|
||||||
|
|
||||||
|
self.assertTrue(
|
||||||
|
call.args[0].startswith(expected + "/")
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_host_header_passed(self):
|
||||||
|
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
for call in self.http.call_args_list:
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
call.kwargs["host"],
|
||||||
|
self.config["site"]["domain"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_http_timeout_passed(self):
|
||||||
|
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.http.call_args.kwargs["timeout"],
|
||||||
|
self.config["health"]["timeout_seconds"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_http_500_rejected(self):
|
||||||
|
|
||||||
|
self.http.return_value = 500
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_http_404_rejected(self):
|
||||||
|
|
||||||
|
self.http.return_value = 404
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_http_redirect_rejected(self):
|
||||||
|
|
||||||
|
self.http.return_value = 302
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_http_boolean_rejected(self):
|
||||||
|
|
||||||
|
self.http.return_value = True
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_http_string_rejected(self):
|
||||||
|
|
||||||
|
self.http.return_value = "200"
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_http_exception_rejected(self):
|
||||||
|
|
||||||
|
self.http.side_effect = TimeoutError()
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_service_failure_rejected(self):
|
||||||
|
|
||||||
|
self.service.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_database_failure_rejected(self):
|
||||||
|
|
||||||
|
self.database.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_redis_failure_rejected(self):
|
||||||
|
|
||||||
|
self.redis.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_asset_failure_rejected(self):
|
||||||
|
|
||||||
|
self.assets.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_wrong_release_rejected(self):
|
||||||
|
|
||||||
|
self.release.return_value = "1"
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_release_change_during_verification(self):
|
||||||
|
|
||||||
|
self.release.side_effect = ["2", "3"]
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_missing_release_rejected(self):
|
||||||
|
|
||||||
|
self.release.return_value = None
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_non_boolean_database_result_rejected(self):
|
||||||
|
|
||||||
|
self.database.return_value = 1
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_non_boolean_service_result_rejected(self):
|
||||||
|
|
||||||
|
self.service.return_value = "running"
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_retry_recovers_http_failure(self):
|
||||||
|
|
||||||
|
self.http.side_effect = [
|
||||||
|
503, 200, 200, 200
|
||||||
|
]
|
||||||
|
|
||||||
|
result = self.verify(attempts=2)
|
||||||
|
|
||||||
|
self.assertTrue(result["healthy"])
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
result["attempt"], 2
|
||||||
|
)
|
||||||
|
|
||||||
|
self.sleep.assert_called_once_with(2)
|
||||||
|
|
||||||
|
def test_retry_limit_enforced(self):
|
||||||
|
|
||||||
|
self.http.return_value = 503
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verify(attempts=3)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.http.call_count, 3
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.sleep.call_count, 2
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_no_sleep_after_success(self):
|
||||||
|
|
||||||
|
self.verify(attempts=3)
|
||||||
|
|
||||||
|
self.sleep.assert_not_called()
|
||||||
|
|
||||||
|
def test_custom_retry_delay(self):
|
||||||
|
|
||||||
|
self.http.side_effect = [
|
||||||
|
503, 200, 200, 200
|
||||||
|
]
|
||||||
|
|
||||||
|
self.verify(
|
||||||
|
attempts=2,
|
||||||
|
retry_delay=5,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.sleep.assert_called_once_with(5)
|
||||||
|
|
||||||
|
def test_invalid_retry_count_rejected(self):
|
||||||
|
|
||||||
|
for value in (0, -1, 11, True, "3"):
|
||||||
|
|
||||||
|
with self.subTest(value=value):
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verifier(attempts=value)
|
||||||
|
|
||||||
|
def test_invalid_retry_delay_rejected(self):
|
||||||
|
|
||||||
|
for value in (-1, 31, True, "2"):
|
||||||
|
|
||||||
|
with self.subTest(value=value):
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verifier(retry_delay=value)
|
||||||
|
|
||||||
|
def test_invalid_expected_release_rejected(self):
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verifier().verify("../outside")
|
||||||
|
|
||||||
|
self.http.assert_not_called()
|
||||||
|
|
||||||
|
def test_invalid_configuration_rejected(self):
|
||||||
|
|
||||||
|
self.config["health"]["endpoints"] = [
|
||||||
|
"https://example.invalid"
|
||||||
|
]
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verifier()
|
||||||
|
|
||||||
|
def test_configuration_not_mutated(self):
|
||||||
|
|
||||||
|
original = copy.deepcopy(self.config)
|
||||||
|
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
self.assertEqual(self.config, original)
|
||||||
|
|
||||||
|
def test_configuration_snapshot(self):
|
||||||
|
|
||||||
|
verifier = self.verifier()
|
||||||
|
|
||||||
|
self.config["health"]["endpoints"] = ["/changed"]
|
||||||
|
|
||||||
|
result = verifier.verify("2")
|
||||||
|
|
||||||
|
self.assertNotIn(
|
||||||
|
"/changed",
|
||||||
|
result["http"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_sensitive_probe_error_not_disclosed(self):
|
||||||
|
|
||||||
|
self.database.side_effect = RuntimeError(
|
||||||
|
"private-password"
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError) as result:
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
self.assertNotIn(
|
||||||
|
"private-password",
|
||||||
|
str(result.exception),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_custom_service_names(self):
|
||||||
|
|
||||||
|
self.config["docker"]["php_service"] = "application"
|
||||||
|
|
||||||
|
result = self.verify()
|
||||||
|
|
||||||
|
self.assertIn(
|
||||||
|
"application",
|
||||||
|
result["services"],
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertNotIn(
|
||||||
|
"php",
|
||||||
|
result["services"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invalid_probe_rejected(self):
|
||||||
|
|
||||||
|
self.http = None
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verifier()
|
||||||
|
|
||||||
|
def test_no_probes_during_initialisation(self):
|
||||||
|
|
||||||
|
self.verifier()
|
||||||
|
|
||||||
|
for probe in (
|
||||||
|
self.http,
|
||||||
|
self.service,
|
||||||
|
self.database,
|
||||||
|
self.redis,
|
||||||
|
self.assets,
|
||||||
|
self.release,
|
||||||
|
):
|
||||||
|
probe.assert_not_called()
|
||||||
|
|
||||||
|
def test_failed_http_prevents_later_probes(self):
|
||||||
|
|
||||||
|
self.http.return_value = 500
|
||||||
|
|
||||||
|
with self.assertRaises(HealthError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
self.database.assert_not_called()
|
||||||
|
self.assets.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,264 @@
|
|||||||
|
import copy
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from core.inspection_cli import (
|
||||||
|
inventory_report,
|
||||||
|
provisioning_plan,
|
||||||
|
capabilities,
|
||||||
|
)
|
||||||
|
|
||||||
|
from core.configuration import load_config
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
|
||||||
|
|
||||||
|
class InspectionCLITests(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.temp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.temp.cleanup)
|
||||||
|
|
||||||
|
self.root = Path(self.temp.name)
|
||||||
|
self.app = self.root / "app"
|
||||||
|
|
||||||
|
self.app.mkdir()
|
||||||
|
(self.app / "releases").mkdir()
|
||||||
|
|
||||||
|
for release in ("1", "2", "3"):
|
||||||
|
(self.app / "releases" / release).mkdir()
|
||||||
|
|
||||||
|
(self.app / "current").symlink_to("releases/3")
|
||||||
|
|
||||||
|
self.config = load_config(
|
||||||
|
ROOT / "config/site.example.json"
|
||||||
|
)
|
||||||
|
|
||||||
|
def cli(self, *args):
|
||||||
|
return subprocess.run(
|
||||||
|
[
|
||||||
|
sys.executable,
|
||||||
|
str(ROOT / "bin/absdev-deploy"),
|
||||||
|
*args,
|
||||||
|
],
|
||||||
|
cwd=ROOT,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=10,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_inventory(self):
|
||||||
|
result = inventory_report(self.app)
|
||||||
|
|
||||||
|
self.assertEqual(result["inventory"], ["1", "2", "3"])
|
||||||
|
self.assertEqual(result["current"], "3")
|
||||||
|
|
||||||
|
def test_failed_release_inventory(self):
|
||||||
|
(
|
||||||
|
self.app / "releases/1/BAD_RELEASE"
|
||||||
|
).touch()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
inventory_report(self.app)["failed"],
|
||||||
|
["1"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_failed_current_rejected(self):
|
||||||
|
(
|
||||||
|
self.app / "releases/3/BAD_RELEASE"
|
||||||
|
).touch()
|
||||||
|
|
||||||
|
with self.assertRaises(RuntimeError):
|
||||||
|
inventory_report(self.app)
|
||||||
|
|
||||||
|
def test_inventory_is_read_only(self):
|
||||||
|
before = sorted(
|
||||||
|
str(path.relative_to(self.app))
|
||||||
|
for path in self.app.rglob("*")
|
||||||
|
)
|
||||||
|
|
||||||
|
inventory_report(self.app)
|
||||||
|
|
||||||
|
after = sorted(
|
||||||
|
str(path.relative_to(self.app))
|
||||||
|
for path in self.app.rglob("*")
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(before, after)
|
||||||
|
|
||||||
|
def test_inventory_does_not_authorise_execution(self):
|
||||||
|
self.assertFalse(
|
||||||
|
inventory_report(self.app)["execution_permitted"]
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_provisioning_plan(self):
|
||||||
|
result = provisioning_plan(self.config)
|
||||||
|
|
||||||
|
self.assertEqual(result["status"], "PLAN_ONLY")
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
result["site"],
|
||||||
|
self.config["site"]["identifier"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_provisioning_does_not_mutate_config(self):
|
||||||
|
original = copy.deepcopy(self.config)
|
||||||
|
|
||||||
|
provisioning_plan(self.config)
|
||||||
|
|
||||||
|
self.assertEqual(self.config, original)
|
||||||
|
|
||||||
|
def test_provisioning_deterministic(self):
|
||||||
|
self.assertEqual(
|
||||||
|
provisioning_plan(self.config),
|
||||||
|
provisioning_plan(self.config),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_provisioning_execution_disabled(self):
|
||||||
|
result = provisioning_plan(self.config)
|
||||||
|
|
||||||
|
self.assertFalse(result["execution_permitted"])
|
||||||
|
self.assertFalse(result["database_creation_permitted"])
|
||||||
|
|
||||||
|
def test_provisioning_database_driver(self):
|
||||||
|
result = provisioning_plan(self.config)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
result["database"]["driver"],
|
||||||
|
self.config["database"]["driver"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_capabilities(self):
|
||||||
|
result = capabilities()
|
||||||
|
|
||||||
|
self.assertFalse(result["production_ready"])
|
||||||
|
self.assertFalse(result["deployment_execution_enabled"])
|
||||||
|
|
||||||
|
def test_cli_capabilities(self):
|
||||||
|
result = self.cli("capabilities")
|
||||||
|
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
self.assertEqual(json.loads(result.stdout), capabilities())
|
||||||
|
|
||||||
|
def test_cli_inventory(self):
|
||||||
|
result = self.cli(
|
||||||
|
"inventory",
|
||||||
|
"--app",
|
||||||
|
str(self.app),
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
json.loads(result.stdout)["current"],
|
||||||
|
"3",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_cli_provisioning(self):
|
||||||
|
result = self.cli(
|
||||||
|
"provision-plan",
|
||||||
|
"--config",
|
||||||
|
str(ROOT / "config/site.example.json"),
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
json.loads(result.stdout)["status"],
|
||||||
|
"PLAN_ONLY",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_cli_missing_config(self):
|
||||||
|
result = self.cli(
|
||||||
|
"provision-plan",
|
||||||
|
"--config",
|
||||||
|
str(self.root / "missing.json"),
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertNotEqual(result.returncode, 0)
|
||||||
|
|
||||||
|
def test_cli_retention_plan(self):
|
||||||
|
policy = self.root / "retention.json"
|
||||||
|
|
||||||
|
policy.write_text(json.dumps({
|
||||||
|
"inventory": ["1", "2", "3", "4"],
|
||||||
|
"current": "4",
|
||||||
|
"keep": 2,
|
||||||
|
"protected": [],
|
||||||
|
"failed": [],
|
||||||
|
"unresolved": [],
|
||||||
|
}))
|
||||||
|
|
||||||
|
result = self.cli(
|
||||||
|
"retention-plan",
|
||||||
|
"--policy",
|
||||||
|
str(policy),
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
|
||||||
|
report = json.loads(result.stdout)
|
||||||
|
|
||||||
|
self.assertEqual(report["archive_candidates"], ["1", "2"])
|
||||||
|
self.assertFalse(report["execution_permitted"])
|
||||||
|
|
||||||
|
def test_cli_retention_invalid_json(self):
|
||||||
|
policy = self.root / "retention.json"
|
||||||
|
policy.write_text("{invalid")
|
||||||
|
|
||||||
|
result = self.cli(
|
||||||
|
"retention-plan",
|
||||||
|
"--policy",
|
||||||
|
str(policy),
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertNotEqual(result.returncode, 0)
|
||||||
|
|
||||||
|
def test_cli_duplicate_json_fields(self):
|
||||||
|
policy = self.root / "retention.json"
|
||||||
|
policy.write_text('{"current":"1","current":"2"}')
|
||||||
|
|
||||||
|
result = self.cli(
|
||||||
|
"retention-plan",
|
||||||
|
"--policy",
|
||||||
|
str(policy),
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertNotEqual(result.returncode, 0)
|
||||||
|
|
||||||
|
def test_original_validation_preserved(self):
|
||||||
|
result = self.cli(
|
||||||
|
"validate",
|
||||||
|
"--config",
|
||||||
|
str(ROOT / "config/site.example.json"),
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
|
||||||
|
def test_cli_help(self):
|
||||||
|
result = self.cli("--help")
|
||||||
|
|
||||||
|
self.assertEqual(result.returncode, 0)
|
||||||
|
self.assertIn("validate", result.stdout)
|
||||||
|
self.assertIn("inventory", result.stdout)
|
||||||
|
self.assertIn("provision-plan", result.stdout)
|
||||||
|
|
||||||
|
def test_unknown_command_rejected(self):
|
||||||
|
result = self.cli("unknown-command")
|
||||||
|
|
||||||
|
self.assertNotEqual(result.returncode, 0)
|
||||||
|
|
||||||
|
def test_live_deployment_command_disabled(self):
|
||||||
|
result = self.cli("deploy")
|
||||||
|
|
||||||
|
self.assertNotEqual(result.returncode, 0)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
import os
|
||||||
|
import stat
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from core.locking import DeploymentLock, LockError
|
||||||
|
|
||||||
|
|
||||||
|
class LockingTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
|
||||||
|
self.temp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.temp.cleanup)
|
||||||
|
|
||||||
|
self.root = Path(self.temp.name)
|
||||||
|
self.path = self.root / ".deployment.lock"
|
||||||
|
|
||||||
|
def test_lock_acquisition(self):
|
||||||
|
|
||||||
|
with DeploymentLock(self.path) as lock:
|
||||||
|
|
||||||
|
self.assertTrue(lock.acquired)
|
||||||
|
|
||||||
|
def test_lock_file_created(self):
|
||||||
|
|
||||||
|
with DeploymentLock(self.path):
|
||||||
|
|
||||||
|
self.assertTrue(self.path.is_file())
|
||||||
|
|
||||||
|
def test_lock_file_permissions(self):
|
||||||
|
|
||||||
|
with DeploymentLock(self.path):
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
stat.S_IMODE(self.path.stat().st_mode),
|
||||||
|
0o600,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_lock_release(self):
|
||||||
|
|
||||||
|
lock = DeploymentLock(self.path)
|
||||||
|
|
||||||
|
with lock:
|
||||||
|
|
||||||
|
self.assertTrue(lock.acquired)
|
||||||
|
|
||||||
|
self.assertFalse(lock.acquired)
|
||||||
|
|
||||||
|
def test_lock_file_preserved(self):
|
||||||
|
|
||||||
|
with DeploymentLock(self.path):
|
||||||
|
|
||||||
|
original = self.path.stat().st_ino
|
||||||
|
|
||||||
|
self.assertTrue(self.path.exists())
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.path.stat().st_ino,
|
||||||
|
original,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_reacquisition(self):
|
||||||
|
|
||||||
|
with DeploymentLock(self.path):
|
||||||
|
pass
|
||||||
|
|
||||||
|
with DeploymentLock(self.path) as lock:
|
||||||
|
|
||||||
|
self.assertTrue(lock.acquired)
|
||||||
|
|
||||||
|
def test_concurrent_lock_rejected(self):
|
||||||
|
|
||||||
|
with DeploymentLock(self.path):
|
||||||
|
|
||||||
|
with self.assertRaises(LockError):
|
||||||
|
|
||||||
|
with DeploymentLock(self.path):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def test_independent_locks(self):
|
||||||
|
|
||||||
|
with DeploymentLock(self.path):
|
||||||
|
|
||||||
|
with DeploymentLock(
|
||||||
|
self.root / ".other.lock"
|
||||||
|
) as lock:
|
||||||
|
|
||||||
|
self.assertTrue(lock.acquired)
|
||||||
|
|
||||||
|
def test_release_after_exception(self):
|
||||||
|
|
||||||
|
with self.assertRaises(RuntimeError):
|
||||||
|
|
||||||
|
with DeploymentLock(self.path):
|
||||||
|
|
||||||
|
raise RuntimeError("Simulated failure")
|
||||||
|
|
||||||
|
with DeploymentLock(self.path) as lock:
|
||||||
|
|
||||||
|
self.assertTrue(lock.acquired)
|
||||||
|
|
||||||
|
def test_symlink_rejected(self):
|
||||||
|
|
||||||
|
target = self.root / "target"
|
||||||
|
target.touch()
|
||||||
|
|
||||||
|
self.path.symlink_to(target)
|
||||||
|
|
||||||
|
with self.assertRaises(LockError):
|
||||||
|
|
||||||
|
with DeploymentLock(self.path):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def test_dangling_symlink_rejected(self):
|
||||||
|
|
||||||
|
self.path.symlink_to(
|
||||||
|
self.root / "missing"
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(LockError):
|
||||||
|
|
||||||
|
with DeploymentLock(self.path):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def test_hardlink_rejected(self):
|
||||||
|
|
||||||
|
target = self.root / "target"
|
||||||
|
target.touch(mode=0o600)
|
||||||
|
|
||||||
|
os.link(target, self.path)
|
||||||
|
|
||||||
|
with self.assertRaises(LockError):
|
||||||
|
|
||||||
|
with DeploymentLock(self.path):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def test_directory_rejected(self):
|
||||||
|
|
||||||
|
self.path.mkdir()
|
||||||
|
|
||||||
|
with self.assertRaises(LockError):
|
||||||
|
|
||||||
|
with DeploymentLock(self.path):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def test_fifo_rejected(self):
|
||||||
|
|
||||||
|
os.mkfifo(self.path, 0o600)
|
||||||
|
|
||||||
|
with self.assertRaises(LockError):
|
||||||
|
|
||||||
|
with DeploymentLock(self.path):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def test_insecure_permissions_rejected(self):
|
||||||
|
|
||||||
|
self.path.touch()
|
||||||
|
self.path.chmod(0o666)
|
||||||
|
|
||||||
|
with self.assertRaises(LockError):
|
||||||
|
|
||||||
|
with DeploymentLock(self.path):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def test_missing_parent_rejected(self):
|
||||||
|
|
||||||
|
path = self.root / "missing" / ".lock"
|
||||||
|
|
||||||
|
with self.assertRaises(LockError):
|
||||||
|
|
||||||
|
with DeploymentLock(path):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def test_symlink_parent_rejected(self):
|
||||||
|
|
||||||
|
actual = self.root / "actual"
|
||||||
|
actual.mkdir()
|
||||||
|
|
||||||
|
link = self.root / "linked"
|
||||||
|
link.symlink_to(actual)
|
||||||
|
|
||||||
|
with self.assertRaises(LockError):
|
||||||
|
|
||||||
|
with DeploymentLock(link / ".lock"):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def test_relative_path_rejected(self):
|
||||||
|
|
||||||
|
with self.assertRaises(LockError):
|
||||||
|
|
||||||
|
DeploymentLock("relative.lock")
|
||||||
|
|
||||||
|
def test_duplicate_acquire_rejected(self):
|
||||||
|
|
||||||
|
lock = DeploymentLock(self.path)
|
||||||
|
|
||||||
|
with lock:
|
||||||
|
|
||||||
|
with self.assertRaises(LockError):
|
||||||
|
|
||||||
|
lock.acquire()
|
||||||
|
|
||||||
|
def test_release_is_idempotent(self):
|
||||||
|
|
||||||
|
lock = DeploymentLock(self.path)
|
||||||
|
|
||||||
|
lock.acquire()
|
||||||
|
lock.release()
|
||||||
|
lock.release()
|
||||||
|
|
||||||
|
self.assertFalse(lock.acquired)
|
||||||
|
|
||||||
|
def test_cross_process_contention(self):
|
||||||
|
|
||||||
|
code = """
|
||||||
|
import sys
|
||||||
|
from core.locking import DeploymentLock, LockError
|
||||||
|
|
||||||
|
try:
|
||||||
|
with DeploymentLock(sys.argv[1]):
|
||||||
|
sys.exit(0)
|
||||||
|
except LockError:
|
||||||
|
sys.exit(7)
|
||||||
|
"""
|
||||||
|
|
||||||
|
with DeploymentLock(self.path):
|
||||||
|
|
||||||
|
result = subprocess.run(
|
||||||
|
[
|
||||||
|
sys.executable,
|
||||||
|
"-B",
|
||||||
|
"-c",
|
||||||
|
code,
|
||||||
|
str(self.path),
|
||||||
|
],
|
||||||
|
stdin=subprocess.DEVNULL,
|
||||||
|
capture_output=True,
|
||||||
|
timeout=10,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(result.returncode, 7)
|
||||||
|
|
||||||
|
def test_process_exit_releases_lock(self):
|
||||||
|
|
||||||
|
code = """
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from core.locking import DeploymentLock
|
||||||
|
|
||||||
|
lock = DeploymentLock(sys.argv[1])
|
||||||
|
lock.acquire()
|
||||||
|
os._exit(0)
|
||||||
|
"""
|
||||||
|
|
||||||
|
result = subprocess.run(
|
||||||
|
[
|
||||||
|
sys.executable,
|
||||||
|
"-B",
|
||||||
|
"-c",
|
||||||
|
code,
|
||||||
|
str(self.path),
|
||||||
|
],
|
||||||
|
stdin=subprocess.DEVNULL,
|
||||||
|
capture_output=True,
|
||||||
|
timeout=10,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(result.returncode, 0)
|
||||||
|
|
||||||
|
with DeploymentLock(self.path) as lock:
|
||||||
|
|
||||||
|
self.assertTrue(lock.acquired)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,360 @@
|
|||||||
|
import copy
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from datetime import timedelta
|
||||||
|
from unittest.mock import Mock
|
||||||
|
|
||||||
|
import test_approval_store
|
||||||
|
|
||||||
|
from core.migration import MigrationCoordinator, MigrationError
|
||||||
|
from core.locking import DeploymentLock, LockError
|
||||||
|
|
||||||
|
|
||||||
|
class MigrationTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.fixture = test_approval_store.ApprovalStoreTests()
|
||||||
|
self.addCleanup(self.fixture.doCleanups)
|
||||||
|
self.fixture.setUp()
|
||||||
|
self.fixture.save()
|
||||||
|
|
||||||
|
self.root = self.fixture.root
|
||||||
|
|
||||||
|
self.context = Mock(
|
||||||
|
side_effect=lambda: copy.deepcopy(self.fixture.base)
|
||||||
|
)
|
||||||
|
|
||||||
|
self.contain = Mock(return_value=True)
|
||||||
|
self.contained = Mock(return_value=True)
|
||||||
|
self.backup = Mock(return_value=True)
|
||||||
|
|
||||||
|
self.before = ["2026_01_01_000000_create_users"]
|
||||||
|
|
||||||
|
self.after = (
|
||||||
|
self.before + self.fixture.base["pending_migrations"]
|
||||||
|
)
|
||||||
|
|
||||||
|
self.history = Mock(
|
||||||
|
side_effect=[
|
||||||
|
list(self.before),
|
||||||
|
list(self.before),
|
||||||
|
list(self.after),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
self.migrate = Mock(return_value=0)
|
||||||
|
self.application = Mock(return_value=True)
|
||||||
|
self.clock = Mock(return_value=self.fixture.now)
|
||||||
|
|
||||||
|
self.coordinator = MigrationCoordinator(
|
||||||
|
store=self.fixture.store,
|
||||||
|
lock_path=self.root / ".deployment.lock",
|
||||||
|
context_probe=self.context,
|
||||||
|
contain=self.contain,
|
||||||
|
containment_probe=self.contained,
|
||||||
|
backup_probe=self.backup,
|
||||||
|
history_probe=self.history,
|
||||||
|
migration_runner=self.migrate,
|
||||||
|
application_probe=self.application,
|
||||||
|
clock=self.clock,
|
||||||
|
)
|
||||||
|
|
||||||
|
def execute(self):
|
||||||
|
return self.coordinator.execute(
|
||||||
|
self.fixture.identifier,
|
||||||
|
self.fixture.rehearsal,
|
||||||
|
confirmation=self.fixture.approval["confirmation"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_successful_migration(self):
|
||||||
|
self.assertEqual(self.execute()["status"], "MIGRATED")
|
||||||
|
|
||||||
|
def test_runner_called_once(self):
|
||||||
|
self.execute()
|
||||||
|
self.migrate.assert_called_once()
|
||||||
|
|
||||||
|
def test_exact_migration_inventory(self):
|
||||||
|
self.execute()
|
||||||
|
self.migrate.assert_called_once_with(
|
||||||
|
tuple(self.fixture.base["pending_migrations"])
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_approval_consumed_before_execution(self):
|
||||||
|
def check(pending):
|
||||||
|
self.assertTrue(
|
||||||
|
self.fixture.store.consumed_path(
|
||||||
|
self.fixture.identifier
|
||||||
|
).exists()
|
||||||
|
)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
self.migrate.side_effect = check
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
def test_intent_persisted_before_execution(self):
|
||||||
|
def check(pending):
|
||||||
|
record = self.fixture.store.read(
|
||||||
|
self.coordinator.intent_path(self.fixture.identifier)
|
||||||
|
)
|
||||||
|
self.assertEqual(record["status"], "MIGRATION_INTENT")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
self.migrate.side_effect = check
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
def test_wrong_confirmation_rejected(self):
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.coordinator.execute(
|
||||||
|
self.fixture.identifier,
|
||||||
|
self.fixture.rehearsal,
|
||||||
|
confirmation="INVALID",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.contain.assert_not_called()
|
||||||
|
self.migrate.assert_not_called()
|
||||||
|
|
||||||
|
def test_expired_approval_rejected(self):
|
||||||
|
self.clock.return_value += timedelta(hours=25)
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.migrate.assert_not_called()
|
||||||
|
|
||||||
|
def test_context_change_rejected(self):
|
||||||
|
self.fixture.base["database_identity"] = "0" * 64
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.contain.assert_not_called()
|
||||||
|
|
||||||
|
def test_backup_verification_required(self):
|
||||||
|
self.backup.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.migrate.assert_not_called()
|
||||||
|
|
||||||
|
def test_containment_required(self):
|
||||||
|
self.contain.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.migrate.assert_not_called()
|
||||||
|
|
||||||
|
def test_containment_verification_required(self):
|
||||||
|
self.contained.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.migrate.assert_not_called()
|
||||||
|
|
||||||
|
def test_context_rechecked_after_containment(self):
|
||||||
|
original = copy.deepcopy(self.fixture.base)
|
||||||
|
changed = copy.deepcopy(original)
|
||||||
|
changed["database_identity"] = "0" * 64
|
||||||
|
|
||||||
|
self.context.side_effect = [original, changed]
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.migrate.assert_not_called()
|
||||||
|
|
||||||
|
def test_backup_rechecked_after_containment(self):
|
||||||
|
self.backup.side_effect = [True, False]
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.migrate.assert_not_called()
|
||||||
|
|
||||||
|
def test_history_change_before_execution(self):
|
||||||
|
self.history.side_effect = [
|
||||||
|
self.before,
|
||||||
|
self.before + ["unexpected"],
|
||||||
|
]
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.migrate.assert_not_called()
|
||||||
|
|
||||||
|
def test_previously_applied_migration_rejected(self):
|
||||||
|
self.history.side_effect = [self.after]
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.migrate.assert_not_called()
|
||||||
|
|
||||||
|
def test_runner_failure_rejected(self):
|
||||||
|
self.migrate.return_value = 1
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.application.assert_not_called()
|
||||||
|
|
||||||
|
def test_runner_exception_rejected(self):
|
||||||
|
self.migrate.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
def test_missing_applied_migration_rejected(self):
|
||||||
|
self.history.side_effect = [
|
||||||
|
self.before, self.before, self.before
|
||||||
|
]
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
def test_unexpected_migration_rejected(self):
|
||||||
|
self.history.side_effect = [
|
||||||
|
self.before,
|
||||||
|
self.before,
|
||||||
|
self.after + ["unexpected"],
|
||||||
|
]
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
def test_removed_history_rejected(self):
|
||||||
|
self.history.side_effect = [
|
||||||
|
self.before,
|
||||||
|
self.before,
|
||||||
|
self.fixture.base["pending_migrations"],
|
||||||
|
]
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
def test_application_verification_required(self):
|
||||||
|
self.application.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
def test_success_evidence_persisted(self):
|
||||||
|
result = self.execute()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
result,
|
||||||
|
self.fixture.store.read(
|
||||||
|
self.coordinator.result_path(self.fixture.identifier)
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_failure_evidence_persisted(self):
|
||||||
|
self.migrate.return_value = 1
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
result = self.fixture.store.read(
|
||||||
|
self.coordinator.result_path(self.fixture.identifier)
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(result["status"], "FAILED")
|
||||||
|
self.assertTrue(result["manual_recovery_required"])
|
||||||
|
|
||||||
|
def test_failed_execution_cannot_repeat(self):
|
||||||
|
self.migrate.return_value = 1
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.migrate.return_value = 0
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.migrate.assert_called_once()
|
||||||
|
|
||||||
|
def test_successful_execution_cannot_repeat(self):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.migrate.assert_called_once()
|
||||||
|
|
||||||
|
def test_existing_intent_blocks_execution(self):
|
||||||
|
self.coordinator.intent_path(
|
||||||
|
self.fixture.identifier
|
||||||
|
).touch(mode=0o600)
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.migrate.assert_not_called()
|
||||||
|
|
||||||
|
def test_concurrent_deployment_rejected(self):
|
||||||
|
with DeploymentLock(self.root / ".deployment.lock"):
|
||||||
|
with self.assertRaises(LockError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
def test_database_rollback_prohibited(self):
|
||||||
|
self.assertFalse(
|
||||||
|
self.execute()["automatic_database_rollback"]
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_application_activation_not_performed(self):
|
||||||
|
self.assertFalse(self.execute()["application_activated"])
|
||||||
|
|
||||||
|
def test_containment_remains_required(self):
|
||||||
|
self.assertTrue(self.execute()["containment_required"])
|
||||||
|
|
||||||
|
def test_boolean_runner_result_rejected(self):
|
||||||
|
self.migrate.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
def test_approval_expiry_rechecked(self):
|
||||||
|
self.clock.side_effect = [
|
||||||
|
self.fixture.now,
|
||||||
|
self.fixture.now + timedelta(hours=25),
|
||||||
|
]
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.migrate.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def test_different_approval_intent_blocks_migration(self):
|
||||||
|
|
||||||
|
identifier = "0" * 32
|
||||||
|
|
||||||
|
self.fixture.store.path(
|
||||||
|
identifier,
|
||||||
|
".migration-intent.json",
|
||||||
|
).touch(mode=0o600)
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.contain.assert_not_called()
|
||||||
|
self.migrate.assert_not_called()
|
||||||
|
|
||||||
|
def test_other_consumed_approval_blocks_migration(self):
|
||||||
|
|
||||||
|
self.fixture.store.consumed_path(
|
||||||
|
"0" * 32
|
||||||
|
).touch(mode=0o600)
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.migrate.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,345 @@
|
|||||||
|
import copy
|
||||||
|
import json
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
import test_migration_recovery
|
||||||
|
|
||||||
|
from core.approval_store import ApprovalStoreError
|
||||||
|
from core.compatibility import canonical_hash
|
||||||
|
from core.locking import DeploymentLock, LockError
|
||||||
|
from core.operation_guard import OperationGuard, OperationBlocked
|
||||||
|
|
||||||
|
from core.migration_archive import (
|
||||||
|
MigrationArchive,
|
||||||
|
MigrationArchiveError,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class MigrationArchiveTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
|
||||||
|
self.fixture = (
|
||||||
|
test_migration_recovery.MigrationRecoveryTests()
|
||||||
|
)
|
||||||
|
|
||||||
|
self.addCleanup(self.fixture.doCleanups)
|
||||||
|
self.fixture.setUp()
|
||||||
|
|
||||||
|
self.fixture.execute()
|
||||||
|
|
||||||
|
self.store = self.fixture.store
|
||||||
|
self.identifier = self.fixture.identifier
|
||||||
|
|
||||||
|
self.archive = MigrationArchive(
|
||||||
|
site=self.fixture.recovery.site,
|
||||||
|
store=self.store,
|
||||||
|
lock_path=self.fixture.recovery.lock_path,
|
||||||
|
identity_probe=self.fixture.identity,
|
||||||
|
history_probe=self.fixture.history,
|
||||||
|
provenance_probe=self.fixture.provenance,
|
||||||
|
backup_probe=self.fixture.backup,
|
||||||
|
current_probe=self.fixture.current,
|
||||||
|
health_probe=self.fixture.health,
|
||||||
|
writes_enabled_probe=self.fixture.writes_enabled,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.guard = OperationGuard(self.store)
|
||||||
|
|
||||||
|
def plan(self):
|
||||||
|
|
||||||
|
return self.archive.plan(self.identifier)
|
||||||
|
|
||||||
|
def execute(self):
|
||||||
|
|
||||||
|
plan = self.plan()
|
||||||
|
|
||||||
|
return self.archive.execute(
|
||||||
|
self.identifier,
|
||||||
|
confirmation=plan["confirmation"],
|
||||||
|
fingerprint=plan["fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def rewrite(self, suffix, **changes):
|
||||||
|
|
||||||
|
path = self.store.path(
|
||||||
|
self.identifier, suffix
|
||||||
|
)
|
||||||
|
|
||||||
|
record = self.store.read(path)
|
||||||
|
record.update(changes)
|
||||||
|
record.pop("checksum", None)
|
||||||
|
record["checksum"] = canonical_hash(record)
|
||||||
|
|
||||||
|
path.write_text(json.dumps(record))
|
||||||
|
|
||||||
|
def test_valid_archive_plan(self):
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.plan()["status"],
|
||||||
|
"ARCHIVE_READY",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_successful_archive(self):
|
||||||
|
|
||||||
|
result = self.execute()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
result["status"],
|
||||||
|
"ARCHIVED",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_original_records_preserved(self):
|
||||||
|
|
||||||
|
before = {
|
||||||
|
path.name: path.read_bytes()
|
||||||
|
for path in self.store.directory.glob("*.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
for name, content in before.items():
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
(self.store.directory / name).read_bytes(),
|
||||||
|
content,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_guard_blocks_before_archive(self):
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_guard_clears_after_archive(self):
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.guard.require_clear()["status"],
|
||||||
|
"CLEAR",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_consumed_approval_preserved(self):
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.assertTrue(
|
||||||
|
self.store.consumed_path(
|
||||||
|
self.identifier
|
||||||
|
).exists()
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_archived_approval_cannot_be_reused(self):
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
with self.assertRaises(ApprovalStoreError):
|
||||||
|
|
||||||
|
self.fixture.fixture.fixture.consume()
|
||||||
|
|
||||||
|
def test_missing_activation_result_rejected(self):
|
||||||
|
|
||||||
|
self.fixture.recovery.result_path(
|
||||||
|
self.identifier
|
||||||
|
).unlink()
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationArchiveError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_failed_activation_rejected(self):
|
||||||
|
|
||||||
|
self.rewrite(
|
||||||
|
".activation-result.json",
|
||||||
|
status="FAILED",
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationArchiveError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_changed_database_identity_rejected(self):
|
||||||
|
|
||||||
|
self.fixture.identity.return_value = "0" * 64
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationArchiveError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_changed_history_rejected(self):
|
||||||
|
|
||||||
|
self.fixture.history.return_value = ["unexpected"]
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationArchiveError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_changed_provenance_rejected(self):
|
||||||
|
|
||||||
|
self.fixture.provenance.return_value[
|
||||||
|
"fingerprint"
|
||||||
|
] = "0" * 64
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationArchiveError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_wrong_active_release_rejected(self):
|
||||||
|
|
||||||
|
self.fixture.active = "1"
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationArchiveError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_backup_verification_required(self):
|
||||||
|
|
||||||
|
self.fixture.backup.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationArchiveError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_health_verification_required(self):
|
||||||
|
|
||||||
|
self.fixture.health.side_effect = None
|
||||||
|
self.fixture.health.return_value = {
|
||||||
|
"healthy": False,
|
||||||
|
"release": "2",
|
||||||
|
}
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationArchiveError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_writes_enabled_verification_required(self):
|
||||||
|
|
||||||
|
self.fixture.writes_enabled.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationArchiveError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_wrong_confirmation_rejected(self):
|
||||||
|
|
||||||
|
plan = self.plan()
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationArchiveError):
|
||||||
|
|
||||||
|
self.archive.execute(
|
||||||
|
self.identifier,
|
||||||
|
confirmation="INVALID",
|
||||||
|
fingerprint=plan["fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_wrong_fingerprint_rejected(self):
|
||||||
|
|
||||||
|
plan = self.plan()
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationArchiveError):
|
||||||
|
|
||||||
|
self.archive.execute(
|
||||||
|
self.identifier,
|
||||||
|
confirmation=plan["confirmation"],
|
||||||
|
fingerprint="0" * 64,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_duplicate_archival_rejected(self):
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationArchiveError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
def test_corrupted_archive_blocks_operations(self):
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.archive.path(
|
||||||
|
self.identifier
|
||||||
|
).write_text("{invalid")
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_missing_consumption_blocks_operations(self):
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.store.consumed_path(
|
||||||
|
self.identifier
|
||||||
|
).unlink()
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_changed_archived_evidence_blocks_operations(self):
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.rewrite(
|
||||||
|
".activation-result.json",
|
||||||
|
active_release="99",
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_unrelated_intent_still_blocks_operations(self):
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.store.path(
|
||||||
|
"0" * 32,
|
||||||
|
".migration-intent.json",
|
||||||
|
).touch(mode=0o600)
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_archive_publication_failure_blocks_operations(self):
|
||||||
|
|
||||||
|
plan = self.plan()
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"core.approval_store.os.link",
|
||||||
|
side_effect=OSError("publication failure"),
|
||||||
|
):
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationArchiveError):
|
||||||
|
|
||||||
|
self.archive.execute(
|
||||||
|
self.identifier,
|
||||||
|
confirmation=plan["confirmation"],
|
||||||
|
fingerprint=plan["fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_concurrent_operation_rejected(self):
|
||||||
|
|
||||||
|
with DeploymentLock(
|
||||||
|
self.fixture.recovery.lock_path
|
||||||
|
):
|
||||||
|
|
||||||
|
with self.assertRaises(LockError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_archive_marker_alone_does_not_clear_guard(self):
|
||||||
|
|
||||||
|
self.archive.path(
|
||||||
|
self.identifier
|
||||||
|
).touch(mode=0o600)
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_archival_never_reexecutes_migration(self):
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.fixture.fixture.migrate.assert_called_once()
|
||||||
|
|
||||||
|
def test_no_database_restore(self):
|
||||||
|
|
||||||
|
result = self.execute()
|
||||||
|
|
||||||
|
self.assertFalse(result["database_restored"])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,427 @@
|
|||||||
|
import copy
|
||||||
|
import json
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from unittest.mock import Mock
|
||||||
|
|
||||||
|
import test_migration
|
||||||
|
|
||||||
|
from core.compatibility import canonical_hash
|
||||||
|
from core.locking import DeploymentLock, LockError
|
||||||
|
|
||||||
|
from core.migration_recovery import (
|
||||||
|
MigrationRecovery,
|
||||||
|
MigrationRecoveryError,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class MigrationRecoveryTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
|
||||||
|
self.fixture = test_migration.MigrationTests()
|
||||||
|
self.addCleanup(self.fixture.doCleanups)
|
||||||
|
self.fixture.setUp()
|
||||||
|
|
||||||
|
self.identifier = self.fixture.fixture.identifier
|
||||||
|
self.store = self.fixture.fixture.store
|
||||||
|
|
||||||
|
self.migration_result = self.fixture.execute()
|
||||||
|
|
||||||
|
self.identity = Mock(
|
||||||
|
return_value=self.migration_result[
|
||||||
|
"database_identity"
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
self.history = Mock(
|
||||||
|
return_value=list(self.fixture.after)
|
||||||
|
)
|
||||||
|
|
||||||
|
self.provenance = Mock(
|
||||||
|
return_value={
|
||||||
|
"revision": self.fixture.fixture.base["revision"],
|
||||||
|
"fingerprint": self.fixture.fixture.base["provenance"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
self.backup = Mock(return_value=True)
|
||||||
|
self.contain = Mock(return_value=True)
|
||||||
|
self.contained = Mock(return_value=True)
|
||||||
|
|
||||||
|
self.active = "1"
|
||||||
|
|
||||||
|
self.current = Mock(
|
||||||
|
side_effect=lambda: self.active
|
||||||
|
)
|
||||||
|
|
||||||
|
def activate(release):
|
||||||
|
self.active = release
|
||||||
|
return True
|
||||||
|
|
||||||
|
self.activate = Mock(side_effect=activate)
|
||||||
|
self.refresh = Mock(return_value=True)
|
||||||
|
self.ready = Mock(return_value=True)
|
||||||
|
|
||||||
|
self.release_containment = Mock(return_value=True)
|
||||||
|
self.writes_enabled = Mock(return_value=True)
|
||||||
|
|
||||||
|
self.health = Mock(
|
||||||
|
side_effect=lambda release: {
|
||||||
|
"healthy": True,
|
||||||
|
"release": release,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
self.recovery = MigrationRecovery(
|
||||||
|
site=self.fixture.fixture.base["site"],
|
||||||
|
store=self.store,
|
||||||
|
lock_path=self.fixture.root / ".deployment.lock",
|
||||||
|
identity_probe=self.identity,
|
||||||
|
history_probe=self.history,
|
||||||
|
provenance_probe=self.provenance,
|
||||||
|
backup_probe=self.backup,
|
||||||
|
contain=self.contain,
|
||||||
|
containment_probe=self.contained,
|
||||||
|
current_probe=self.current,
|
||||||
|
activate=self.activate,
|
||||||
|
refresh=self.refresh,
|
||||||
|
readiness_probe=self.ready,
|
||||||
|
release_containment=self.release_containment,
|
||||||
|
writes_enabled_probe=self.writes_enabled,
|
||||||
|
health_probe=self.health,
|
||||||
|
)
|
||||||
|
|
||||||
|
def plan(self):
|
||||||
|
return self.recovery.inspect(self.identifier)
|
||||||
|
|
||||||
|
def execute(self):
|
||||||
|
plan = self.plan()
|
||||||
|
|
||||||
|
return self.recovery.execute(
|
||||||
|
self.identifier,
|
||||||
|
confirmation=plan["confirmation"],
|
||||||
|
fingerprint=plan["plan_fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def rewrite(self, path, record):
|
||||||
|
|
||||||
|
data = copy.deepcopy(record)
|
||||||
|
data.pop("checksum", None)
|
||||||
|
data["checksum"] = canonical_hash(data)
|
||||||
|
|
||||||
|
path.write_text(json.dumps(data))
|
||||||
|
|
||||||
|
def test_valid_recovery_plan(self):
|
||||||
|
self.assertEqual(
|
||||||
|
self.plan()["status"],
|
||||||
|
"FORWARD_ACTIVATION_READY",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_plan_is_read_only(self):
|
||||||
|
|
||||||
|
before = {
|
||||||
|
path.name: path.read_bytes()
|
||||||
|
for path in self.store.directory.glob("*.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
after = {
|
||||||
|
path.name: path.read_bytes()
|
||||||
|
for path in self.store.directory.glob("*.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
self.assertEqual(before, after)
|
||||||
|
self.activate.assert_not_called()
|
||||||
|
self.release_containment.assert_not_called()
|
||||||
|
|
||||||
|
def test_successful_activation(self):
|
||||||
|
|
||||||
|
result = self.execute()
|
||||||
|
|
||||||
|
self.assertEqual(result["status"], "VERIFIED")
|
||||||
|
self.assertEqual(self.active, "2")
|
||||||
|
|
||||||
|
def test_migration_never_repeated(self):
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
self.fixture.migrate.assert_called_once()
|
||||||
|
|
||||||
|
def test_wrong_confirmation(self):
|
||||||
|
|
||||||
|
plan = self.plan()
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.recovery.execute(
|
||||||
|
self.identifier,
|
||||||
|
confirmation="INVALID",
|
||||||
|
fingerprint=plan["plan_fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
self.activate.assert_not_called()
|
||||||
|
|
||||||
|
def test_wrong_fingerprint(self):
|
||||||
|
|
||||||
|
plan = self.plan()
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.recovery.execute(
|
||||||
|
self.identifier,
|
||||||
|
confirmation=plan["confirmation"],
|
||||||
|
fingerprint="0" * 64,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.activate.assert_not_called()
|
||||||
|
|
||||||
|
def test_changed_database_identity(self):
|
||||||
|
|
||||||
|
self.identity.return_value = "0" * 64
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_changed_migration_history(self):
|
||||||
|
|
||||||
|
self.history.return_value = ["unexpected"]
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_changed_candidate_revision(self):
|
||||||
|
|
||||||
|
self.provenance.return_value["revision"] = "0" * 40
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_changed_candidate_fingerprint(self):
|
||||||
|
|
||||||
|
self.provenance.return_value["fingerprint"] = "0" * 64
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_backup_verification_required(self):
|
||||||
|
|
||||||
|
self.backup.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_missing_result_rejected(self):
|
||||||
|
|
||||||
|
self.fixture.coordinator.result_path(
|
||||||
|
self.identifier
|
||||||
|
).unlink()
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_corrupted_result_rejected(self):
|
||||||
|
|
||||||
|
self.fixture.coordinator.result_path(
|
||||||
|
self.identifier
|
||||||
|
).write_text("{invalid")
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_failed_migration_rejected(self):
|
||||||
|
|
||||||
|
path = self.fixture.coordinator.result_path(
|
||||||
|
self.identifier
|
||||||
|
)
|
||||||
|
|
||||||
|
record = self.store.read(path)
|
||||||
|
record["status"] = "FAILED"
|
||||||
|
|
||||||
|
self.rewrite(path, record)
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_inconsistent_history_evidence_rejected(self):
|
||||||
|
|
||||||
|
path = self.fixture.coordinator.result_path(
|
||||||
|
self.identifier
|
||||||
|
)
|
||||||
|
|
||||||
|
record = self.store.read(path)
|
||||||
|
record["history_after"] = ["unexpected"]
|
||||||
|
|
||||||
|
self.rewrite(path, record)
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_wrong_site_rejected(self):
|
||||||
|
|
||||||
|
self.recovery.site = "different-site"
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_consumption_evidence_required(self):
|
||||||
|
|
||||||
|
self.store.consumed_path(
|
||||||
|
self.identifier
|
||||||
|
).unlink()
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_containment_required(self):
|
||||||
|
|
||||||
|
self.contained.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.activate.assert_not_called()
|
||||||
|
|
||||||
|
def test_activation_intent_persisted_first(self):
|
||||||
|
|
||||||
|
def check(release):
|
||||||
|
|
||||||
|
path = self.recovery.intent_path(
|
||||||
|
self.identifier
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertTrue(path.exists())
|
||||||
|
self.active = release
|
||||||
|
return True
|
||||||
|
|
||||||
|
self.activate.side_effect = check
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
def test_activation_failure_preserves_containment(self):
|
||||||
|
|
||||||
|
self.activate.return_value = False
|
||||||
|
self.activate.side_effect = None
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.release_containment.assert_not_called()
|
||||||
|
|
||||||
|
def test_refresh_failure_preserves_containment(self):
|
||||||
|
|
||||||
|
self.refresh.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.release_containment.assert_not_called()
|
||||||
|
|
||||||
|
def test_readiness_required_before_reopening(self):
|
||||||
|
|
||||||
|
self.ready.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.release_containment.assert_not_called()
|
||||||
|
|
||||||
|
def test_failed_health_reestablishes_containment(self):
|
||||||
|
|
||||||
|
self.health.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.assertGreaterEqual(
|
||||||
|
self.contain.call_count,
|
||||||
|
2,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_reopening_must_be_verified(self):
|
||||||
|
|
||||||
|
self.writes_enabled.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.health.assert_not_called()
|
||||||
|
|
||||||
|
def test_existing_activation_intent_blocks_retry(self):
|
||||||
|
|
||||||
|
self.recovery.intent_path(
|
||||||
|
self.identifier
|
||||||
|
).touch(mode=0o600)
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.activate.assert_not_called()
|
||||||
|
|
||||||
|
def test_successful_execution_cannot_repeat(self):
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.activate.assert_called_once()
|
||||||
|
|
||||||
|
def test_concurrent_operation_rejected(self):
|
||||||
|
|
||||||
|
with DeploymentLock(
|
||||||
|
self.fixture.root / ".deployment.lock"
|
||||||
|
):
|
||||||
|
|
||||||
|
with self.assertRaises(LockError):
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
def test_original_migration_evidence_preserved(self):
|
||||||
|
|
||||||
|
path = self.fixture.coordinator.result_path(
|
||||||
|
self.identifier
|
||||||
|
)
|
||||||
|
|
||||||
|
before = path.read_bytes()
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.assertEqual(path.read_bytes(), before)
|
||||||
|
|
||||||
|
def test_database_rollback_prohibited(self):
|
||||||
|
|
||||||
|
result = self.execute()
|
||||||
|
|
||||||
|
self.assertFalse(
|
||||||
|
result["database_restored"]
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertFalse(
|
||||||
|
result["migration_reexecuted"]
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_final_result_persisted(self):
|
||||||
|
|
||||||
|
result = self.execute()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.store.read(
|
||||||
|
self.recovery.result_path(self.identifier)
|
||||||
|
),
|
||||||
|
result,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_failure_result_persisted(self):
|
||||||
|
|
||||||
|
self.refresh.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(MigrationRecoveryError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
result = self.store.read(
|
||||||
|
self.recovery.result_path(self.identifier)
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(result["status"], "FAILED")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from core.approval_store import ApprovalStore
|
||||||
|
from core.operation_guard import OperationGuard, OperationBlocked
|
||||||
|
|
||||||
|
|
||||||
|
class OperationGuardTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.temp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.temp.cleanup)
|
||||||
|
|
||||||
|
self.root = Path(self.temp.name)
|
||||||
|
self.store = ApprovalStore(self.root)
|
||||||
|
self.guard = OperationGuard(self.store)
|
||||||
|
|
||||||
|
self.identifier = "a" * 32
|
||||||
|
|
||||||
|
def marker(self, suffix):
|
||||||
|
path = self.root / (self.identifier + suffix)
|
||||||
|
path.touch(mode=0o600)
|
||||||
|
return path
|
||||||
|
|
||||||
|
def test_empty_store_clear(self):
|
||||||
|
self.assertEqual(self.guard.inspect()["status"], "CLEAR")
|
||||||
|
|
||||||
|
def test_empty_store_permits_operations(self):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_unused_approval_permitted(self):
|
||||||
|
import test_approval_store
|
||||||
|
|
||||||
|
fixture = test_approval_store.ApprovalStoreTests()
|
||||||
|
self.addCleanup(fixture.doCleanups)
|
||||||
|
fixture.setUp()
|
||||||
|
fixture.save()
|
||||||
|
|
||||||
|
OperationGuard(fixture.store).require_clear()
|
||||||
|
|
||||||
|
def test_migration_intent_blocks(self):
|
||||||
|
self.marker(".migration-intent.json")
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_consumed_approval_blocks(self):
|
||||||
|
self.marker(".consumed.json")
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_migration_result_blocks_until_archived(self):
|
||||||
|
self.marker(".migration-result.json")
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_activation_intent_blocks(self):
|
||||||
|
self.marker(".activation-intent.json")
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_activation_result_blocks_until_archived(self):
|
||||||
|
self.marker(".activation-result.json")
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_successful_result_does_not_bypass_guard(self):
|
||||||
|
path = self.marker(".activation-result.json")
|
||||||
|
path.write_text('{"status":"VERIFIED"}')
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_corrupted_record_blocks(self):
|
||||||
|
path = self.marker(".migration-intent.json")
|
||||||
|
path.write_text("{invalid")
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_dangling_symlink_blocks(self):
|
||||||
|
path = self.root / (
|
||||||
|
self.identifier + ".migration-intent.json"
|
||||||
|
)
|
||||||
|
|
||||||
|
path.symlink_to(self.root / "missing")
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_directory_marker_blocks(self):
|
||||||
|
path = self.root / (
|
||||||
|
self.identifier + ".migration-result.json"
|
||||||
|
)
|
||||||
|
|
||||||
|
path.mkdir()
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_invalid_identifier_blocks(self):
|
||||||
|
(self.root / "invalid.migration-intent.json").touch()
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_temporary_publication_record_blocks(self):
|
||||||
|
(self.root / ".approval-tmp-interrupted").touch()
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_unknown_json_record_blocks(self):
|
||||||
|
(self.root / "unexpected.json").touch()
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_multiple_operations_reported(self):
|
||||||
|
self.marker(".migration-intent.json")
|
||||||
|
self.marker(".consumed.json")
|
||||||
|
|
||||||
|
result = self.guard.inspect()
|
||||||
|
|
||||||
|
self.assertEqual(result["status"], "BLOCKED")
|
||||||
|
self.assertEqual(len(result["blockers"]), 2)
|
||||||
|
|
||||||
|
def test_deterministic_report(self):
|
||||||
|
self.marker(".migration-result.json")
|
||||||
|
self.marker(".consumed.json")
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.guard.inspect(),
|
||||||
|
self.guard.inspect(),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_read_only_inspection(self):
|
||||||
|
path = self.marker(".migration-intent.json")
|
||||||
|
path.write_text("original")
|
||||||
|
|
||||||
|
before = path.read_bytes()
|
||||||
|
self.guard.inspect()
|
||||||
|
|
||||||
|
self.assertEqual(path.read_bytes(), before)
|
||||||
|
|
||||||
|
def test_lock_file_ignored(self):
|
||||||
|
(self.root / ".approval.lock").touch(mode=0o600)
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_insecure_directory_blocks(self):
|
||||||
|
self.root.chmod(0o755)
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
def test_missing_directory_blocks(self):
|
||||||
|
self.root.rename(self.root.with_name(
|
||||||
|
self.root.name + "-moved"
|
||||||
|
))
|
||||||
|
|
||||||
|
moved = self.root.with_name(
|
||||||
|
self.root.name + "-moved"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.addCleanup(moved.rmdir)
|
||||||
|
|
||||||
|
with self.assertRaises(OperationBlocked):
|
||||||
|
self.guard.require_clear()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
import copy
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from core.configuration import load_config
|
||||||
|
from core.preflight import PreflightError, site_preflight
|
||||||
|
from core.inspection_cli import provisioning_plan
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
|
||||||
|
|
||||||
|
class PreflightTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.temp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.temp.cleanup)
|
||||||
|
|
||||||
|
self.root = Path(self.temp.name)
|
||||||
|
|
||||||
|
self.config = load_config(
|
||||||
|
ROOT / "config/site.example.json"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.other = copy.deepcopy(self.config)
|
||||||
|
|
||||||
|
self.other["site"].update({
|
||||||
|
"identifier": "other-absdev-net",
|
||||||
|
"domain": "other.absdev.net",
|
||||||
|
"root": "/opt/laravel-sites/other-absdev-net",
|
||||||
|
"origin_port": 8198,
|
||||||
|
})
|
||||||
|
|
||||||
|
self.other["docker"]["project"] = (
|
||||||
|
"site-other-absdev-net"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.other["database"]["name"] = "other_db"
|
||||||
|
self.other["database"]["username"] = "other_app"
|
||||||
|
|
||||||
|
def preflight(self, registry=None):
|
||||||
|
return site_preflight(
|
||||||
|
self.config,
|
||||||
|
[] if registry is None else registry,
|
||||||
|
)
|
||||||
|
|
||||||
|
def write_json(self, name, data):
|
||||||
|
path = self.root / name
|
||||||
|
path.write_text(json.dumps(data))
|
||||||
|
return path
|
||||||
|
|
||||||
|
def cli(self, *args):
|
||||||
|
return subprocess.run(
|
||||||
|
[
|
||||||
|
sys.executable,
|
||||||
|
str(ROOT / "bin/absdev-deploy"),
|
||||||
|
*map(str, args),
|
||||||
|
],
|
||||||
|
cwd=ROOT,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=10,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_valid_preflight(self):
|
||||||
|
result = self.preflight()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
result["status"],
|
||||||
|
"STATIC_PREFLIGHT_PASSED",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_valid_existing_registry(self):
|
||||||
|
result = self.preflight([self.other])
|
||||||
|
|
||||||
|
self.assertEqual(result["site_count"], 2)
|
||||||
|
|
||||||
|
def test_duplicate_site_rejected(self):
|
||||||
|
with self.assertRaises(PreflightError):
|
||||||
|
self.preflight([self.config])
|
||||||
|
|
||||||
|
def test_port_conflict_rejected(self):
|
||||||
|
self.other["site"]["origin_port"] = (
|
||||||
|
self.config["site"]["origin_port"]
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(PreflightError):
|
||||||
|
self.preflight([self.other])
|
||||||
|
|
||||||
|
def test_domain_conflict_rejected(self):
|
||||||
|
self.other["site"]["domain"] = (
|
||||||
|
self.config["site"]["domain"]
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(PreflightError):
|
||||||
|
self.preflight([self.other])
|
||||||
|
|
||||||
|
def test_database_conflict_rejected(self):
|
||||||
|
self.other["database"]["name"] = (
|
||||||
|
self.config["database"]["name"]
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(PreflightError):
|
||||||
|
self.preflight([self.other])
|
||||||
|
|
||||||
|
def test_username_conflict_rejected(self):
|
||||||
|
self.other["database"]["username"] = (
|
||||||
|
self.config["database"]["username"]
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(PreflightError):
|
||||||
|
self.preflight([self.other])
|
||||||
|
|
||||||
|
def test_untrusted_site_root_rejected(self):
|
||||||
|
self.config["site"]["root"] = "/etc"
|
||||||
|
|
||||||
|
with self.assertRaises(PreflightError):
|
||||||
|
self.preflight()
|
||||||
|
|
||||||
|
def test_invalid_registry_rejected(self):
|
||||||
|
with self.assertRaises(PreflightError):
|
||||||
|
self.preflight("invalid")
|
||||||
|
|
||||||
|
def test_deterministic_preflight(self):
|
||||||
|
self.assertEqual(
|
||||||
|
self.preflight(),
|
||||||
|
self.preflight(),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_input_not_mutated(self):
|
||||||
|
original = copy.deepcopy(self.config)
|
||||||
|
|
||||||
|
self.preflight([self.other])
|
||||||
|
|
||||||
|
self.assertEqual(self.config, original)
|
||||||
|
|
||||||
|
def test_runtime_not_verified(self):
|
||||||
|
self.assertFalse(
|
||||||
|
self.preflight()["runtime_verified"]
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_execution_disabled(self):
|
||||||
|
self.assertFalse(
|
||||||
|
self.preflight()["execution_permitted"]
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_registry_completeness_not_assumed(self):
|
||||||
|
self.assertFalse(
|
||||||
|
self.preflight()["registry_completeness_verified"]
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_provision_plan_enforces_site_policy(self):
|
||||||
|
self.config["database"]["username"] = "root"
|
||||||
|
|
||||||
|
with self.assertRaises(RuntimeError):
|
||||||
|
provisioning_plan(self.config)
|
||||||
|
|
||||||
|
def test_provision_plan_reports_static_validation(self):
|
||||||
|
result = provisioning_plan(self.config)
|
||||||
|
|
||||||
|
self.assertTrue(result["static_policy_verified"])
|
||||||
|
|
||||||
|
def test_cli_site_policy(self):
|
||||||
|
config = self.write_json(
|
||||||
|
"site.json",
|
||||||
|
self.config,
|
||||||
|
)
|
||||||
|
|
||||||
|
result = self.cli(
|
||||||
|
"site-policy",
|
||||||
|
"--config",
|
||||||
|
config,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
json.loads(result.stdout)["status"],
|
||||||
|
"VALID",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_cli_registry_validation(self):
|
||||||
|
registry = self.write_json(
|
||||||
|
"registry.json",
|
||||||
|
[self.config, self.other],
|
||||||
|
)
|
||||||
|
|
||||||
|
result = self.cli(
|
||||||
|
"registry-validate",
|
||||||
|
"--registry",
|
||||||
|
registry,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
json.loads(result.stdout)["site_count"],
|
||||||
|
2,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_cli_registry_conflict(self):
|
||||||
|
registry = self.write_json(
|
||||||
|
"registry.json",
|
||||||
|
[self.config, self.config],
|
||||||
|
)
|
||||||
|
|
||||||
|
result = self.cli(
|
||||||
|
"registry-validate",
|
||||||
|
"--registry",
|
||||||
|
registry,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertNotEqual(result.returncode, 0)
|
||||||
|
|
||||||
|
def test_cli_preflight(self):
|
||||||
|
config = self.write_json("site.json", self.config)
|
||||||
|
registry = self.write_json("registry.json", [self.other])
|
||||||
|
|
||||||
|
result = self.cli(
|
||||||
|
"preflight",
|
||||||
|
"--config",
|
||||||
|
config,
|
||||||
|
"--registry",
|
||||||
|
registry,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
|
||||||
|
report = json.loads(result.stdout)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
report["status"],
|
||||||
|
"STATIC_PREFLIGHT_PASSED",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertFalse(report["execution_permitted"])
|
||||||
|
|
||||||
|
def test_cli_preflight_requires_registry(self):
|
||||||
|
config = self.write_json("site.json", self.config)
|
||||||
|
|
||||||
|
result = self.cli(
|
||||||
|
"preflight",
|
||||||
|
"--config",
|
||||||
|
config,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertNotEqual(result.returncode, 0)
|
||||||
|
|
||||||
|
def test_cli_missing_registry_rejected(self):
|
||||||
|
result = self.cli(
|
||||||
|
"registry-validate",
|
||||||
|
"--registry",
|
||||||
|
self.root / "missing.json",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertNotEqual(result.returncode, 0)
|
||||||
|
|
||||||
|
def test_cli_capabilities_updated(self):
|
||||||
|
result = self.cli("capabilities")
|
||||||
|
|
||||||
|
self.assertEqual(result.returncode, 0)
|
||||||
|
|
||||||
|
report = json.loads(result.stdout)
|
||||||
|
|
||||||
|
for command in (
|
||||||
|
"site-policy",
|
||||||
|
"registry-validate",
|
||||||
|
"preflight",
|
||||||
|
):
|
||||||
|
self.assertIn(command, report["commands"])
|
||||||
|
|
||||||
|
def test_cli_provisioning_rejects_unsafe_site(self):
|
||||||
|
self.config["site"]["root"] = "/etc"
|
||||||
|
|
||||||
|
config = self.write_json(
|
||||||
|
"site.json",
|
||||||
|
self.config,
|
||||||
|
)
|
||||||
|
|
||||||
|
result = self.cli(
|
||||||
|
"provision-plan",
|
||||||
|
"--config",
|
||||||
|
config,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertNotEqual(result.returncode, 0)
|
||||||
|
|
||||||
|
def test_mutating_commands_remain_unavailable(self):
|
||||||
|
for command in (
|
||||||
|
"deploy",
|
||||||
|
"migrate",
|
||||||
|
"rollback",
|
||||||
|
"restore",
|
||||||
|
"provision",
|
||||||
|
"delete",
|
||||||
|
):
|
||||||
|
with self.subTest(command=command):
|
||||||
|
self.assertNotEqual(
|
||||||
|
self.cli(command).returncode,
|
||||||
|
0,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from core.provenance import (
|
||||||
|
ProvenanceError,
|
||||||
|
ProvenanceVerifier,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ProvenanceTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
|
||||||
|
self.temp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.temp.cleanup)
|
||||||
|
|
||||||
|
self.root = Path(self.temp.name)
|
||||||
|
|
||||||
|
self.repository = self.root / "repository"
|
||||||
|
self.repository.mkdir()
|
||||||
|
|
||||||
|
self.release = self.root / "release"
|
||||||
|
|
||||||
|
self.git("init", "-q")
|
||||||
|
self.git("config", "user.name", "Test User")
|
||||||
|
self.git("config", "user.email", "[email protected]")
|
||||||
|
|
||||||
|
files = {
|
||||||
|
"composer.json": "{}",
|
||||||
|
"composer.lock": "{}",
|
||||||
|
"package.json": "{}",
|
||||||
|
"package-lock.json": "{}",
|
||||||
|
"database/migrations/0001_create_users.php":
|
||||||
|
"<?php // users\n",
|
||||||
|
"database/migrations/0002_create_orders.php":
|
||||||
|
"<?php // orders\n",
|
||||||
|
}
|
||||||
|
|
||||||
|
for name, content in files.items():
|
||||||
|
|
||||||
|
path = self.repository / name
|
||||||
|
|
||||||
|
path.parent.mkdir(
|
||||||
|
parents=True,
|
||||||
|
exist_ok=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
path.write_text(content)
|
||||||
|
|
||||||
|
self.git("add", ".")
|
||||||
|
self.git("commit", "-qm", "Test release")
|
||||||
|
|
||||||
|
self.revision = self.git(
|
||||||
|
"rev-parse", "HEAD"
|
||||||
|
).strip()
|
||||||
|
|
||||||
|
shutil.copytree(
|
||||||
|
self.repository,
|
||||||
|
self.release,
|
||||||
|
ignore=shutil.ignore_patterns(".git"),
|
||||||
|
)
|
||||||
|
|
||||||
|
(self.release / "REVISION").write_text(
|
||||||
|
self.revision + "\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.verifier = ProvenanceVerifier(
|
||||||
|
self.repository
|
||||||
|
)
|
||||||
|
|
||||||
|
def git(self, *args):
|
||||||
|
|
||||||
|
return subprocess.check_output(
|
||||||
|
[
|
||||||
|
"git",
|
||||||
|
"-C",
|
||||||
|
str(self.repository),
|
||||||
|
*args,
|
||||||
|
],
|
||||||
|
stdin=subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.DEVNULL,
|
||||||
|
text=True,
|
||||||
|
timeout=20,
|
||||||
|
)
|
||||||
|
|
||||||
|
def verify(self):
|
||||||
|
|
||||||
|
return self.verifier.verify(self.release)
|
||||||
|
|
||||||
|
def test_valid_release(self):
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.verify()["revision"],
|
||||||
|
self.revision,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_migration_inventory(self):
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
len(self.verify()["migrations"]),
|
||||||
|
2,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_dependency_inventory(self):
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
len(self.verify()["dependencies"]),
|
||||||
|
4,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_deterministic_fingerprint(self):
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.verify()["fingerprint"],
|
||||||
|
self.verify()["fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_fingerprint_format(self):
|
||||||
|
|
||||||
|
self.assertRegex(
|
||||||
|
self.verify()["fingerprint"],
|
||||||
|
r"^[a-f0-9]{64}$",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_modified_migration_rejected(self):
|
||||||
|
|
||||||
|
path = (
|
||||||
|
self.release
|
||||||
|
/ "database/migrations/0001_create_users.php"
|
||||||
|
)
|
||||||
|
|
||||||
|
path.write_text("modified")
|
||||||
|
|
||||||
|
with self.assertRaises(ProvenanceError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_missing_migration_rejected(self):
|
||||||
|
|
||||||
|
(
|
||||||
|
self.release
|
||||||
|
/ "database/migrations/0001_create_users.php"
|
||||||
|
).unlink()
|
||||||
|
|
||||||
|
with self.assertRaises(ProvenanceError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_unexpected_migration_rejected(self):
|
||||||
|
|
||||||
|
(
|
||||||
|
self.release
|
||||||
|
/ "database/migrations/unexpected.php"
|
||||||
|
).write_text("unexpected")
|
||||||
|
|
||||||
|
with self.assertRaises(ProvenanceError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_modified_composer_manifest_rejected(self):
|
||||||
|
|
||||||
|
(self.release / "composer.json").write_text("changed")
|
||||||
|
|
||||||
|
with self.assertRaises(ProvenanceError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_modified_composer_lock_rejected(self):
|
||||||
|
|
||||||
|
(self.release / "composer.lock").write_text("changed")
|
||||||
|
|
||||||
|
with self.assertRaises(ProvenanceError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_modified_package_manifest_rejected(self):
|
||||||
|
|
||||||
|
(self.release / "package.json").write_text("changed")
|
||||||
|
|
||||||
|
with self.assertRaises(ProvenanceError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_modified_package_lock_rejected(self):
|
||||||
|
|
||||||
|
(self.release / "package-lock.json").write_text("changed")
|
||||||
|
|
||||||
|
with self.assertRaises(ProvenanceError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_missing_dependency_rejected(self):
|
||||||
|
|
||||||
|
(self.release / "composer.lock").unlink()
|
||||||
|
|
||||||
|
with self.assertRaises(ProvenanceError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_invalid_revision_rejected(self):
|
||||||
|
|
||||||
|
(self.release / "REVISION").write_text("invalid")
|
||||||
|
|
||||||
|
with self.assertRaises(ProvenanceError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_unknown_revision_rejected(self):
|
||||||
|
|
||||||
|
(self.release / "REVISION").write_text("a" * 40)
|
||||||
|
|
||||||
|
with self.assertRaises(ProvenanceError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_missing_revision_rejected(self):
|
||||||
|
|
||||||
|
(self.release / "REVISION").unlink()
|
||||||
|
|
||||||
|
with self.assertRaises(ProvenanceError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_symlink_revision_rejected(self):
|
||||||
|
|
||||||
|
path = self.release / "REVISION"
|
||||||
|
path.unlink()
|
||||||
|
|
||||||
|
target = self.root / "revision"
|
||||||
|
target.write_text(self.revision)
|
||||||
|
|
||||||
|
path.symlink_to(target)
|
||||||
|
|
||||||
|
with self.assertRaises(ProvenanceError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_symlink_migration_rejected(self):
|
||||||
|
|
||||||
|
path = (
|
||||||
|
self.release
|
||||||
|
/ "database/migrations/0001_create_users.php"
|
||||||
|
)
|
||||||
|
|
||||||
|
original = path.read_bytes()
|
||||||
|
path.unlink()
|
||||||
|
|
||||||
|
target = self.root / "migration.php"
|
||||||
|
target.write_bytes(original)
|
||||||
|
|
||||||
|
path.symlink_to(target)
|
||||||
|
|
||||||
|
with self.assertRaises(ProvenanceError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_symlink_dependency_rejected(self):
|
||||||
|
|
||||||
|
path = self.release / "composer.json"
|
||||||
|
path.unlink()
|
||||||
|
|
||||||
|
path.symlink_to(
|
||||||
|
self.repository / "composer.json"
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(ProvenanceError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_symlink_migration_directory_rejected(self):
|
||||||
|
|
||||||
|
path = self.release / "database/migrations"
|
||||||
|
|
||||||
|
shutil.rmtree(path)
|
||||||
|
|
||||||
|
path.symlink_to(
|
||||||
|
self.repository / "database/migrations"
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(ProvenanceError):
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
def test_invalid_repository_rejected(self):
|
||||||
|
|
||||||
|
with self.assertRaises(ProvenanceError):
|
||||||
|
|
||||||
|
ProvenanceVerifier(
|
||||||
|
self.root / "missing"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_symlink_release_rejected(self):
|
||||||
|
|
||||||
|
link = self.root / "linked-release"
|
||||||
|
link.symlink_to(self.release)
|
||||||
|
|
||||||
|
with self.assertRaises(ProvenanceError):
|
||||||
|
|
||||||
|
self.verifier.verify(link)
|
||||||
|
|
||||||
|
def test_no_git_repository_required_in_release(self):
|
||||||
|
|
||||||
|
self.assertFalse(
|
||||||
|
(self.release / ".git").exists()
|
||||||
|
)
|
||||||
|
|
||||||
|
self.verify()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,463 @@
|
|||||||
|
import copy
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import Mock
|
||||||
|
|
||||||
|
from core.compatibility import provenance_fingerprint
|
||||||
|
from core.recovery import RecoveryPlanner, RecoveryError
|
||||||
|
from core.transactions import TransactionJournal
|
||||||
|
from core.backup_evidence import BackupEvidence
|
||||||
|
from core.releases import ReleaseManager
|
||||||
|
from core.locking import DeploymentLock, LockError
|
||||||
|
|
||||||
|
|
||||||
|
def provenance(revision):
|
||||||
|
|
||||||
|
data = {
|
||||||
|
"format_version": 1,
|
||||||
|
"revision": revision,
|
||||||
|
"migrations": {
|
||||||
|
"database/migrations/0001_users.php": "a" * 64,
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"composer.json": "b" * 64,
|
||||||
|
"composer.lock": "c" * 64,
|
||||||
|
"package.json": "d" * 64,
|
||||||
|
"package-lock.json": "e" * 64,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
data["fingerprint"] = provenance_fingerprint(data)
|
||||||
|
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
class RecoveryTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
|
||||||
|
self.temp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.temp.cleanup)
|
||||||
|
|
||||||
|
self.root = Path(self.temp.name)
|
||||||
|
|
||||||
|
self.app = self.root / "app"
|
||||||
|
self.app.mkdir()
|
||||||
|
|
||||||
|
(self.app / "releases").mkdir()
|
||||||
|
|
||||||
|
self.state = self.root / "state"
|
||||||
|
self.state.mkdir(mode=0o700)
|
||||||
|
|
||||||
|
self.releases = ReleaseManager(self.app)
|
||||||
|
self.journal = TransactionJournal(self.state)
|
||||||
|
self.evidence = BackupEvidence(self.state)
|
||||||
|
|
||||||
|
self.old = provenance("a" * 40)
|
||||||
|
self.new = provenance("b" * 40)
|
||||||
|
|
||||||
|
for number, evidence in (
|
||||||
|
("1", self.old),
|
||||||
|
("2", self.new),
|
||||||
|
("3", provenance("c" * 40)),
|
||||||
|
):
|
||||||
|
|
||||||
|
root = self.app / "releases" / number
|
||||||
|
|
||||||
|
(root / "vendor").mkdir(parents=True)
|
||||||
|
(root / "public/build").mkdir(parents=True)
|
||||||
|
|
||||||
|
(root / "vendor/autoload.php").write_text(
|
||||||
|
"<?php\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
(root / "public/build/manifest.json").write_text(
|
||||||
|
"{}"
|
||||||
|
)
|
||||||
|
|
||||||
|
(root / "REVISION").write_text(
|
||||||
|
evidence["revision"] + "\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.releases.activate("1")
|
||||||
|
|
||||||
|
self.provenance = Mock()
|
||||||
|
|
||||||
|
self.provenance.verify.side_effect = (
|
||||||
|
lambda path: copy.deepcopy(
|
||||||
|
self.old if path.name == "1" else self.new
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
self.manifest = {
|
||||||
|
"backup_id": "fixture-backup",
|
||||||
|
"driver": "mysql",
|
||||||
|
"database": "example_db",
|
||||||
|
"username": "example_app",
|
||||||
|
"container": "example-mysql",
|
||||||
|
"identity": "fixture-server",
|
||||||
|
"filename": "database.sql",
|
||||||
|
"sha256": "f" * 64,
|
||||||
|
"bytes": 1024,
|
||||||
|
}
|
||||||
|
|
||||||
|
self.backup_verify = Mock(
|
||||||
|
return_value=copy.deepcopy(self.manifest)
|
||||||
|
)
|
||||||
|
|
||||||
|
self.runtime_check = Mock(return_value=True)
|
||||||
|
|
||||||
|
self.planner = RecoveryPlanner(
|
||||||
|
site="example-absdev-net",
|
||||||
|
lock_path=self.root / ".deployment.lock",
|
||||||
|
releases=self.releases,
|
||||||
|
provenance=self.provenance,
|
||||||
|
journal=self.journal,
|
||||||
|
backup_evidence=self.evidence,
|
||||||
|
backup_verify=self.backup_verify,
|
||||||
|
runtime_check=self.runtime_check,
|
||||||
|
)
|
||||||
|
|
||||||
|
def prepare(self, failed=True):
|
||||||
|
|
||||||
|
transaction = self.journal.create(
|
||||||
|
"example-absdev-net",
|
||||||
|
"1",
|
||||||
|
"2",
|
||||||
|
self.new["revision"],
|
||||||
|
self.new["fingerprint"],
|
||||||
|
previous_revision=self.old["revision"],
|
||||||
|
previous_provenance=self.old["fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
self.evidence.create(
|
||||||
|
transaction["transaction_id"],
|
||||||
|
self.manifest,
|
||||||
|
)
|
||||||
|
|
||||||
|
for phase in (
|
||||||
|
"BACKED_UP",
|
||||||
|
"QUIESCED",
|
||||||
|
"ACTIVATING",
|
||||||
|
):
|
||||||
|
|
||||||
|
transaction = self.journal.transition(
|
||||||
|
transaction["transaction_id"],
|
||||||
|
transaction["phase"],
|
||||||
|
phase,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.releases.activate("2")
|
||||||
|
|
||||||
|
transaction = self.journal.transition(
|
||||||
|
transaction["transaction_id"],
|
||||||
|
"ACTIVATING",
|
||||||
|
"ACTIVATED",
|
||||||
|
)
|
||||||
|
|
||||||
|
return self.journal.transition(
|
||||||
|
transaction["transaction_id"],
|
||||||
|
"ACTIVATED",
|
||||||
|
"FAILED" if failed else "VERIFIED",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_clear_status(self):
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.planner.inspect()["status"],
|
||||||
|
"CLEAR",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_failed_transaction_rollback_plan(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
result = self.planner.inspect()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
result["status"],
|
||||||
|
"ROLLBACK_REVIEW_READY",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(result["target"], "1")
|
||||||
|
|
||||||
|
def test_verified_transaction_not_rollback_eligible(self):
|
||||||
|
|
||||||
|
self.prepare(failed=False)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.planner.inspect()["status"],
|
||||||
|
"VERIFIED",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_plan_is_read_only(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
before = self.journal.load()
|
||||||
|
current = self.releases.current()
|
||||||
|
|
||||||
|
self.planner.inspect()
|
||||||
|
|
||||||
|
self.assertEqual(self.journal.load(), before)
|
||||||
|
self.assertEqual(self.releases.current(), current)
|
||||||
|
|
||||||
|
def test_backup_verification_required(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
self.planner.inspect()
|
||||||
|
|
||||||
|
self.backup_verify.assert_called_once_with(
|
||||||
|
"fixture-backup"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_backup_checksum_mismatch_rejected(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
self.backup_verify.return_value["sha256"] = "0" * 64
|
||||||
|
|
||||||
|
with self.assertRaises(RecoveryError):
|
||||||
|
self.planner.inspect()
|
||||||
|
|
||||||
|
def test_database_identity_mismatch_rejected(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
self.backup_verify.return_value["identity"] = (
|
||||||
|
"different-server"
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(RecoveryError):
|
||||||
|
self.planner.inspect()
|
||||||
|
|
||||||
|
def test_backup_size_mismatch_rejected(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
self.backup_verify.return_value["bytes"] = 99
|
||||||
|
|
||||||
|
with self.assertRaises(RecoveryError):
|
||||||
|
self.planner.inspect()
|
||||||
|
|
||||||
|
def test_backup_failure_rejected(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
self.backup_verify.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(RecoveryError):
|
||||||
|
self.planner.inspect()
|
||||||
|
|
||||||
|
def test_runtime_check_required(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
self.runtime_check.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(RecoveryError):
|
||||||
|
self.planner.inspect()
|
||||||
|
|
||||||
|
def test_wrong_active_release_rejected(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
self.releases.activate("3")
|
||||||
|
|
||||||
|
with self.assertRaises(RecoveryError):
|
||||||
|
self.planner.inspect()
|
||||||
|
|
||||||
|
def test_previous_release_already_active(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
self.releases.activate("1")
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.planner.inspect()["status"],
|
||||||
|
"PREVIOUS_ACTIVE_REVIEW_REQUIRED",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_bad_previous_release_rejected(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
(
|
||||||
|
self.releases.release_path("1") / "BAD_RELEASE"
|
||||||
|
).touch()
|
||||||
|
|
||||||
|
with self.assertRaises(RecoveryError):
|
||||||
|
self.planner.inspect()
|
||||||
|
|
||||||
|
def test_missing_previous_release_rejected(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
self.releases.release_path("1").rename(
|
||||||
|
self.root / "removed-release"
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(RecoveryError):
|
||||||
|
self.planner.inspect()
|
||||||
|
|
||||||
|
def test_changed_candidate_provenance_rejected(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
self.new["dependencies"]["composer.lock"] = "0" * 64
|
||||||
|
|
||||||
|
self.new["fingerprint"] = provenance_fingerprint(
|
||||||
|
self.new
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(RecoveryError):
|
||||||
|
self.planner.inspect()
|
||||||
|
|
||||||
|
def test_migration_difference_rejected(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
self.old["migrations"][
|
||||||
|
"database/migrations/0001_users.php"
|
||||||
|
] = "0" * 64
|
||||||
|
|
||||||
|
self.old["fingerprint"] = provenance_fingerprint(
|
||||||
|
self.old
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(RecoveryError):
|
||||||
|
self.planner.inspect()
|
||||||
|
|
||||||
|
def test_missing_backup_evidence_rejected(self):
|
||||||
|
|
||||||
|
transaction = self.prepare()
|
||||||
|
|
||||||
|
self.evidence.path(
|
||||||
|
transaction["transaction_id"]
|
||||||
|
).unlink()
|
||||||
|
|
||||||
|
with self.assertRaises(RecoveryError):
|
||||||
|
self.planner.inspect()
|
||||||
|
|
||||||
|
def test_corrupt_backup_evidence_rejected(self):
|
||||||
|
|
||||||
|
transaction = self.prepare()
|
||||||
|
|
||||||
|
self.evidence.path(
|
||||||
|
transaction["transaction_id"]
|
||||||
|
).write_text("{invalid")
|
||||||
|
|
||||||
|
with self.assertRaises(RecoveryError):
|
||||||
|
self.planner.inspect()
|
||||||
|
|
||||||
|
def test_concurrent_operation_rejected(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
with DeploymentLock(
|
||||||
|
self.root / ".deployment.lock"
|
||||||
|
):
|
||||||
|
|
||||||
|
with self.assertRaises(LockError):
|
||||||
|
self.planner.inspect()
|
||||||
|
|
||||||
|
def test_confirmation_bound_to_transaction(self):
|
||||||
|
|
||||||
|
transaction = self.prepare()
|
||||||
|
|
||||||
|
result = self.planner.inspect()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
result["confirmation"],
|
||||||
|
"ROLLBACK-" + transaction["transaction_id"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_automatic_rollback_prohibited(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
self.assertFalse(
|
||||||
|
self.planner.inspect()[
|
||||||
|
"automatic_rollback_allowed"
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_database_restore_prohibited(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
self.assertFalse(
|
||||||
|
self.planner.inspect()[
|
||||||
|
"database_restore_allowed"
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_deterministic_plan(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.planner.inspect(),
|
||||||
|
self.planner.inspect(),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_prepared_transaction_requires_review(self):
|
||||||
|
|
||||||
|
self.journal.create(
|
||||||
|
"example-absdev-net",
|
||||||
|
"1",
|
||||||
|
"2",
|
||||||
|
self.new["revision"],
|
||||||
|
self.new["fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.planner.inspect()["status"],
|
||||||
|
"PREVIOUS_ACTIVE_REVIEW_REQUIRED",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.backup_verify.assert_not_called()
|
||||||
|
|
||||||
|
def test_wrong_site_rejected(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
self.planner.site = "different-site"
|
||||||
|
|
||||||
|
with self.assertRaises(RecoveryError):
|
||||||
|
self.planner.inspect()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def test_replaced_previous_revision_rejected(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
self.old["revision"] = "d" * 40
|
||||||
|
|
||||||
|
self.old["fingerprint"] = provenance_fingerprint(
|
||||||
|
self.old
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(RecoveryError):
|
||||||
|
self.planner.inspect()
|
||||||
|
|
||||||
|
def test_changed_previous_dependencies_rejected(self):
|
||||||
|
|
||||||
|
self.prepare()
|
||||||
|
|
||||||
|
self.old["dependencies"]["composer.lock"] = "0" * 64
|
||||||
|
|
||||||
|
self.old["fingerprint"] = provenance_fingerprint(
|
||||||
|
self.old
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(RecoveryError):
|
||||||
|
self.planner.inspect()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,390 @@
|
|||||||
|
import copy
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
from core.compatibility import canonical_hash
|
||||||
|
|
||||||
|
from core.rehearsal import (
|
||||||
|
RehearsalError,
|
||||||
|
create_rehearsal,
|
||||||
|
verify_rehearsal,
|
||||||
|
approval_context,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class RehearsalTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
|
||||||
|
self.now = datetime(
|
||||||
|
2026, 11, 26, 10, 0,
|
||||||
|
tzinfo=timezone.utc,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.context = {
|
||||||
|
"site": "example-absdev-net",
|
||||||
|
"release": "2",
|
||||||
|
"revision": "a" * 40,
|
||||||
|
"provenance": "b" * 64,
|
||||||
|
"compatibility": "c" * 64,
|
||||||
|
"database_identity": "d" * 64,
|
||||||
|
"backup_sha256": "e" * 64,
|
||||||
|
"pending_migrations": [
|
||||||
|
"2026_11_26_100000_create_products"
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
self.execution = {
|
||||||
|
"driver": "mysql",
|
||||||
|
"source_database": "example_db",
|
||||||
|
"target_database": "isolated_restore_fixture",
|
||||||
|
"target_identity": "f" * 64,
|
||||||
|
"applied_migrations": list(
|
||||||
|
self.context["pending_migrations"]
|
||||||
|
),
|
||||||
|
"checks": {
|
||||||
|
"isolation_verified": True,
|
||||||
|
"backup_restored": True,
|
||||||
|
"migration_succeeded": True,
|
||||||
|
"migration_history_verified": True,
|
||||||
|
"application_verified": True,
|
||||||
|
"cleanup_verified": True,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
def create(self):
|
||||||
|
|
||||||
|
return create_rehearsal(
|
||||||
|
self.context,
|
||||||
|
self.execution,
|
||||||
|
completed_at=self.now,
|
||||||
|
)
|
||||||
|
|
||||||
|
def verify(self, record=None, now=None):
|
||||||
|
|
||||||
|
return verify_rehearsal(
|
||||||
|
self.create() if record is None else record,
|
||||||
|
self.context,
|
||||||
|
now=self.now if now is None else now,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_valid_rehearsal(self):
|
||||||
|
self.assertTrue(self.verify())
|
||||||
|
|
||||||
|
def test_rehearsal_identifier(self):
|
||||||
|
self.assertRegex(
|
||||||
|
self.create()["rehearsal_id"],
|
||||||
|
r"^[a-f0-9]{32}$",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_unique_rehearsal_identifier(self):
|
||||||
|
self.assertNotEqual(
|
||||||
|
self.create()["rehearsal_id"],
|
||||||
|
self.create()["rehearsal_id"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_fingerprint_format(self):
|
||||||
|
self.assertRegex(
|
||||||
|
self.create()["fingerprint"],
|
||||||
|
r"^[a-f0-9]{64}$",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_live_database_target_rejected(self):
|
||||||
|
self.execution["target_database"] = "example_db"
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
def test_invalid_target_prefix_rejected(self):
|
||||||
|
self.execution["target_database"] = "other_database"
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
def test_same_database_identity_rejected(self):
|
||||||
|
self.execution["target_identity"] = (
|
||||||
|
self.context["database_identity"]
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
def test_invalid_target_identity_rejected(self):
|
||||||
|
self.execution["target_identity"] = "invalid"
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
def test_invalid_driver_rejected(self):
|
||||||
|
self.execution["driver"] = "sqlite"
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
def test_postgresql_supported(self):
|
||||||
|
self.execution["driver"] = "postgresql"
|
||||||
|
self.assertTrue(self.verify())
|
||||||
|
|
||||||
|
def test_missing_applied_migration_rejected(self):
|
||||||
|
self.execution["applied_migrations"] = []
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
def test_unexpected_applied_migration_rejected(self):
|
||||||
|
self.execution["applied_migrations"].append(
|
||||||
|
"unexpected_migration"
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
def test_migration_order_mismatch_rejected(self):
|
||||||
|
|
||||||
|
self.context["pending_migrations"].append(
|
||||||
|
"2026_11_26_110000_create_orders"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.execution["applied_migrations"] = list(
|
||||||
|
reversed(
|
||||||
|
self.context["pending_migrations"]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
def test_every_check_is_mandatory(self):
|
||||||
|
|
||||||
|
for field in self.execution["checks"]:
|
||||||
|
|
||||||
|
with self.subTest(field=field):
|
||||||
|
|
||||||
|
self.execution["checks"][field] = False
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
self.execution["checks"][field] = True
|
||||||
|
|
||||||
|
def test_numeric_check_rejected(self):
|
||||||
|
|
||||||
|
self.execution["checks"]["backup_restored"] = 1
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
def test_missing_check_rejected(self):
|
||||||
|
|
||||||
|
del self.execution["checks"]["cleanup_verified"]
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
def test_unknown_check_rejected(self):
|
||||||
|
|
||||||
|
self.execution["checks"]["unexpected"] = True
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
def test_changed_backup_rejected(self):
|
||||||
|
|
||||||
|
record = self.create()
|
||||||
|
self.context["backup_sha256"] = "0" * 64
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.verify(record)
|
||||||
|
|
||||||
|
def test_changed_release_rejected(self):
|
||||||
|
|
||||||
|
record = self.create()
|
||||||
|
self.context["release"] = "3"
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.verify(record)
|
||||||
|
|
||||||
|
def test_changed_database_rejected(self):
|
||||||
|
|
||||||
|
record = self.create()
|
||||||
|
self.context["database_identity"] = "0" * 64
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.verify(record)
|
||||||
|
|
||||||
|
def test_changed_pending_migrations_rejected(self):
|
||||||
|
|
||||||
|
record = self.create()
|
||||||
|
|
||||||
|
self.context["pending_migrations"].append(
|
||||||
|
"unexpected_migration"
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.verify(record)
|
||||||
|
|
||||||
|
def test_expired_rehearsal_rejected(self):
|
||||||
|
|
||||||
|
record = self.create()
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.verify(
|
||||||
|
record,
|
||||||
|
self.now + timedelta(hours=24),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_future_rehearsal_rejected(self):
|
||||||
|
|
||||||
|
record = self.create()
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.verify(
|
||||||
|
record,
|
||||||
|
self.now - timedelta(seconds=1),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_modified_evidence_rejected(self):
|
||||||
|
|
||||||
|
record = self.create()
|
||||||
|
|
||||||
|
record["execution"]["target_identity"] = "0" * 64
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.verify(record)
|
||||||
|
|
||||||
|
def test_invalid_check_with_new_fingerprint_rejected(self):
|
||||||
|
|
||||||
|
record = self.create()
|
||||||
|
|
||||||
|
record["execution"]["checks"][
|
||||||
|
"isolation_verified"
|
||||||
|
] = False
|
||||||
|
|
||||||
|
del record["fingerprint"]
|
||||||
|
|
||||||
|
record["fingerprint"] = canonical_hash(record)
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.verify(record)
|
||||||
|
|
||||||
|
def test_unknown_record_field_rejected(self):
|
||||||
|
|
||||||
|
record = self.create()
|
||||||
|
record["unexpected"] = True
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.verify(record)
|
||||||
|
|
||||||
|
def test_unknown_execution_field_rejected(self):
|
||||||
|
|
||||||
|
self.execution["password"] = "private-secret"
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
def test_input_not_mutated(self):
|
||||||
|
|
||||||
|
original = copy.deepcopy(self.execution)
|
||||||
|
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
self.assertEqual(self.execution, original)
|
||||||
|
|
||||||
|
def test_record_independent_of_input(self):
|
||||||
|
|
||||||
|
record = self.create()
|
||||||
|
|
||||||
|
self.execution["checks"]["backup_restored"] = False
|
||||||
|
|
||||||
|
self.assertTrue(
|
||||||
|
record["execution"]["checks"]["backup_restored"]
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_approval_context_binding(self):
|
||||||
|
|
||||||
|
record = self.create()
|
||||||
|
|
||||||
|
result = approval_context(
|
||||||
|
record,
|
||||||
|
self.context,
|
||||||
|
now=self.now,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
result["rehearsal_fingerprint"],
|
||||||
|
record["fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_expired_rehearsal_cannot_create_approval_context(self):
|
||||||
|
|
||||||
|
record = self.create()
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
|
||||||
|
approval_context(
|
||||||
|
record,
|
||||||
|
self.context,
|
||||||
|
now=self.now + timedelta(hours=25),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_approval_policy_integration(self):
|
||||||
|
|
||||||
|
from core.approval import (
|
||||||
|
issue_approval,
|
||||||
|
verify_approval,
|
||||||
|
)
|
||||||
|
|
||||||
|
record = self.create()
|
||||||
|
|
||||||
|
context = approval_context(
|
||||||
|
record,
|
||||||
|
self.context,
|
||||||
|
now=self.now,
|
||||||
|
)
|
||||||
|
|
||||||
|
approval = issue_approval(
|
||||||
|
context,
|
||||||
|
approver="operator",
|
||||||
|
now=self.now,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertTrue(
|
||||||
|
verify_approval(
|
||||||
|
approval,
|
||||||
|
context,
|
||||||
|
confirmation=approval["confirmation"],
|
||||||
|
now=self.now,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invalid_source_database_rejected(self):
|
||||||
|
|
||||||
|
self.execution["source_database"] = "../outside"
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
def test_naive_timestamp_rejected(self):
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
|
||||||
|
create_rehearsal(
|
||||||
|
self.context,
|
||||||
|
self.execution,
|
||||||
|
completed_at=self.now.replace(tzinfo=None),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invalid_record_type_rejected(self):
|
||||||
|
|
||||||
|
with self.assertRaises(RehearsalError):
|
||||||
|
|
||||||
|
verify_rehearsal(
|
||||||
|
"invalid",
|
||||||
|
self.context,
|
||||||
|
now=self.now,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from core.releases import ReleaseManager, ReleaseError
|
||||||
|
|
||||||
|
|
||||||
|
class ReleaseTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
|
||||||
|
self.temp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.temp.cleanup)
|
||||||
|
|
||||||
|
self.app = Path(self.temp.name) / "app"
|
||||||
|
self.app.mkdir()
|
||||||
|
|
||||||
|
self.releases = self.app / "releases"
|
||||||
|
self.releases.mkdir()
|
||||||
|
|
||||||
|
self.manager = ReleaseManager(self.app)
|
||||||
|
|
||||||
|
def create_release(self, number):
|
||||||
|
|
||||||
|
root = self.releases / str(number)
|
||||||
|
|
||||||
|
root.mkdir()
|
||||||
|
|
||||||
|
(root / "vendor").mkdir()
|
||||||
|
(root / "public/build").mkdir(parents=True)
|
||||||
|
|
||||||
|
(root / "vendor/autoload.php").write_text(
|
||||||
|
"<?php\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
(root / "public/build/manifest.json").write_text(
|
||||||
|
"{}"
|
||||||
|
)
|
||||||
|
|
||||||
|
(root / "REVISION").write_text(
|
||||||
|
"a" * 40 + "\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
return root
|
||||||
|
|
||||||
|
def test_empty_inventory(self):
|
||||||
|
self.assertEqual(self.manager.inventory(), [])
|
||||||
|
|
||||||
|
def test_numeric_sorting(self):
|
||||||
|
|
||||||
|
for number in (10, 2, 1):
|
||||||
|
self.create_release(number)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.manager.inventory(),
|
||||||
|
["1", "2", "10"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_no_active_release(self):
|
||||||
|
self.assertIsNone(self.manager.current())
|
||||||
|
|
||||||
|
def test_initial_activation(self):
|
||||||
|
|
||||||
|
self.create_release(1)
|
||||||
|
|
||||||
|
self.manager.activate("1")
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.manager.current(), "1"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_switch_release(self):
|
||||||
|
|
||||||
|
self.create_release(1)
|
||||||
|
self.create_release(2)
|
||||||
|
|
||||||
|
self.manager.activate("1")
|
||||||
|
self.manager.activate("2")
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.manager.current(), "2"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_relative_activation_link(self):
|
||||||
|
|
||||||
|
self.create_release(1)
|
||||||
|
self.manager.activate("1")
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
str((self.app / "current").readlink()),
|
||||||
|
"releases/1",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_previous_release_preserved(self):
|
||||||
|
|
||||||
|
self.create_release(1)
|
||||||
|
self.create_release(2)
|
||||||
|
|
||||||
|
self.manager.activate("1")
|
||||||
|
self.manager.activate("2")
|
||||||
|
|
||||||
|
self.assertTrue(
|
||||||
|
(self.releases / "1").is_dir()
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_missing_release_rejected(self):
|
||||||
|
|
||||||
|
with self.assertRaises(ReleaseError):
|
||||||
|
self.manager.activate("99")
|
||||||
|
|
||||||
|
def test_path_traversal_rejected(self):
|
||||||
|
|
||||||
|
with self.assertRaises(ReleaseError):
|
||||||
|
self.manager.activate("../outside")
|
||||||
|
|
||||||
|
def test_invalid_release_number(self):
|
||||||
|
|
||||||
|
for value in ("0", "-1", "01", "abc"):
|
||||||
|
|
||||||
|
with self.subTest(value=value):
|
||||||
|
|
||||||
|
with self.assertRaises(ReleaseError):
|
||||||
|
self.manager.activate(value)
|
||||||
|
|
||||||
|
def test_bad_release_rejected(self):
|
||||||
|
|
||||||
|
root = self.create_release(1)
|
||||||
|
|
||||||
|
(root / "BAD_RELEASE").touch()
|
||||||
|
|
||||||
|
with self.assertRaises(ReleaseError):
|
||||||
|
self.manager.activate("1")
|
||||||
|
|
||||||
|
def test_missing_vendor_rejected(self):
|
||||||
|
|
||||||
|
root = self.create_release(1)
|
||||||
|
(root / "vendor/autoload.php").unlink()
|
||||||
|
|
||||||
|
with self.assertRaises(ReleaseError):
|
||||||
|
self.manager.activate("1")
|
||||||
|
|
||||||
|
def test_missing_manifest_rejected(self):
|
||||||
|
|
||||||
|
root = self.create_release(1)
|
||||||
|
(root / "public/build/manifest.json").unlink()
|
||||||
|
|
||||||
|
with self.assertRaises(ReleaseError):
|
||||||
|
self.manager.activate("1")
|
||||||
|
|
||||||
|
def test_invalid_revision_rejected(self):
|
||||||
|
|
||||||
|
root = self.create_release(1)
|
||||||
|
(root / "REVISION").write_text("invalid")
|
||||||
|
|
||||||
|
with self.assertRaises(ReleaseError):
|
||||||
|
self.manager.activate("1")
|
||||||
|
|
||||||
|
def test_symlink_release_rejected(self):
|
||||||
|
|
||||||
|
root = self.create_release(1)
|
||||||
|
|
||||||
|
(self.releases / "2").symlink_to(root)
|
||||||
|
|
||||||
|
with self.assertRaises(ReleaseError):
|
||||||
|
self.manager.activate("2")
|
||||||
|
|
||||||
|
def test_invalid_current_link_rejected(self):
|
||||||
|
|
||||||
|
(self.app / "current").symlink_to("/tmp")
|
||||||
|
|
||||||
|
with self.assertRaises(ReleaseError):
|
||||||
|
self.manager.current()
|
||||||
|
|
||||||
|
def test_current_regular_file_rejected(self):
|
||||||
|
|
||||||
|
(self.app / "current").touch()
|
||||||
|
|
||||||
|
with self.assertRaises(ReleaseError):
|
||||||
|
self.manager.current()
|
||||||
|
|
||||||
|
def test_failed_activation_preserves_current(self):
|
||||||
|
|
||||||
|
self.create_release(1)
|
||||||
|
self.manager.activate("1")
|
||||||
|
|
||||||
|
with self.assertRaises(ReleaseError):
|
||||||
|
self.manager.activate("2")
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.manager.current(), "1"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_no_temporary_activation_links(self):
|
||||||
|
|
||||||
|
self.create_release(1)
|
||||||
|
self.manager.activate("1")
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
sorted(p.name for p in self.app.iterdir()),
|
||||||
|
["current", "releases"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invalid_inventory_entry(self):
|
||||||
|
|
||||||
|
(self.releases / "unexpected").mkdir()
|
||||||
|
|
||||||
|
with self.assertRaises(ReleaseError):
|
||||||
|
self.manager.inventory()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,273 @@
|
|||||||
|
import unittest
|
||||||
|
|
||||||
|
from core.retention import RetentionError, plan_retention
|
||||||
|
|
||||||
|
|
||||||
|
class RetentionTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.releases = [str(i) for i in range(1, 11)]
|
||||||
|
|
||||||
|
self.options = {
|
||||||
|
"inventory": self.releases,
|
||||||
|
"current": "10",
|
||||||
|
"keep": 5,
|
||||||
|
"protected": [],
|
||||||
|
"failed": [],
|
||||||
|
"unresolved": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
def plan(self, **changes):
|
||||||
|
return plan_retention({
|
||||||
|
**self.options,
|
||||||
|
**changes,
|
||||||
|
})
|
||||||
|
|
||||||
|
def test_default_retention(self):
|
||||||
|
result = self.plan()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
result["retained"],
|
||||||
|
["6", "7", "8", "9", "10"],
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
result["archive_candidates"],
|
||||||
|
["1", "2", "3", "4", "5"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_active_release_protected(self):
|
||||||
|
result = self.plan(current="1")
|
||||||
|
|
||||||
|
self.assertIn("1", result["retained"])
|
||||||
|
self.assertNotIn("1", result["archive_candidates"])
|
||||||
|
|
||||||
|
def test_explicitly_protected_release(self):
|
||||||
|
result = self.plan(protected=["2"])
|
||||||
|
|
||||||
|
self.assertIn("2", result["retained"])
|
||||||
|
|
||||||
|
def test_multiple_protected_releases(self):
|
||||||
|
result = self.plan(protected=["1", "2", "3"])
|
||||||
|
|
||||||
|
for release in ("1", "2", "3"):
|
||||||
|
self.assertIn(release, result["retained"])
|
||||||
|
|
||||||
|
def test_failed_release_preserved(self):
|
||||||
|
result = self.plan(failed=["1"])
|
||||||
|
|
||||||
|
self.assertIn("1", result["retained"])
|
||||||
|
|
||||||
|
def test_failed_current_rejected(self):
|
||||||
|
with self.assertRaises(RetentionError):
|
||||||
|
self.plan(failed=["10"])
|
||||||
|
|
||||||
|
def test_unresolved_transaction_blocks_archival(self):
|
||||||
|
result = self.plan(unresolved=["1", "2"])
|
||||||
|
|
||||||
|
self.assertEqual(result["status"], "BLOCKED")
|
||||||
|
self.assertEqual(result["archive_candidates"], [])
|
||||||
|
self.assertEqual(result["retained"], self.releases)
|
||||||
|
|
||||||
|
def test_no_automatic_deletion(self):
|
||||||
|
self.assertFalse(
|
||||||
|
self.plan()["automatic_deletion"]
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_no_automatic_archival(self):
|
||||||
|
self.assertFalse(
|
||||||
|
self.plan()["automatic_archival"]
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_small_inventory_retained(self):
|
||||||
|
result = self.plan(
|
||||||
|
inventory=["1", "2"],
|
||||||
|
current="2",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(result["archive_candidates"], [])
|
||||||
|
|
||||||
|
def test_single_release_retained(self):
|
||||||
|
result = self.plan(
|
||||||
|
inventory=["1"],
|
||||||
|
current="1",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(result["retained"], ["1"])
|
||||||
|
|
||||||
|
def test_empty_inventory_rejected(self):
|
||||||
|
with self.assertRaises(RetentionError):
|
||||||
|
self.plan(inventory=[])
|
||||||
|
|
||||||
|
def test_missing_current_rejected(self):
|
||||||
|
with self.assertRaises(RetentionError):
|
||||||
|
self.plan(current="99")
|
||||||
|
|
||||||
|
def test_duplicate_release_rejected(self):
|
||||||
|
with self.assertRaises(RetentionError):
|
||||||
|
self.plan(inventory=["1", "1", "10"])
|
||||||
|
|
||||||
|
def test_numeric_release_order(self):
|
||||||
|
result = self.plan(
|
||||||
|
inventory=["100", "2", "10", "1"],
|
||||||
|
current="100",
|
||||||
|
keep=2,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
result["retained"],
|
||||||
|
["10", "100"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invalid_release_identifiers(self):
|
||||||
|
for value in (
|
||||||
|
"../outside", "0", "01",
|
||||||
|
"-1", "", 10, True, "1.0",
|
||||||
|
):
|
||||||
|
with self.subTest(value=value):
|
||||||
|
with self.assertRaises(RetentionError):
|
||||||
|
self.plan(inventory=["10", value])
|
||||||
|
|
||||||
|
def test_invalid_retention_values(self):
|
||||||
|
for value in (
|
||||||
|
0, 1, -1, True, "5", 1001,
|
||||||
|
):
|
||||||
|
with self.subTest(value=value):
|
||||||
|
with self.assertRaises(RetentionError):
|
||||||
|
self.plan(keep=value)
|
||||||
|
|
||||||
|
def test_missing_protected_release_rejected(self):
|
||||||
|
with self.assertRaises(RetentionError):
|
||||||
|
self.plan(protected=["99"])
|
||||||
|
|
||||||
|
def test_missing_failed_release_rejected(self):
|
||||||
|
with self.assertRaises(RetentionError):
|
||||||
|
self.plan(failed=["99"])
|
||||||
|
|
||||||
|
def test_missing_unresolved_release_rejected(self):
|
||||||
|
with self.assertRaises(RetentionError):
|
||||||
|
self.plan(unresolved=["99"])
|
||||||
|
|
||||||
|
def test_duplicate_protected_release_rejected(self):
|
||||||
|
with self.assertRaises(RetentionError):
|
||||||
|
self.plan(protected=["1", "1"])
|
||||||
|
|
||||||
|
def test_invalid_inventory_type(self):
|
||||||
|
with self.assertRaises(RetentionError):
|
||||||
|
self.plan(inventory="123")
|
||||||
|
|
||||||
|
def test_invalid_protection_type(self):
|
||||||
|
with self.assertRaises(RetentionError):
|
||||||
|
self.plan(protected="1")
|
||||||
|
|
||||||
|
def test_missing_policy_field_rejected(self):
|
||||||
|
data = dict(self.options)
|
||||||
|
del data["failed"]
|
||||||
|
|
||||||
|
with self.assertRaises(RetentionError):
|
||||||
|
plan_retention(data)
|
||||||
|
|
||||||
|
def test_unknown_policy_field_rejected(self):
|
||||||
|
with self.assertRaises(RetentionError):
|
||||||
|
self.plan(delete=True)
|
||||||
|
|
||||||
|
def test_input_not_mutated(self):
|
||||||
|
original = list(self.releases)
|
||||||
|
|
||||||
|
self.plan()
|
||||||
|
|
||||||
|
self.assertEqual(self.releases, original)
|
||||||
|
|
||||||
|
def test_plan_fingerprint(self):
|
||||||
|
self.assertRegex(
|
||||||
|
self.plan()["fingerprint"],
|
||||||
|
r"^[a-f0-9]{64}$",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_deterministic_plan(self):
|
||||||
|
self.assertEqual(self.plan(), self.plan())
|
||||||
|
|
||||||
|
def test_fingerprint_changes_with_policy(self):
|
||||||
|
self.assertNotEqual(
|
||||||
|
self.plan()["fingerprint"],
|
||||||
|
self.plan(keep=6)["fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_fingerprint_changes_with_protection(self):
|
||||||
|
self.assertNotEqual(
|
||||||
|
self.plan()["fingerprint"],
|
||||||
|
self.plan(protected=["1"])["fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_all_releases_accounted_for(self):
|
||||||
|
result = self.plan(
|
||||||
|
protected=["1"],
|
||||||
|
failed=["2"],
|
||||||
|
)
|
||||||
|
|
||||||
|
retained = set(result["retained"])
|
||||||
|
candidates = set(result["archive_candidates"])
|
||||||
|
|
||||||
|
self.assertFalse(retained & candidates)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
retained | candidates,
|
||||||
|
set(self.releases),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_retention_reasons(self):
|
||||||
|
result = self.plan(
|
||||||
|
protected=["1"],
|
||||||
|
failed=["2"],
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertIn(
|
||||||
|
"active",
|
||||||
|
result["reasons"]["10"],
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertIn(
|
||||||
|
"explicitly_protected",
|
||||||
|
result["reasons"]["1"],
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertIn(
|
||||||
|
"failed_release",
|
||||||
|
result["reasons"]["2"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_no_candidates_when_every_release_protected(self):
|
||||||
|
result = self.plan(protected=self.releases)
|
||||||
|
|
||||||
|
self.assertEqual(result["archive_candidates"], [])
|
||||||
|
|
||||||
|
def test_keep_larger_than_inventory(self):
|
||||||
|
result = self.plan(keep=100)
|
||||||
|
|
||||||
|
self.assertEqual(result["archive_candidates"], [])
|
||||||
|
|
||||||
|
def test_previous_healthy_release_preserved(self):
|
||||||
|
result = self.plan(
|
||||||
|
current="5",
|
||||||
|
keep=2,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertIn("4", result["retained"])
|
||||||
|
|
||||||
|
def test_failed_release_not_selected_as_previous(self):
|
||||||
|
result = self.plan(
|
||||||
|
current="5",
|
||||||
|
keep=2,
|
||||||
|
failed=["4"],
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertIn("3", result["retained"])
|
||||||
|
|
||||||
|
self.assertIn(
|
||||||
|
"previous_available",
|
||||||
|
result["reasons"]["3"],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,325 @@
|
|||||||
|
import json
|
||||||
|
import stat
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from unittest.mock import Mock
|
||||||
|
|
||||||
|
import test_recovery
|
||||||
|
|
||||||
|
from core.rollback import RollbackExecutor, RollbackError
|
||||||
|
from core.locking import DeploymentLock, LockError
|
||||||
|
|
||||||
|
|
||||||
|
class RollbackTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
|
||||||
|
self.fixture = test_recovery.RecoveryTests()
|
||||||
|
self.addCleanup(self.fixture.doCleanups)
|
||||||
|
self.fixture.setUp()
|
||||||
|
|
||||||
|
self.fixture.prepare()
|
||||||
|
|
||||||
|
self.services = Mock()
|
||||||
|
self.stopped = Mock(return_value=True)
|
||||||
|
|
||||||
|
self.health = Mock()
|
||||||
|
|
||||||
|
self.health.verify.side_effect = (
|
||||||
|
lambda release: {
|
||||||
|
"healthy": True,
|
||||||
|
"release": release,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
self.executor = RollbackExecutor(
|
||||||
|
planner=self.fixture.planner,
|
||||||
|
services=self.services,
|
||||||
|
health=self.health,
|
||||||
|
stopped_check=self.stopped,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.plan = self.fixture.planner.inspect()
|
||||||
|
|
||||||
|
def execute(self):
|
||||||
|
|
||||||
|
return self.executor.execute(
|
||||||
|
self.plan["confirmation"],
|
||||||
|
self.plan["plan_fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_successful_rollback(self):
|
||||||
|
|
||||||
|
result = self.execute()
|
||||||
|
|
||||||
|
self.assertEqual(result["status"], "ROLLED_BACK")
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.fixture.releases.current(),
|
||||||
|
"1",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_wrong_confirmation_rejected(self):
|
||||||
|
|
||||||
|
with self.assertRaises(RollbackError):
|
||||||
|
|
||||||
|
self.executor.execute(
|
||||||
|
"INVALID",
|
||||||
|
self.plan["plan_fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
self.services.quiesce.assert_not_called()
|
||||||
|
|
||||||
|
def test_wrong_fingerprint_rejected(self):
|
||||||
|
|
||||||
|
with self.assertRaises(RollbackError):
|
||||||
|
|
||||||
|
self.executor.execute(
|
||||||
|
self.plan["confirmation"],
|
||||||
|
"0" * 64,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.services.quiesce.assert_not_called()
|
||||||
|
|
||||||
|
def test_changed_provenance_rejected(self):
|
||||||
|
|
||||||
|
self.fixture.old["revision"] = "0" * 40
|
||||||
|
|
||||||
|
with self.assertRaises(RollbackError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.services.quiesce.assert_not_called()
|
||||||
|
|
||||||
|
def test_changed_backup_rejected(self):
|
||||||
|
|
||||||
|
self.fixture.backup_verify.return_value[
|
||||||
|
"sha256"
|
||||||
|
] = "0" * 64
|
||||||
|
|
||||||
|
with self.assertRaises(RollbackError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.services.quiesce.assert_not_called()
|
||||||
|
|
||||||
|
def test_intent_persisted_before_shutdown(self):
|
||||||
|
|
||||||
|
def check():
|
||||||
|
|
||||||
|
path = self.executor.intent_path(
|
||||||
|
self.plan["transaction_id"]
|
||||||
|
)
|
||||||
|
|
||||||
|
record = json.loads(path.read_text())
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
record["status"],
|
||||||
|
"ROLLBACK_INTENT",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.services.quiesce.side_effect = check
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
def test_worker_shutdown_required(self):
|
||||||
|
|
||||||
|
self.stopped.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(RollbackError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.fixture.releases.current(),
|
||||||
|
"2",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_service_refresh_failure(self):
|
||||||
|
|
||||||
|
self.services.refresh.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(RollbackError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.fixture.releases.current(),
|
||||||
|
"1",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.services.resume.assert_not_called()
|
||||||
|
|
||||||
|
def test_health_failure_contains_workers(self):
|
||||||
|
|
||||||
|
self.health.verify.side_effect = RuntimeError()
|
||||||
|
|
||||||
|
with self.assertRaises(RollbackError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.services.quiesce.call_count,
|
||||||
|
2,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_unhealthy_result_rejected(self):
|
||||||
|
|
||||||
|
self.health.verify.side_effect = None
|
||||||
|
|
||||||
|
self.health.verify.return_value = {
|
||||||
|
"healthy": False,
|
||||||
|
"release": "1",
|
||||||
|
}
|
||||||
|
|
||||||
|
with self.assertRaises(RollbackError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
def test_wrong_health_release_rejected(self):
|
||||||
|
|
||||||
|
self.health.verify.side_effect = None
|
||||||
|
|
||||||
|
self.health.verify.return_value = {
|
||||||
|
"healthy": True,
|
||||||
|
"release": "2",
|
||||||
|
}
|
||||||
|
|
||||||
|
with self.assertRaises(RollbackError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
def test_repeated_execution_rejected(self):
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
with self.assertRaises(RollbackError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.services.refresh.assert_called_once()
|
||||||
|
|
||||||
|
def test_failed_rollback_cannot_repeat(self):
|
||||||
|
|
||||||
|
self.stopped.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(RollbackError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.stopped.return_value = True
|
||||||
|
|
||||||
|
with self.assertRaises(RollbackError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.services.refresh.assert_not_called()
|
||||||
|
|
||||||
|
def test_original_transaction_preserved(self):
|
||||||
|
|
||||||
|
original = self.fixture.journal.load()
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.fixture.journal.load(),
|
||||||
|
original,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_success_evidence_persisted(self):
|
||||||
|
|
||||||
|
result = self.execute()
|
||||||
|
|
||||||
|
path = self.executor.result_path(
|
||||||
|
self.plan["transaction_id"]
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
json.loads(path.read_text()),
|
||||||
|
result,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_evidence_permissions(self):
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
for path in (
|
||||||
|
self.executor.intent_path(
|
||||||
|
self.plan["transaction_id"]
|
||||||
|
),
|
||||||
|
self.executor.result_path(
|
||||||
|
self.plan["transaction_id"]
|
||||||
|
),
|
||||||
|
):
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
stat.S_IMODE(path.stat().st_mode),
|
||||||
|
0o600,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_concurrent_operation_rejected(self):
|
||||||
|
|
||||||
|
with DeploymentLock(
|
||||||
|
self.fixture.root / ".deployment.lock"
|
||||||
|
):
|
||||||
|
|
||||||
|
with self.assertRaises(LockError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
def test_failed_release_preserved(self):
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.assertTrue(
|
||||||
|
self.fixture.releases.release_path("2").is_dir()
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_database_restoration_prohibited(self):
|
||||||
|
|
||||||
|
result = self.execute()
|
||||||
|
|
||||||
|
self.assertFalse(result["database_restored"])
|
||||||
|
|
||||||
|
def test_runtime_rechecked_after_shutdown(self):
|
||||||
|
|
||||||
|
def change_runtime():
|
||||||
|
|
||||||
|
self.fixture.runtime_check.return_value = False
|
||||||
|
|
||||||
|
self.services.quiesce.side_effect = change_runtime
|
||||||
|
|
||||||
|
with self.assertRaises(RollbackError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.fixture.releases.current(),
|
||||||
|
"2",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_existing_intent_blocks_execution(self):
|
||||||
|
|
||||||
|
path = self.executor.intent_path(
|
||||||
|
self.plan["transaction_id"]
|
||||||
|
)
|
||||||
|
|
||||||
|
path.touch(mode=0o600)
|
||||||
|
|
||||||
|
with self.assertRaises(RollbackError):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.services.quiesce.assert_not_called()
|
||||||
|
|
||||||
|
def test_successful_health_verification(self):
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.health.verify.assert_called_once_with("1")
|
||||||
|
|
||||||
|
def test_invalid_confirmation_has_no_intent(self):
|
||||||
|
|
||||||
|
with self.assertRaises(RollbackError):
|
||||||
|
|
||||||
|
self.executor.execute(
|
||||||
|
"INVALID",
|
||||||
|
self.plan["plan_fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertFalse(
|
||||||
|
self.executor.intent_path(
|
||||||
|
self.plan["transaction_id"]
|
||||||
|
).exists()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,252 @@
|
|||||||
|
import json
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
import test_rollback
|
||||||
|
|
||||||
|
from core.rollback_archive import RollbackArchive, ArchiveError
|
||||||
|
from core.compatibility import canonical_hash
|
||||||
|
from core.locking import DeploymentLock, LockError
|
||||||
|
|
||||||
|
|
||||||
|
class RollbackArchiveTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.fixture = test_rollback.RollbackTests()
|
||||||
|
self.addCleanup(self.fixture.doCleanups)
|
||||||
|
self.fixture.setUp()
|
||||||
|
self.fixture.execute()
|
||||||
|
|
||||||
|
self.recovery = self.fixture.fixture
|
||||||
|
self.planner = self.recovery.planner
|
||||||
|
self.journal = self.recovery.journal
|
||||||
|
self.transaction = self.journal.load()
|
||||||
|
self.identifier = self.transaction["transaction_id"]
|
||||||
|
|
||||||
|
self.directory = self.recovery.root / "archives"
|
||||||
|
self.directory.mkdir(mode=0o700)
|
||||||
|
|
||||||
|
self.archive = RollbackArchive(
|
||||||
|
planner=self.planner,
|
||||||
|
directory=self.directory,
|
||||||
|
health_probe=self.fixture.health.verify,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.marker = (
|
||||||
|
self.recovery.releases.release_path("2")
|
||||||
|
/ "BAD_RELEASE"
|
||||||
|
)
|
||||||
|
|
||||||
|
def execute(self):
|
||||||
|
plan = self.archive.plan()
|
||||||
|
|
||||||
|
return self.archive.execute(
|
||||||
|
confirmation=plan["confirmation"],
|
||||||
|
fingerprint=plan["fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def rewrite(self, path, **changes):
|
||||||
|
record = json.loads(path.read_text())
|
||||||
|
record.update(changes)
|
||||||
|
record.pop("checksum", None)
|
||||||
|
record["checksum"] = canonical_hash(record)
|
||||||
|
path.write_text(json.dumps(record))
|
||||||
|
|
||||||
|
def test_valid_plan(self):
|
||||||
|
self.assertEqual(
|
||||||
|
self.archive.plan()["status"],
|
||||||
|
"ARCHIVE_READY",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_plan_is_read_only(self):
|
||||||
|
self.archive.plan()
|
||||||
|
|
||||||
|
self.assertFalse(self.marker.exists())
|
||||||
|
self.assertEqual(
|
||||||
|
self.journal.load(),
|
||||||
|
self.transaction,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_successful_archive(self):
|
||||||
|
result = self.execute()
|
||||||
|
|
||||||
|
self.assertEqual(result["status"], "ARCHIVED")
|
||||||
|
self.assertIsNone(self.journal.load())
|
||||||
|
|
||||||
|
def test_failed_candidate_marked(self):
|
||||||
|
self.execute()
|
||||||
|
self.assertTrue(self.marker.is_file())
|
||||||
|
|
||||||
|
def test_original_transaction_preserved(self):
|
||||||
|
result = self.execute()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
result["transaction"],
|
||||||
|
self.transaction,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_original_rollback_evidence_preserved(self):
|
||||||
|
intent = self.fixture.executor.intent_path(
|
||||||
|
self.identifier
|
||||||
|
)
|
||||||
|
|
||||||
|
result = self.fixture.executor.result_path(
|
||||||
|
self.identifier
|
||||||
|
)
|
||||||
|
|
||||||
|
before = (intent.read_bytes(), result.read_bytes())
|
||||||
|
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
(intent.read_bytes(), result.read_bytes()),
|
||||||
|
before,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_missing_result_rejected(self):
|
||||||
|
self.fixture.executor.result_path(
|
||||||
|
self.identifier
|
||||||
|
).unlink()
|
||||||
|
|
||||||
|
with self.assertRaises(ArchiveError):
|
||||||
|
self.archive.plan()
|
||||||
|
|
||||||
|
def test_missing_intent_rejected(self):
|
||||||
|
self.fixture.executor.intent_path(
|
||||||
|
self.identifier
|
||||||
|
).unlink()
|
||||||
|
|
||||||
|
with self.assertRaises(ArchiveError):
|
||||||
|
self.archive.plan()
|
||||||
|
|
||||||
|
def test_wrong_active_release_rejected(self):
|
||||||
|
self.recovery.releases.activate("2")
|
||||||
|
|
||||||
|
with self.assertRaises(ArchiveError):
|
||||||
|
self.archive.plan()
|
||||||
|
|
||||||
|
def test_changed_provenance_rejected(self):
|
||||||
|
self.recovery.old["fingerprint"] = "0" * 64
|
||||||
|
|
||||||
|
with self.assertRaises(ArchiveError):
|
||||||
|
self.archive.plan()
|
||||||
|
|
||||||
|
def test_changed_backup_rejected(self):
|
||||||
|
self.recovery.backup_verify.return_value[
|
||||||
|
"sha256"
|
||||||
|
] = "0" * 64
|
||||||
|
|
||||||
|
with self.assertRaises(ArchiveError):
|
||||||
|
self.archive.plan()
|
||||||
|
|
||||||
|
def test_runtime_verification_required(self):
|
||||||
|
self.recovery.runtime_check.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(ArchiveError):
|
||||||
|
self.archive.plan()
|
||||||
|
|
||||||
|
def test_health_verification_required(self):
|
||||||
|
self.fixture.health.verify.side_effect = None
|
||||||
|
self.fixture.health.verify.return_value = {
|
||||||
|
"healthy": False,
|
||||||
|
"release": "1",
|
||||||
|
}
|
||||||
|
|
||||||
|
with self.assertRaises(ArchiveError):
|
||||||
|
self.archive.plan()
|
||||||
|
|
||||||
|
def test_wrong_confirmation_rejected(self):
|
||||||
|
plan = self.archive.plan()
|
||||||
|
|
||||||
|
with self.assertRaises(ArchiveError):
|
||||||
|
self.archive.execute(
|
||||||
|
confirmation="INVALID",
|
||||||
|
fingerprint=plan["fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertFalse(self.marker.exists())
|
||||||
|
|
||||||
|
def test_wrong_fingerprint_rejected(self):
|
||||||
|
plan = self.archive.plan()
|
||||||
|
|
||||||
|
with self.assertRaises(ArchiveError):
|
||||||
|
self.archive.execute(
|
||||||
|
confirmation=plan["confirmation"],
|
||||||
|
fingerprint="0" * 64,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_modified_rollback_result_rejected(self):
|
||||||
|
self.rewrite(
|
||||||
|
self.fixture.executor.result_path(
|
||||||
|
self.identifier
|
||||||
|
),
|
||||||
|
active_release="99",
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(ArchiveError):
|
||||||
|
self.archive.plan()
|
||||||
|
|
||||||
|
def test_publication_failure_preserves_journal(self):
|
||||||
|
plan = self.archive.plan()
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"core.approval_store.os.link",
|
||||||
|
side_effect=OSError("publication failed"),
|
||||||
|
):
|
||||||
|
with self.assertRaises(ArchiveError):
|
||||||
|
self.archive.execute(
|
||||||
|
confirmation=plan["confirmation"],
|
||||||
|
fingerprint=plan["fingerprint"],
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.journal.load(),
|
||||||
|
self.transaction,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertFalse(self.marker.exists())
|
||||||
|
|
||||||
|
def test_concurrent_operation_rejected(self):
|
||||||
|
with DeploymentLock(self.planner.lock_path):
|
||||||
|
with self.assertRaises(LockError):
|
||||||
|
self.archive.plan()
|
||||||
|
|
||||||
|
def test_duplicate_archival_rejected(self):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
with self.assertRaises(ArchiveError):
|
||||||
|
self.archive.plan()
|
||||||
|
|
||||||
|
def test_no_database_restoration(self):
|
||||||
|
self.assertFalse(
|
||||||
|
self.execute()["database_restored"]
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_both_releases_preserved(self):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
for release in ("1", "2"):
|
||||||
|
self.assertTrue(
|
||||||
|
self.recovery.releases.release_path(
|
||||||
|
release
|
||||||
|
).is_dir()
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_failed_release_cannot_be_validated(self):
|
||||||
|
self.execute()
|
||||||
|
|
||||||
|
with self.assertRaises(Exception):
|
||||||
|
self.recovery.releases.validate("2")
|
||||||
|
|
||||||
|
def test_archive_readback(self):
|
||||||
|
result = self.execute()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.archive.load(self.identifier),
|
||||||
|
result,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,410 @@
|
|||||||
|
import copy
|
||||||
|
import json
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import Mock
|
||||||
|
|
||||||
|
from core.services import (
|
||||||
|
ServiceError,
|
||||||
|
ServiceLifecycle,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ServiceTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
|
||||||
|
self.config = json.loads(
|
||||||
|
Path("config/site.example.json").read_text()
|
||||||
|
)
|
||||||
|
|
||||||
|
self.runner = Mock(return_value=0)
|
||||||
|
|
||||||
|
self.manager = ServiceLifecycle(
|
||||||
|
self.config,
|
||||||
|
self.runner,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.prefix = [
|
||||||
|
"docker",
|
||||||
|
"compose",
|
||||||
|
"--project-name",
|
||||||
|
self.config["docker"]["project"],
|
||||||
|
"--project-directory",
|
||||||
|
self.config["site"]["root"],
|
||||||
|
"--file",
|
||||||
|
self.config["site"]["root"] + "/compose.yaml",
|
||||||
|
]
|
||||||
|
|
||||||
|
def commands(self):
|
||||||
|
|
||||||
|
return [
|
||||||
|
list(call.args[0])
|
||||||
|
for call in self.runner.call_args_list
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_no_commands_on_initialisation(self):
|
||||||
|
|
||||||
|
self.runner.assert_not_called()
|
||||||
|
|
||||||
|
def test_quiesce_workers(self):
|
||||||
|
|
||||||
|
self.manager.quiesce()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.commands(),
|
||||||
|
[
|
||||||
|
self.prefix + [
|
||||||
|
"stop", "--timeout", "90",
|
||||||
|
"queue", "scheduler",
|
||||||
|
],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_restart_php(self):
|
||||||
|
|
||||||
|
self.manager.restart_php()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.commands(),
|
||||||
|
[
|
||||||
|
self.prefix + [
|
||||||
|
"restart", "--timeout", "90", "php",
|
||||||
|
],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_validate_nginx(self):
|
||||||
|
|
||||||
|
self.manager.validate_nginx()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.commands(),
|
||||||
|
[
|
||||||
|
self.prefix + [
|
||||||
|
"exec", "-T", "--interactive=false",
|
||||||
|
"web", "nginx", "-t",
|
||||||
|
],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_reload_nginx(self):
|
||||||
|
|
||||||
|
self.manager.reload_nginx()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.commands(),
|
||||||
|
[
|
||||||
|
self.prefix + [
|
||||||
|
"exec", "-T", "--interactive=false",
|
||||||
|
"web", "nginx", "-t",
|
||||||
|
],
|
||||||
|
self.prefix + [
|
||||||
|
"exec", "-T", "--interactive=false",
|
||||||
|
"web", "nginx", "-s", "reload",
|
||||||
|
],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_resume_workers(self):
|
||||||
|
|
||||||
|
self.manager.resume()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.commands(),
|
||||||
|
[
|
||||||
|
self.prefix + [
|
||||||
|
"up", "-d", "--no-deps",
|
||||||
|
"queue", "scheduler",
|
||||||
|
],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_refresh_application(self):
|
||||||
|
|
||||||
|
self.manager.refresh()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.commands(),
|
||||||
|
[
|
||||||
|
self.prefix + [
|
||||||
|
"restart", "--timeout", "90", "php",
|
||||||
|
],
|
||||||
|
self.prefix + [
|
||||||
|
"exec", "-T", "--interactive=false",
|
||||||
|
"web", "nginx", "-t",
|
||||||
|
],
|
||||||
|
self.prefix + [
|
||||||
|
"exec", "-T", "--interactive=false",
|
||||||
|
"web", "nginx", "-s", "reload",
|
||||||
|
],
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_custom_php_service(self):
|
||||||
|
|
||||||
|
self.config["docker"]["php_service"] = "application"
|
||||||
|
|
||||||
|
manager = ServiceLifecycle(
|
||||||
|
self.config,
|
||||||
|
self.runner,
|
||||||
|
)
|
||||||
|
|
||||||
|
manager.restart_php()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.commands()[0][-1],
|
||||||
|
"application",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_custom_web_service(self):
|
||||||
|
|
||||||
|
self.config["docker"]["web_service"] = "frontend"
|
||||||
|
|
||||||
|
manager = ServiceLifecycle(
|
||||||
|
self.config,
|
||||||
|
self.runner,
|
||||||
|
)
|
||||||
|
|
||||||
|
manager.validate_nginx()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.commands()[0][-3:],
|
||||||
|
["frontend", "nginx", "-t"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_custom_worker_services(self):
|
||||||
|
|
||||||
|
self.config["docker"]["queue_service"] = "jobs"
|
||||||
|
self.config["docker"]["scheduler_service"] = "cron"
|
||||||
|
|
||||||
|
manager = ServiceLifecycle(
|
||||||
|
self.config,
|
||||||
|
self.runner,
|
||||||
|
)
|
||||||
|
|
||||||
|
manager.quiesce()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.commands()[0][-2:],
|
||||||
|
["jobs", "cron"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_stop_failure_rejected(self):
|
||||||
|
|
||||||
|
self.runner.return_value = 1
|
||||||
|
|
||||||
|
with self.assertRaises(ServiceError):
|
||||||
|
self.manager.quiesce()
|
||||||
|
|
||||||
|
def test_php_failure_rejected(self):
|
||||||
|
|
||||||
|
self.runner.return_value = 1
|
||||||
|
|
||||||
|
with self.assertRaises(ServiceError):
|
||||||
|
self.manager.restart_php()
|
||||||
|
|
||||||
|
def test_nginx_validation_failure_rejected(self):
|
||||||
|
|
||||||
|
self.runner.return_value = 1
|
||||||
|
|
||||||
|
with self.assertRaises(ServiceError):
|
||||||
|
self.manager.validate_nginx()
|
||||||
|
|
||||||
|
def test_nginx_reload_failure_rejected(self):
|
||||||
|
|
||||||
|
self.runner.side_effect = [0, 1]
|
||||||
|
|
||||||
|
with self.assertRaises(ServiceError):
|
||||||
|
self.manager.reload_nginx()
|
||||||
|
|
||||||
|
def test_worker_resume_failure_rejected(self):
|
||||||
|
|
||||||
|
self.runner.return_value = 1
|
||||||
|
|
||||||
|
with self.assertRaises(ServiceError):
|
||||||
|
self.manager.resume()
|
||||||
|
|
||||||
|
def test_php_failure_stops_refresh(self):
|
||||||
|
|
||||||
|
self.runner.return_value = 1
|
||||||
|
|
||||||
|
with self.assertRaises(ServiceError):
|
||||||
|
self.manager.refresh()
|
||||||
|
|
||||||
|
self.assertEqual(self.runner.call_count, 1)
|
||||||
|
|
||||||
|
def test_nginx_validation_prevents_reload(self):
|
||||||
|
|
||||||
|
self.runner.return_value = 1
|
||||||
|
|
||||||
|
with self.assertRaises(ServiceError):
|
||||||
|
self.manager.reload_nginx()
|
||||||
|
|
||||||
|
self.assertEqual(self.runner.call_count, 1)
|
||||||
|
|
||||||
|
def test_refresh_does_not_restart_workers(self):
|
||||||
|
|
||||||
|
self.manager.refresh()
|
||||||
|
|
||||||
|
self.assertFalse(
|
||||||
|
any(
|
||||||
|
"queue" in cmd or "scheduler" in cmd
|
||||||
|
for cmd in self.commands()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_configuration_copied(self):
|
||||||
|
|
||||||
|
original = copy.deepcopy(self.config)
|
||||||
|
|
||||||
|
self.manager.refresh()
|
||||||
|
|
||||||
|
self.assertEqual(self.config, original)
|
||||||
|
|
||||||
|
def test_later_configuration_mutation_ignored(self):
|
||||||
|
|
||||||
|
self.config["docker"]["php_service"] = "changed"
|
||||||
|
|
||||||
|
self.manager.restart_php()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.commands()[0][-1],
|
||||||
|
"php",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invalid_runner_rejected(self):
|
||||||
|
|
||||||
|
with self.assertRaises(ServiceError):
|
||||||
|
|
||||||
|
ServiceLifecycle(self.config, None)
|
||||||
|
|
||||||
|
def test_runner_exception_rejected(self):
|
||||||
|
|
||||||
|
self.runner.side_effect = OSError("failure")
|
||||||
|
|
||||||
|
with self.assertRaises(ServiceError):
|
||||||
|
self.manager.quiesce()
|
||||||
|
|
||||||
|
def test_boolean_runner_result_rejected(self):
|
||||||
|
|
||||||
|
self.runner.return_value = False
|
||||||
|
|
||||||
|
with self.assertRaises(ServiceError):
|
||||||
|
self.manager.quiesce()
|
||||||
|
|
||||||
|
def test_missing_runner_result_rejected(self):
|
||||||
|
|
||||||
|
self.runner.return_value = None
|
||||||
|
|
||||||
|
with self.assertRaises(ServiceError):
|
||||||
|
self.manager.quiesce()
|
||||||
|
|
||||||
|
def test_command_timeout_passed(self):
|
||||||
|
|
||||||
|
self.manager.quiesce()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.runner.call_args.kwargs["timeout"],
|
||||||
|
120,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_nginx_timeout_passed(self):
|
||||||
|
|
||||||
|
self.manager.validate_nginx()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.runner.call_args.kwargs["timeout"],
|
||||||
|
30,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invalid_stop_timeout_rejected(self):
|
||||||
|
|
||||||
|
for value in (0, -1, True, 301, "90"):
|
||||||
|
|
||||||
|
with self.subTest(value=value):
|
||||||
|
|
||||||
|
with self.assertRaises(ServiceError):
|
||||||
|
|
||||||
|
ServiceLifecycle(
|
||||||
|
self.config,
|
||||||
|
self.runner,
|
||||||
|
stop_timeout=value,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_custom_stop_timeout(self):
|
||||||
|
|
||||||
|
manager = ServiceLifecycle(
|
||||||
|
self.config,
|
||||||
|
self.runner,
|
||||||
|
stop_timeout=60,
|
||||||
|
)
|
||||||
|
|
||||||
|
manager.quiesce()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.commands()[0][-4:],
|
||||||
|
["--timeout", "60", "queue", "scheduler"],
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.runner.call_args.kwargs["timeout"],
|
||||||
|
90,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_no_destructive_compose_commands(self):
|
||||||
|
|
||||||
|
self.manager.quiesce()
|
||||||
|
self.manager.refresh()
|
||||||
|
self.manager.resume()
|
||||||
|
|
||||||
|
forbidden = {
|
||||||
|
"down", "rm", "prune", "--volumes",
|
||||||
|
"--remove-orphans", "--force-recreate",
|
||||||
|
}
|
||||||
|
|
||||||
|
for command in self.commands():
|
||||||
|
|
||||||
|
self.assertFalse(
|
||||||
|
set(command) & forbidden
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invalid_configuration_rejected(self):
|
||||||
|
|
||||||
|
self.config["docker"]["php_service"] = "../bad"
|
||||||
|
|
||||||
|
with self.assertRaises(ServiceError):
|
||||||
|
|
||||||
|
ServiceLifecycle(
|
||||||
|
self.config,
|
||||||
|
self.runner,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_root_path_binding(self):
|
||||||
|
|
||||||
|
self.manager.refresh()
|
||||||
|
|
||||||
|
for command in self.commands():
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
command[:len(self.prefix)],
|
||||||
|
self.prefix,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_sensitive_runner_exception_not_exposed(self):
|
||||||
|
|
||||||
|
self.runner.side_effect = RuntimeError(
|
||||||
|
"private-secret"
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(ServiceError) as result:
|
||||||
|
self.manager.quiesce()
|
||||||
|
|
||||||
|
self.assertNotIn(
|
||||||
|
"private-secret",
|
||||||
|
str(result.exception),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
import copy
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from core.configuration import load_config
|
||||||
|
from core.site_policy import (
|
||||||
|
SitePolicyError,
|
||||||
|
validate_site,
|
||||||
|
validate_registry,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
|
||||||
|
|
||||||
|
class SitePolicyTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.config = load_config(
|
||||||
|
ROOT / "config/site.example.json"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.other = copy.deepcopy(self.config)
|
||||||
|
|
||||||
|
self.other["site"].update({
|
||||||
|
"identifier": "other-absdev-net",
|
||||||
|
"domain": "other.absdev.net",
|
||||||
|
"root": "/opt/laravel-sites/other-absdev-net",
|
||||||
|
"origin_port": 8198,
|
||||||
|
})
|
||||||
|
|
||||||
|
self.other["docker"]["project"] = (
|
||||||
|
"site-other-absdev-net"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.other["database"]["name"] = "other_db"
|
||||||
|
self.other["database"]["username"] = "other_app"
|
||||||
|
|
||||||
|
def test_valid_site(self):
|
||||||
|
result = validate_site(self.config)
|
||||||
|
self.assertEqual(result["status"], "VALID")
|
||||||
|
|
||||||
|
def test_root_must_match_identifier(self):
|
||||||
|
self.config["site"]["root"] = (
|
||||||
|
"/opt/laravel-sites/different"
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_site(self.config)
|
||||||
|
|
||||||
|
def test_untrusted_root_rejected(self):
|
||||||
|
self.config["site"]["root"] = "/etc"
|
||||||
|
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_site(self.config)
|
||||||
|
|
||||||
|
def test_nested_root_rejected(self):
|
||||||
|
self.config["site"]["root"] = (
|
||||||
|
"/opt/laravel-sites/nested/example-absdev-net"
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_site(self.config)
|
||||||
|
|
||||||
|
def test_double_slash_rejected(self):
|
||||||
|
self.config["site"]["root"] = (
|
||||||
|
"//opt/laravel-sites/example-absdev-net"
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_site(self.config)
|
||||||
|
|
||||||
|
def test_project_must_match_site(self):
|
||||||
|
self.config["docker"]["project"] = "other-project"
|
||||||
|
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_site(self.config)
|
||||||
|
|
||||||
|
def test_root_database_user_rejected(self):
|
||||||
|
self.config["database"]["username"] = "root"
|
||||||
|
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_site(self.config)
|
||||||
|
|
||||||
|
def test_postgres_admin_rejected(self):
|
||||||
|
self.config["database"]["username"] = "postgres"
|
||||||
|
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_site(self.config)
|
||||||
|
|
||||||
|
def test_mysql_system_database_rejected(self):
|
||||||
|
self.config["database"]["name"] = "mysql"
|
||||||
|
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_site(self.config)
|
||||||
|
|
||||||
|
def test_postgres_system_database_rejected(self):
|
||||||
|
self.config["database"]["name"] = "template1"
|
||||||
|
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_site(self.config)
|
||||||
|
|
||||||
|
def test_distinct_services_required(self):
|
||||||
|
self.config["docker"]["queue_service"] = (
|
||||||
|
self.config["docker"]["php_service"]
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_site(self.config)
|
||||||
|
|
||||||
|
def test_distinct_networks_required(self):
|
||||||
|
self.config["docker"]["proxy_network"] = (
|
||||||
|
self.config["docker"]["backend_network"]
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_site(self.config)
|
||||||
|
|
||||||
|
def test_reserved_origin_port_rejected(self):
|
||||||
|
self.config["site"]["origin_port"] = 443
|
||||||
|
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_site(self.config)
|
||||||
|
|
||||||
|
def test_valid_registry(self):
|
||||||
|
result = validate_registry([
|
||||||
|
self.config, self.other,
|
||||||
|
])
|
||||||
|
|
||||||
|
self.assertEqual(result["site_count"], 2)
|
||||||
|
self.assertEqual(result["status"], "VALID")
|
||||||
|
|
||||||
|
def test_duplicate_site_rejected(self):
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_registry([
|
||||||
|
self.config, self.config,
|
||||||
|
])
|
||||||
|
|
||||||
|
def test_duplicate_domain_rejected(self):
|
||||||
|
self.other["site"]["domain"] = (
|
||||||
|
self.config["site"]["domain"]
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_registry([
|
||||||
|
self.config, self.other,
|
||||||
|
])
|
||||||
|
|
||||||
|
def test_duplicate_port_rejected(self):
|
||||||
|
self.other["site"]["origin_port"] = (
|
||||||
|
self.config["site"]["origin_port"]
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_registry([
|
||||||
|
self.config, self.other,
|
||||||
|
])
|
||||||
|
|
||||||
|
def test_duplicate_database_rejected(self):
|
||||||
|
self.other["database"]["name"] = (
|
||||||
|
self.config["database"]["name"]
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_registry([
|
||||||
|
self.config, self.other,
|
||||||
|
])
|
||||||
|
|
||||||
|
def test_duplicate_database_user_rejected(self):
|
||||||
|
self.other["database"]["username"] = (
|
||||||
|
self.config["database"]["username"]
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_registry([
|
||||||
|
self.config, self.other,
|
||||||
|
])
|
||||||
|
|
||||||
|
def test_case_insensitive_database_conflict(self):
|
||||||
|
self.other["database"]["name"] = (
|
||||||
|
self.config["database"]["name"].upper()
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_registry([
|
||||||
|
self.config, self.other,
|
||||||
|
])
|
||||||
|
|
||||||
|
def test_shared_database_container_permitted(self):
|
||||||
|
self.assertEqual(
|
||||||
|
self.config["database"]["container"],
|
||||||
|
self.other["database"]["container"],
|
||||||
|
)
|
||||||
|
|
||||||
|
validate_registry([
|
||||||
|
self.config, self.other,
|
||||||
|
])
|
||||||
|
|
||||||
|
def test_registry_order_independent(self):
|
||||||
|
self.assertEqual(
|
||||||
|
validate_registry([
|
||||||
|
self.config, self.other,
|
||||||
|
]),
|
||||||
|
validate_registry([
|
||||||
|
self.other, self.config,
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_empty_registry_rejected(self):
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_registry([])
|
||||||
|
|
||||||
|
def test_invalid_registry_type_rejected(self):
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_registry("invalid")
|
||||||
|
|
||||||
|
def test_input_not_mutated(self):
|
||||||
|
before = copy.deepcopy(self.config)
|
||||||
|
validate_site(self.config)
|
||||||
|
self.assertEqual(self.config, before)
|
||||||
|
|
||||||
|
def test_execution_remains_disabled(self):
|
||||||
|
result = validate_site(self.config)
|
||||||
|
|
||||||
|
self.assertFalse(result["execution_permitted"])
|
||||||
|
self.assertFalse(result["runtime_verified"])
|
||||||
|
|
||||||
|
def test_registry_not_runtime_verification(self):
|
||||||
|
result = validate_registry([self.config])
|
||||||
|
|
||||||
|
self.assertFalse(result["runtime_verified"])
|
||||||
|
self.assertFalse(result["execution_permitted"])
|
||||||
|
|
||||||
|
def test_fingerprint_deterministic(self):
|
||||||
|
self.assertEqual(
|
||||||
|
validate_site(self.config),
|
||||||
|
validate_site(self.config),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invalid_configuration_wrapped(self):
|
||||||
|
del self.config["database"]
|
||||||
|
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_site(self.config)
|
||||||
|
|
||||||
|
def test_reserved_username_case_insensitive(self):
|
||||||
|
self.config["database"]["username"] = "ROOT"
|
||||||
|
|
||||||
|
with self.assertRaises(SitePolicyError):
|
||||||
|
validate_site(self.config)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,468 @@
|
|||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import stat
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from core.transactions import (
|
||||||
|
TransactionError,
|
||||||
|
TransactionJournal,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TransactionTests(unittest.TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.temp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.temp.cleanup)
|
||||||
|
|
||||||
|
self.root = Path(self.temp.name)
|
||||||
|
self.journal = TransactionJournal(self.root)
|
||||||
|
|
||||||
|
def create(self):
|
||||||
|
return self.journal.create(
|
||||||
|
site="example-absdev-net",
|
||||||
|
previous="1",
|
||||||
|
candidate="2",
|
||||||
|
revision="a" * 40,
|
||||||
|
provenance="b" * 64,
|
||||||
|
)
|
||||||
|
|
||||||
|
def advance(self, phase):
|
||||||
|
current = self.journal.load()
|
||||||
|
|
||||||
|
return self.journal.transition(
|
||||||
|
current["transaction_id"],
|
||||||
|
current["phase"],
|
||||||
|
phase,
|
||||||
|
)
|
||||||
|
|
||||||
|
def complete(self):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
for phase in (
|
||||||
|
"BACKED_UP",
|
||||||
|
"QUIESCED",
|
||||||
|
"ACTIVATING",
|
||||||
|
"ACTIVATED",
|
||||||
|
"VERIFIED",
|
||||||
|
):
|
||||||
|
self.advance(phase)
|
||||||
|
|
||||||
|
return self.journal.load()
|
||||||
|
|
||||||
|
def test_empty_journal(self):
|
||||||
|
self.assertIsNone(self.journal.load())
|
||||||
|
|
||||||
|
def test_create_transaction(self):
|
||||||
|
self.assertEqual(
|
||||||
|
self.create()["phase"], "PREPARED"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_transaction_identifier(self):
|
||||||
|
self.assertRegex(
|
||||||
|
self.create()["transaction_id"],
|
||||||
|
r"^[a-f0-9]{32}$",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_persistent_transaction(self):
|
||||||
|
original = self.create()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
TransactionJournal(self.root).load(),
|
||||||
|
original,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_duplicate_transaction_rejected(self):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
def test_file_permissions(self):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
stat.S_IMODE(
|
||||||
|
self.journal.path.stat().st_mode
|
||||||
|
),
|
||||||
|
0o600,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_initial_history(self):
|
||||||
|
result = self.create()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
len(result["history"]), 1
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
result["history"][0]["phase"],
|
||||||
|
"PREPARED",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_valid_transition(self):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.advance("BACKED_UP")["phase"],
|
||||||
|
"BACKED_UP",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invalid_transition_rejected(self):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.advance("ACTIVATED")
|
||||||
|
|
||||||
|
def test_unknown_phase_rejected(self):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.advance("UNKNOWN")
|
||||||
|
|
||||||
|
def test_duplicate_phase_rejected(self):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.advance("PREPARED")
|
||||||
|
|
||||||
|
def test_wrong_transaction_rejected(self):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.journal.transition(
|
||||||
|
"0" * 32,
|
||||||
|
"PREPARED",
|
||||||
|
"BACKED_UP",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_stale_phase_rejected(self):
|
||||||
|
transaction = self.create()
|
||||||
|
|
||||||
|
self.advance("BACKED_UP")
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.journal.transition(
|
||||||
|
transaction["transaction_id"],
|
||||||
|
"PREPARED",
|
||||||
|
"BACKED_UP",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_complete_transaction(self):
|
||||||
|
self.assertEqual(
|
||||||
|
self.complete()["phase"],
|
||||||
|
"VERIFIED",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_history_preserved(self):
|
||||||
|
result = self.complete()
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
[item["phase"] for item in result["history"]],
|
||||||
|
[
|
||||||
|
"PREPARED",
|
||||||
|
"BACKED_UP",
|
||||||
|
"QUIESCED",
|
||||||
|
"ACTIVATING",
|
||||||
|
"ACTIVATED",
|
||||||
|
"VERIFIED",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_verified_is_terminal(self):
|
||||||
|
self.complete()
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.advance("FAILED")
|
||||||
|
|
||||||
|
def test_failure_containment(self):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
result = self.advance("FAILED")
|
||||||
|
|
||||||
|
self.assertEqual(result["phase"], "FAILED")
|
||||||
|
|
||||||
|
def test_failed_is_terminal(self):
|
||||||
|
self.create()
|
||||||
|
self.advance("FAILED")
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.advance("BACKED_UP")
|
||||||
|
|
||||||
|
def test_corrupted_json_rejected(self):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
self.journal.path.write_text("{invalid")
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.journal.load()
|
||||||
|
|
||||||
|
def test_modified_evidence_rejected(self):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
data = json.loads(
|
||||||
|
self.journal.path.read_text()
|
||||||
|
)
|
||||||
|
|
||||||
|
data["candidate"] = "99"
|
||||||
|
|
||||||
|
self.journal.path.write_text(
|
||||||
|
json.dumps(data)
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.journal.load()
|
||||||
|
|
||||||
|
def test_duplicate_json_keys_rejected(self):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
self.journal.path.write_text(
|
||||||
|
'{"phase":"FAILED","phase":"VERIFIED"}'
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.journal.load()
|
||||||
|
|
||||||
|
def test_invalid_history_rejected(self):
|
||||||
|
data = self.create()
|
||||||
|
|
||||||
|
data["history"][0]["phase"] = "VERIFIED"
|
||||||
|
|
||||||
|
del data["checksum"]
|
||||||
|
|
||||||
|
data["checksum"] = hashlib.sha256(
|
||||||
|
json.dumps(
|
||||||
|
data,
|
||||||
|
sort_keys=True,
|
||||||
|
separators=(",", ":"),
|
||||||
|
allow_nan=False,
|
||||||
|
).encode()
|
||||||
|
).hexdigest()
|
||||||
|
|
||||||
|
self.journal.path.write_text(
|
||||||
|
json.dumps(data)
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.journal.load()
|
||||||
|
|
||||||
|
def test_symlink_rejected(self):
|
||||||
|
target = self.root / "external"
|
||||||
|
target.write_text("{}")
|
||||||
|
|
||||||
|
self.journal.path.symlink_to(target)
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.journal.load()
|
||||||
|
|
||||||
|
def test_hardlink_rejected(self):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
os.link(
|
||||||
|
self.journal.path,
|
||||||
|
self.root / "duplicate",
|
||||||
|
)
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.journal.load()
|
||||||
|
|
||||||
|
def test_insecure_permissions_rejected(self):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
self.journal.path.chmod(0o644)
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.journal.load()
|
||||||
|
|
||||||
|
def test_invalid_site_rejected(self):
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.journal.create(
|
||||||
|
"../outside",
|
||||||
|
"1",
|
||||||
|
"2",
|
||||||
|
"a" * 40,
|
||||||
|
"b" * 64,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invalid_revision_rejected(self):
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.journal.create(
|
||||||
|
"example",
|
||||||
|
"1",
|
||||||
|
"2",
|
||||||
|
"invalid",
|
||||||
|
"b" * 64,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invalid_candidate_rejected(self):
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.journal.create(
|
||||||
|
"example",
|
||||||
|
"1",
|
||||||
|
"../outside",
|
||||||
|
"a" * 40,
|
||||||
|
"b" * 64,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_same_release_rejected(self):
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.journal.create(
|
||||||
|
"example",
|
||||||
|
"1",
|
||||||
|
"1",
|
||||||
|
"a" * 40,
|
||||||
|
"b" * 64,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_atomic_write_failure(self):
|
||||||
|
original = self.create()
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"core.transactions.os.replace",
|
||||||
|
side_effect=OSError("Simulated failure"),
|
||||||
|
):
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.advance("BACKED_UP")
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.journal.load(), original
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_no_temporary_files_remaining(self):
|
||||||
|
self.complete()
|
||||||
|
|
||||||
|
self.assertFalse(
|
||||||
|
list(self.root.glob(".transaction-*"))
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_insecure_directory_rejected(self):
|
||||||
|
self.root.chmod(0o777)
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
TransactionJournal(self.root)
|
||||||
|
|
||||||
|
def test_concurrent_writer_rejected(self):
|
||||||
|
from core.locking import DeploymentLock, LockError
|
||||||
|
|
||||||
|
with DeploymentLock(
|
||||||
|
self.root / ".journal.lock"
|
||||||
|
):
|
||||||
|
with self.assertRaises(LockError):
|
||||||
|
self.create()
|
||||||
|
|
||||||
|
def test_invalid_provenance_rejected(self):
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.journal.create(
|
||||||
|
"example",
|
||||||
|
"1",
|
||||||
|
"2",
|
||||||
|
"a" * 40,
|
||||||
|
"invalid",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_failed_transition_preserves_evidence(self):
|
||||||
|
original = self.create()
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
self.advance("VERIFIED")
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.journal.load(), original
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def test_previous_provenance_persisted(self):
|
||||||
|
|
||||||
|
result = self.journal.create(
|
||||||
|
"example",
|
||||||
|
"1",
|
||||||
|
"2",
|
||||||
|
"a" * 40,
|
||||||
|
"b" * 64,
|
||||||
|
previous_revision="c" * 40,
|
||||||
|
previous_provenance="d" * 64,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
result["previous_revision"],
|
||||||
|
"c" * 40,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.journal.load()["previous_provenance"],
|
||||||
|
"d" * 64,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_partial_previous_evidence_rejected(self):
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
|
||||||
|
self.journal.create(
|
||||||
|
"example",
|
||||||
|
"1",
|
||||||
|
"2",
|
||||||
|
"a" * 40,
|
||||||
|
"b" * 64,
|
||||||
|
previous_revision="c" * 40,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invalid_previous_revision_rejected(self):
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
|
||||||
|
self.journal.create(
|
||||||
|
"example",
|
||||||
|
"1",
|
||||||
|
"2",
|
||||||
|
"a" * 40,
|
||||||
|
"b" * 64,
|
||||||
|
previous_revision="invalid",
|
||||||
|
previous_provenance="d" * 64,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_invalid_previous_provenance_rejected(self):
|
||||||
|
|
||||||
|
with self.assertRaises(TransactionError):
|
||||||
|
|
||||||
|
self.journal.create(
|
||||||
|
"example",
|
||||||
|
"1",
|
||||||
|
"2",
|
||||||
|
"a" * 40,
|
||||||
|
"b" * 64,
|
||||||
|
previous_revision="c" * 40,
|
||||||
|
previous_provenance="invalid",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_previous_evidence_survives_transition(self):
|
||||||
|
|
||||||
|
transaction = self.journal.create(
|
||||||
|
"example",
|
||||||
|
"1",
|
||||||
|
"2",
|
||||||
|
"a" * 40,
|
||||||
|
"b" * 64,
|
||||||
|
previous_revision="c" * 40,
|
||||||
|
previous_provenance="d" * 64,
|
||||||
|
)
|
||||||
|
|
||||||
|
result = self.journal.transition(
|
||||||
|
transaction["transaction_id"],
|
||||||
|
"PREPARED",
|
||||||
|
"BACKED_UP",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
result["previous_provenance"],
|
||||||
|
"d" * 64,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in New Issue
Block a user