1574 lines
44 KiB
Python
1574 lines
44 KiB
Python
"""Disposable MySQL backup and restoration integration test."""
|
|
|
|
import io
|
|
import json
|
|
import os
|
|
import secrets
|
|
import sys
|
|
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, BackupError
|
|
from core.execution import CommandRunner, ExecutionError
|
|
|
|
|
|
ROOT = Path.cwd()
|
|
|
|
IMAGE = (
|
|
"sha256:"
|
|
"8c233bad33d520a7aae1c1e619c3a9775"
|
|
"f4a1ba2d463d692fada04ec7f40be00"
|
|
)
|
|
|
|
IMAGE_REF = "mysql@" + IMAGE
|
|
|
|
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-ci":
|
|
self.skipTest(
|
|
"Database integration tests permitted only on ABSDEV-CI"
|
|
)
|
|
|
|
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"
|
|
)
|
|
|
|
runtime.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
require(
|
|
runtime.resolve() == runtime.absolute(),
|
|
"Unsafe integration runtime path",
|
|
)
|
|
|
|
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 >= 2097152,
|
|
"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_REF
|
|
)
|
|
)[0]
|
|
|
|
require(
|
|
image["Id"] == IMAGE
|
|
and IMAGE_REF in image["RepoDigests"],
|
|
"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", "1024m",
|
|
"--memory-swap", "1024m",
|
|
"--cpus", "1.0",
|
|
"--pids-limit", "256",
|
|
"--security-opt",
|
|
"no-new-privileges=true",
|
|
"--env-file", str(envfile),
|
|
IMAGE_REF,
|
|
"--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"] == 1024 * 1024 * 1024
|
|
and host["MemorySwap"]
|
|
== 1024 * 1024 * 1024
|
|
and host["NanoCpus"] == 1000000000
|
|
and host["PidsLimit"] == 256
|
|
and "no-new-privileges" in " ".join(
|
|
host.get("SecurityOpt") or []
|
|
),
|
|
"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")
|
|
|
|
verify_isolation()
|
|
|
|
# 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,
|
|
)
|
|
|
|
deadline = time.monotonic() + 300
|
|
|
|
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,
|
|
"mysql",
|
|
"--defaults-file=/run/secrets/absdev-client.cnf",
|
|
"--protocol=TCP",
|
|
"--host=127.0.0.1",
|
|
"--connect-timeout=3",
|
|
"--batch",
|
|
"--skip-column-names",
|
|
"--database=" + SOURCE_DATABASE,
|
|
"--execute",
|
|
"SELECT 1",
|
|
timeout=10,
|
|
)
|
|
|
|
if result.strip() == b"1":
|
|
break
|
|
|
|
except (RuntimeError, subprocess.TimeoutExpired):
|
|
pass
|
|
|
|
time.sleep(2)
|
|
|
|
else:
|
|
|
|
raise RuntimeError(
|
|
"MySQL readiness timed out"
|
|
)
|
|
|
|
print("PASS: Authenticated MySQL TCP service ready")
|
|
|
|
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=== MYSQL FAILURE-PATH QUALIFICATION ===")
|
|
|
|
failure_checks = []
|
|
|
|
source_snapshot = {
|
|
label: sql(query, SOURCE_DATABASE)
|
|
for label, query in queries.items()
|
|
}
|
|
|
|
restore_snapshot = {
|
|
label: sql(query, RESTORE_DATABASE)
|
|
for label, query in queries.items()
|
|
}
|
|
|
|
def passed(label):
|
|
failure_checks.append(label)
|
|
print("PASS:", label)
|
|
|
|
def expect_mysql_error(args, code, state, data=None):
|
|
verify_isolation()
|
|
|
|
result = subprocess.run(
|
|
args,
|
|
input=data,
|
|
stdin=(
|
|
subprocess.DEVNULL
|
|
if data is None else None
|
|
),
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE,
|
|
timeout=75,
|
|
)
|
|
|
|
expected = f"ERROR {code} ({state})".encode()
|
|
|
|
self.assertEqual(
|
|
result.returncode, 1,
|
|
"Expected MySQL command failure",
|
|
)
|
|
|
|
self.assertIn(
|
|
expected,
|
|
result.stderr,
|
|
f"Expected MySQL error {code} ({state})",
|
|
)
|
|
|
|
# 1. Invalid credentials.
|
|
|
|
wrong_client = client.replace(
|
|
password.encode(),
|
|
secrets.token_hex(32).encode(),
|
|
)
|
|
|
|
self.assertNotEqual(wrong_client, client)
|
|
|
|
command(
|
|
"docker", "exec", "-i", cid,
|
|
"sh", "-c",
|
|
"umask 077; "
|
|
"cat > /run/secrets/absdev-invalid.cnf",
|
|
input_data=wrong_client,
|
|
)
|
|
|
|
invalid_ping = [
|
|
"--defaults-file=/run/secrets/absdev-invalid.cnf"
|
|
if arg == adapter.client_configuration
|
|
else arg
|
|
for arg in bounded(adapter.ping_command())
|
|
]
|
|
|
|
expect_mysql_error(invalid_ping, 1045, "28000")
|
|
|
|
passed("invalid_credentials")
|
|
|
|
# 2. Unavailable local database endpoint.
|
|
|
|
unavailable = [
|
|
"--port=1" if arg == "--port=3306" else arg
|
|
for arg in bounded(adapter.ping_command())
|
|
]
|
|
|
|
expect_mysql_error(unavailable, 2003, "HY000")
|
|
|
|
passed("unavailable_database_endpoint")
|
|
|
|
# 3. Real mysqldump failure.
|
|
|
|
invalid_dump = [
|
|
"--defaults-file=/run/secrets/absdev-invalid.cnf"
|
|
if arg == adapter.client_configuration
|
|
else arg
|
|
for arg in bounded(adapter.backup_command())
|
|
]
|
|
|
|
bad_runner = CommandRunner(
|
|
allowed_commands=[invalid_dump],
|
|
timeout=75,
|
|
)
|
|
|
|
staged_output = io.BytesIO()
|
|
|
|
verify_isolation()
|
|
|
|
with self.assertRaisesRegex(
|
|
ExecutionError,
|
|
"Command exited with status",
|
|
):
|
|
bad_runner(invalid_dump, staged_output)
|
|
|
|
self.assertEqual(staged_output.getvalue(), b"")
|
|
|
|
passed("real_dump_failure_no_output")
|
|
|
|
# 4. Failed backup must not be published.
|
|
|
|
failure_root = work / "failed-dump"
|
|
failure_root.mkdir(mode=0o700)
|
|
|
|
def failed_dump_runner(args, output):
|
|
verify_isolation()
|
|
|
|
if args == adapter.backup_command():
|
|
bad_runner(invalid_dump, output)
|
|
else:
|
|
guarded_runner(args, output)
|
|
|
|
failed_engine = BackupEngine(
|
|
adapter,
|
|
failure_root,
|
|
failed_dump_runner,
|
|
)
|
|
|
|
with self.assertRaises(BackupError) as failure:
|
|
failed_engine.create()
|
|
|
|
self.assertIsInstance(
|
|
failure.exception.__cause__,
|
|
ExecutionError,
|
|
)
|
|
|
|
self.assertEqual(list(failure_root.iterdir()), [])
|
|
|
|
passed("failed_backup_not_published")
|
|
|
|
# 5. Partial backup cleanup.
|
|
|
|
partial_root = work / "partial-backup"
|
|
partial_root.mkdir(mode=0o700)
|
|
|
|
def partial_runner(args, output):
|
|
verify_isolation()
|
|
|
|
if args == adapter.backup_command():
|
|
output.write(b"partial synthetic SQL output")
|
|
raise ExecutionError("Injected partial backup failure")
|
|
|
|
guarded_runner(args, output)
|
|
|
|
partial_engine = BackupEngine(
|
|
adapter,
|
|
partial_root,
|
|
partial_runner,
|
|
)
|
|
|
|
with self.assertRaises(BackupError) as failure:
|
|
partial_engine.create()
|
|
|
|
self.assertIsInstance(
|
|
failure.exception.__cause__,
|
|
ExecutionError,
|
|
)
|
|
|
|
self.assertEqual(list(partial_root.iterdir()), [])
|
|
|
|
passed("partial_backup_cleanup")
|
|
|
|
# 6. Host command timeout and output staging.
|
|
|
|
slow_command = [
|
|
sys.executable,
|
|
"-B",
|
|
"-c",
|
|
"import time; print('partial', flush=True); time.sleep(10)",
|
|
]
|
|
|
|
timeout_runner = CommandRunner(
|
|
allowed_commands=[slow_command],
|
|
timeout=1,
|
|
)
|
|
|
|
output = io.BytesIO()
|
|
|
|
with self.assertRaisesRegex(
|
|
ExecutionError,
|
|
"Command execution timed out",
|
|
):
|
|
timeout_runner(slow_command, output)
|
|
|
|
self.assertEqual(output.getvalue(), b"")
|
|
|
|
passed("command_timeout_no_output")
|
|
|
|
# 7. Real MySQL command timeout.
|
|
|
|
slow_sql = [
|
|
"docker", "exec", cid,
|
|
"timeout", "-k", "2s", "2s",
|
|
"mysql",
|
|
adapter.client_configuration,
|
|
"--batch",
|
|
"--skip-column-names",
|
|
"--database=" + SOURCE_DATABASE,
|
|
"--execute",
|
|
"SELECT SLEEP(30)",
|
|
]
|
|
|
|
sql_timeout_runner = CommandRunner(
|
|
allowed_commands=[slow_sql],
|
|
timeout=10,
|
|
)
|
|
|
|
output = io.BytesIO()
|
|
|
|
verify_isolation()
|
|
|
|
with self.assertRaisesRegex(
|
|
ExecutionError,
|
|
"Command exited with status 124$",
|
|
):
|
|
sql_timeout_runner(slow_sql, output)
|
|
|
|
self.assertEqual(output.getvalue(), b"")
|
|
|
|
passed("mysql_statement_timeout")
|
|
|
|
# 8. Unauthorised command rejection.
|
|
|
|
output = io.BytesIO()
|
|
|
|
with self.assertRaisesRegex(
|
|
ExecutionError,
|
|
"Command is not authorised",
|
|
):
|
|
runner(
|
|
[sys.executable, "-c", "print('unauthorised')"],
|
|
output,
|
|
)
|
|
|
|
self.assertEqual(output.getvalue(), b"")
|
|
|
|
passed("unauthorised_command_rejected")
|
|
|
|
# 9. Invalid restoration SQL.
|
|
|
|
expect_mysql_error(
|
|
restore,
|
|
1064,
|
|
"42000",
|
|
data=b"THIS IS NOT VALID SQL;\n",
|
|
)
|
|
|
|
passed("invalid_restore_sql_rejected")
|
|
|
|
# 10. Exact foreign key error verification.
|
|
|
|
fk_command = [
|
|
"docker", "exec", cid,
|
|
"timeout", "-k", "5s", "60s",
|
|
"mysql",
|
|
adapter.client_configuration,
|
|
"--database=" + RESTORE_DATABASE,
|
|
"--execute",
|
|
"INSERT INTO orders VALUES (999, 999, 1.00, NULL)",
|
|
]
|
|
|
|
expect_mysql_error(fk_command, 1452, "23000")
|
|
|
|
passed("foreign_key_error_1452")
|
|
|
|
# 11. Verify source and restored data remain unchanged.
|
|
|
|
for label, query in queries.items():
|
|
self.assertEqual(
|
|
sql(query, SOURCE_DATABASE),
|
|
source_snapshot[label],
|
|
f"Source changed after failure: {label}",
|
|
)
|
|
|
|
self.assertEqual(
|
|
sql(query, RESTORE_DATABASE),
|
|
restore_snapshot[label],
|
|
f"Restore target changed after failure: {label}",
|
|
)
|
|
|
|
passed("database_contents_preserved")
|
|
|
|
# 12. Successful backup following controlled failures.
|
|
|
|
recovery_backup = engine.create()
|
|
recovery_manifest = engine.verify(recovery_backup)
|
|
|
|
self.assertNotEqual(recovery_backup, backup)
|
|
self.assertGreater(recovery_manifest["bytes"], 0)
|
|
|
|
self.assertEqual(
|
|
recovery_manifest["identity"],
|
|
manifest["identity"],
|
|
)
|
|
|
|
passed("backup_recovery_after_failure")
|
|
|
|
# 13. Original backup integrity.
|
|
|
|
self.assertEqual(
|
|
engine.verify(backup),
|
|
manifest,
|
|
)
|
|
|
|
passed("original_backup_integrity")
|
|
|
|
print("\n=== PARTIAL RESTORATION RECOVERY ===")
|
|
|
|
partial_checks = []
|
|
|
|
def partial_pass(label):
|
|
partial_checks.append(label)
|
|
print("PASS:", label)
|
|
|
|
# Only the already verified disposable restore target
|
|
# may be reset. Never operate on the source database.
|
|
|
|
self.assertEqual(
|
|
RESTORE_DATABASE,
|
|
"isolated_restore_mysql",
|
|
)
|
|
|
|
self.assertNotEqual(
|
|
RESTORE_DATABASE,
|
|
SOURCE_DATABASE,
|
|
)
|
|
|
|
adapter.validate_restore_target(RESTORE_DATABASE)
|
|
|
|
verify_isolation()
|
|
|
|
self.assertEqual(
|
|
sql("SELECT DATABASE()", RESTORE_DATABASE).strip(),
|
|
RESTORE_DATABASE.encode(),
|
|
)
|
|
|
|
sql("DROP DATABASE `isolated_restore_mysql`")
|
|
|
|
sql(
|
|
"CREATE DATABASE `isolated_restore_mysql` "
|
|
"CHARACTER SET utf8mb4"
|
|
)
|
|
|
|
self.assertEqual(
|
|
sql(
|
|
"SELECT COUNT(*) FROM information_schema.tables "
|
|
"WHERE TABLE_SCHEMA=DATABASE()",
|
|
RESTORE_DATABASE,
|
|
).strip(),
|
|
b"0",
|
|
)
|
|
|
|
partial_pass("initial_target_empty")
|
|
|
|
broken_sql = b"""
|
|
CREATE TABLE partial_probe (
|
|
id INT PRIMARY KEY,
|
|
description VARCHAR(100) NOT NULL
|
|
) ENGINE=InnoDB;
|
|
|
|
INSERT INTO partial_probe
|
|
VALUES (1, 'partially restored');
|
|
|
|
COMMIT;
|
|
|
|
THIS IS NOT VALID SQL;
|
|
|
|
CREATE TABLE must_not_exist (
|
|
id INT PRIMARY KEY
|
|
);
|
|
"""
|
|
|
|
expect_mysql_error(
|
|
restore,
|
|
1064,
|
|
"42000",
|
|
data=broken_sql,
|
|
)
|
|
|
|
partial_pass("partial_restore_error_1064")
|
|
|
|
self.assertEqual(
|
|
sql(
|
|
"SELECT description FROM partial_probe WHERE id=1",
|
|
RESTORE_DATABASE,
|
|
).strip(),
|
|
b"partially restored",
|
|
)
|
|
|
|
partial_pass("committed_partial_data_detected")
|
|
|
|
self.assertEqual(
|
|
sql(
|
|
"SELECT TABLE_NAME FROM information_schema.tables "
|
|
"WHERE TABLE_SCHEMA=DATABASE() "
|
|
"ORDER BY TABLE_NAME",
|
|
RESTORE_DATABASE,
|
|
).strip(),
|
|
b"partial_probe",
|
|
)
|
|
|
|
partial_pass("dirty_target_detected")
|
|
|
|
# Recreate only the disposable restoration database.
|
|
|
|
verify_isolation()
|
|
|
|
self.assertEqual(
|
|
sql("SELECT DATABASE()", RESTORE_DATABASE).strip(),
|
|
RESTORE_DATABASE.encode(),
|
|
)
|
|
|
|
sql("DROP DATABASE `isolated_restore_mysql`")
|
|
|
|
sql(
|
|
"CREATE DATABASE `isolated_restore_mysql` "
|
|
"CHARACTER SET utf8mb4"
|
|
)
|
|
|
|
self.assertEqual(
|
|
sql(
|
|
"SELECT COUNT(*) FROM information_schema.tables "
|
|
"WHERE TABLE_SCHEMA=DATABASE()",
|
|
RESTORE_DATABASE,
|
|
).strip(),
|
|
b"0",
|
|
)
|
|
|
|
partial_pass("restore_target_recreated_empty")
|
|
|
|
engine.verify(backup)
|
|
|
|
verify_isolation()
|
|
|
|
with (backup / "database.sql").open("rb") as handle:
|
|
recovered = subprocess.run(
|
|
restore,
|
|
stdin=handle,
|
|
stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.DEVNULL,
|
|
timeout=75,
|
|
)
|
|
|
|
self.assertEqual(
|
|
recovered.returncode,
|
|
0,
|
|
"Recovery restoration failed",
|
|
)
|
|
|
|
partial_pass("recovery_restore_completed")
|
|
|
|
for label, query in queries.items():
|
|
self.assertEqual(
|
|
sql(query, SOURCE_DATABASE),
|
|
source_snapshot[label],
|
|
f"Source changed during recovery: {label}",
|
|
)
|
|
|
|
self.assertEqual(
|
|
sql(query, RESTORE_DATABASE),
|
|
restore_snapshot[label],
|
|
f"Recovery mismatch: {label}",
|
|
)
|
|
|
|
partial_pass("all_six_data_and_schema_comparisons")
|
|
|
|
expect_mysql_error(
|
|
fk_command,
|
|
1452,
|
|
"23000",
|
|
)
|
|
|
|
partial_pass("foreign_key_enforcement_recovered")
|
|
|
|
self.assertEqual(
|
|
sql(
|
|
"SELECT TABLE_NAME FROM information_schema.tables "
|
|
"WHERE TABLE_SCHEMA=DATABASE() "
|
|
"ORDER BY TABLE_NAME",
|
|
RESTORE_DATABASE,
|
|
).strip(),
|
|
b"migrations\norders\nusers",
|
|
)
|
|
|
|
partial_pass("no_partial_tables_remaining")
|
|
|
|
self.assertEqual(engine.verify(backup), manifest)
|
|
|
|
self.assertEqual(
|
|
engine.verify(recovery_backup),
|
|
recovery_manifest,
|
|
)
|
|
|
|
partial_pass("original_and_recovery_backups_preserved")
|
|
|
|
self.assertEqual(len(partial_checks), 10)
|
|
|
|
evidence["partial_restore_checks"] = partial_checks
|
|
|
|
print("PASS: All 10 persistent partial recovery checks")
|
|
|
|
evidence["failure_checks"] = failure_checks
|
|
|
|
evidence["recovery_backup"] = str(
|
|
recovery_backup.relative_to(ROOT)
|
|
)
|
|
|
|
evidence["recovery_backup_sha256"] = (
|
|
recovery_manifest["sha256"]
|
|
)
|
|
|
|
self.assertEqual(len(failure_checks), 13)
|
|
|
|
print("PASS: All 13 failure-path checks completed")
|
|
|
|
print("\n=== VERIFY BACKUP INTEGRITY AGAIN ===")
|
|
|
|
engine.verify(backup)
|
|
|
|
evidence["verified_checks"] = list(queries)
|
|
|
|
print("\n=== CROSS-INSTANCE MYSQL RECOVERY ===")
|
|
|
|
cross_checks = []
|
|
|
|
def cross_pass(label):
|
|
cross_checks.append(label)
|
|
print("PASS:", label)
|
|
|
|
# Record the original server and storage identity.
|
|
|
|
original_uuid = sql(
|
|
"SELECT @@server_uuid",
|
|
SOURCE_DATABASE,
|
|
).strip().decode()
|
|
|
|
original_item = verify_isolation()
|
|
|
|
original_mounts = {
|
|
mount["Source"]
|
|
for mount in original_item["Mounts"]
|
|
}
|
|
|
|
self.assertTrue(original_uuid)
|
|
self.assertTrue(original_mounts)
|
|
|
|
self.assertEqual(
|
|
manifest["identity"].split(chr(9))[2],
|
|
original_uuid,
|
|
)
|
|
|
|
engine.verify(backup)
|
|
|
|
cross_pass("original_server_identity_recorded")
|
|
|
|
# Remove the original disposable instance.
|
|
# Recovery must not depend on its availability.
|
|
|
|
old_cid = cid
|
|
|
|
command("docker", "rm", "-f", "-v", cid)
|
|
|
|
cid = None
|
|
|
|
remaining = command(
|
|
"docker", "ps", "-aq", "--no-trunc"
|
|
).decode().splitlines()
|
|
|
|
self.assertNotIn(old_cid, remaining)
|
|
|
|
cross_pass("original_database_server_removed")
|
|
|
|
# Create a fresh independent server using the same
|
|
# verified immutable image and isolation restrictions.
|
|
|
|
with tempfile.TemporaryDirectory(dir=work) as directory:
|
|
|
|
envfile = Path(directory) / "mysql.env"
|
|
|
|
envfile.write_text(
|
|
f"MYSQL_ROOT_PASSWORD={password}\n"
|
|
f"MYSQL_DATABASE={RESTORE_DATABASE}\n"
|
|
)
|
|
|
|
envfile.chmod(0o600)
|
|
|
|
cid = command(
|
|
"docker", "create",
|
|
"--pull=never",
|
|
"--name", name,
|
|
"--label", f"{LABEL}=true",
|
|
"--label", f"absdev.integration.token={token}",
|
|
"--network", "none",
|
|
"--restart", "no",
|
|
"--memory", "1024m",
|
|
"--memory-swap", "1024m",
|
|
"--cpus", "1.0",
|
|
"--pids-limit", "256",
|
|
"--security-opt", "no-new-privileges=true",
|
|
"--env-file", str(envfile),
|
|
IMAGE_REF,
|
|
"--innodb-buffer-pool-size=64M",
|
|
"--max-connections=20",
|
|
"--performance-schema=OFF",
|
|
"--skip-log-bin",
|
|
).decode().strip()
|
|
|
|
self.assertNotEqual(cid, old_cid)
|
|
|
|
replacement = verify_isolation()
|
|
|
|
replacement_mounts = {
|
|
mount["Source"]
|
|
for mount in replacement["Mounts"]
|
|
}
|
|
|
|
self.assertTrue(replacement_mounts)
|
|
|
|
self.assertFalse(
|
|
original_mounts.intersection(replacement_mounts)
|
|
)
|
|
|
|
cross_pass("independent_container_and_storage")
|
|
|
|
command("docker", "start", cid)
|
|
|
|
verify_isolation()
|
|
|
|
command(
|
|
"docker", "exec", "-i", cid,
|
|
"sh", "-c",
|
|
"umask 077; "
|
|
"mkdir -p /run/secrets; "
|
|
"cat > /run/secrets/absdev-client.cnf",
|
|
input_data=client,
|
|
)
|
|
|
|
deadline = time.monotonic() + 90
|
|
|
|
while time.monotonic() < deadline:
|
|
|
|
state = verify_isolation()["State"]
|
|
|
|
require(
|
|
state["Running"] and not state["OOMKilled"],
|
|
"Replacement MySQL server stopped unexpectedly",
|
|
)
|
|
|
|
try:
|
|
if sql(
|
|
"SELECT 1",
|
|
RESTORE_DATABASE,
|
|
).strip() == b"1":
|
|
break
|
|
|
|
except (RuntimeError, subprocess.TimeoutExpired):
|
|
pass
|
|
|
|
time.sleep(2)
|
|
|
|
else:
|
|
raise RuntimeError(
|
|
"Replacement MySQL readiness timed out"
|
|
)
|
|
|
|
cross_pass("replacement_authenticated_readiness")
|
|
|
|
replacement_uuid = sql(
|
|
"SELECT @@server_uuid",
|
|
RESTORE_DATABASE,
|
|
).strip().decode()
|
|
|
|
self.assertTrue(replacement_uuid)
|
|
|
|
self.assertNotEqual(
|
|
replacement_uuid,
|
|
original_uuid,
|
|
)
|
|
|
|
cross_pass("independent_mysql_server_uuid")
|
|
|
|
self.assertEqual(
|
|
sql(
|
|
"SELECT COUNT(*) FROM information_schema.tables "
|
|
"WHERE TABLE_SCHEMA=DATABASE()",
|
|
RESTORE_DATABASE,
|
|
).strip(),
|
|
b"0",
|
|
)
|
|
|
|
cross_pass("replacement_restore_target_empty")
|
|
|
|
self.assertEqual(
|
|
sql(
|
|
"SELECT COUNT(*) FROM information_schema.schemata "
|
|
"WHERE schema_name='example_db'"
|
|
).strip(),
|
|
b"0",
|
|
)
|
|
|
|
cross_pass("original_source_database_absent")
|
|
|
|
# Rebuild the restoration command to bind it to the
|
|
# replacement container ID, not the removed instance.
|
|
|
|
cross_restore = bounded(
|
|
adapter.restore_command(RESTORE_DATABASE)
|
|
)
|
|
|
|
self.assertIn(cid, cross_restore)
|
|
self.assertNotIn(old_cid, cross_restore)
|
|
|
|
engine.verify(backup)
|
|
|
|
verify_isolation()
|
|
|
|
with (backup / "database.sql").open("rb") as handle:
|
|
|
|
restored = subprocess.run(
|
|
cross_restore,
|
|
stdin=handle,
|
|
stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.DEVNULL,
|
|
timeout=75,
|
|
)
|
|
|
|
self.assertEqual(
|
|
restored.returncode,
|
|
0,
|
|
"Independent server restoration failed",
|
|
)
|
|
|
|
cross_pass("cross_instance_restore_completed")
|
|
|
|
for label, query in queries.items():
|
|
|
|
self.assertEqual(
|
|
sql(query, RESTORE_DATABASE),
|
|
source_snapshot[label],
|
|
f"Independent server restoration mismatch: {label}",
|
|
)
|
|
|
|
cross_pass("all_six_cross_instance_comparisons")
|
|
|
|
cross_fk = [
|
|
"docker", "exec", cid,
|
|
"timeout", "-k", "5s", "60s",
|
|
"mysql",
|
|
adapter.client_configuration,
|
|
"--database=" + RESTORE_DATABASE,
|
|
"--execute",
|
|
"INSERT INTO orders VALUES (999,999,1.00,NULL)",
|
|
]
|
|
|
|
expect_mysql_error(
|
|
cross_fk,
|
|
1452,
|
|
"23000",
|
|
)
|
|
|
|
self.assertEqual(
|
|
sql(
|
|
"SELECT COUNT(*) FROM orders",
|
|
RESTORE_DATABASE,
|
|
).strip(),
|
|
b"2",
|
|
)
|
|
|
|
cross_pass("cross_instance_foreign_key_enforcement")
|
|
|
|
self.assertEqual(engine.verify(backup), manifest)
|
|
|
|
self.assertEqual(
|
|
engine.verify(recovery_backup),
|
|
recovery_manifest,
|
|
)
|
|
|
|
cross_pass("original_and_recovery_backups_preserved")
|
|
|
|
self.assertEqual(len(cross_checks), 11)
|
|
|
|
evidence["cross_instance_checks"] = cross_checks
|
|
|
|
evidence["original_server_uuid"] = original_uuid
|
|
|
|
evidence["restored_server_uuid"] = replacement_uuid
|
|
|
|
print("PASS: All 11 persistent cross-instance checks")
|
|
|
|
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)
|