diff --git a/tests/integration/test_mysql.py b/tests/integration/test_mysql.py index 40e0be4..b8cb451 100644 --- a/tests/integration/test_mysql.py +++ b/tests/integration/test_mysql.py @@ -1,11 +1,10 @@ """Disposable MySQL backup and restoration integration test.""" -import copy -import hashlib import io import json import os import secrets +import sys import subprocess import tempfile import time @@ -15,8 +14,8 @@ 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 +from core.backup import BackupEngine, BackupError +from core.execution import CommandRunner, ExecutionError ROOT = Path.cwd() @@ -705,17 +704,339 @@ class MySQLIntegrationTests(unittest.TestCase): print("PASS: Expected record counts verified") - print("\n=== VERIFY FOREIGN KEY ENFORCEMENT ===") + print("\n=== MYSQL FAILURE-PATH QUALIFICATION ===") - with self.assertRaises(RuntimeError): + failure_checks = [] - sql( - "INSERT INTO orders VALUES " - "(999, 999, 1.00, NULL)", - RESTORE_DATABASE, + 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, ) - print("PASS: Invalid foreign key rejected") + 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") + + 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 ===")