diff --git a/tests/integration/test_postgresql.py b/tests/integration/test_postgresql.py index 02b512d..c9bff60 100644 --- a/tests/integration/test_postgresql.py +++ b/tests/integration/test_postgresql.py @@ -4,6 +4,8 @@ import io import json import os import secrets +import shutil +import sys import socket import subprocess import tempfile @@ -13,9 +15,9 @@ import unittest from datetime import datetime, timezone from pathlib import Path -from core.backup import BackupEngine +from core.backup import BackupEngine, BackupError from core.database import get_adapter -from core.execution import CommandRunner +from core.execution import CommandRunner, ExecutionError ROOT = Path.cwd() @@ -807,6 +809,582 @@ class PostgreSQLIntegrationTests(unittest.TestCase): passed("original_backup_integrity") + print("\n=== POSTGRESQL FAILURE-PATH QUALIFICATION ===") + + failure_checks = [] + + def failure_pass(label): + failure_checks.append(label) + print("PASS:", label, flush=True) + + 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 failed_command(args, expected, statuses, data=None): + isolation() + + result = subprocess.run( + args, + input=data, + stdin=subprocess.DEVNULL if data is None else None, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + timeout=75, + ) + + self.assertIn(result.returncode, statuses) + + self.assertTrue( + expected in result.stderr, + "Expected PostgreSQL failure was not detected", + ) + + return result + + # 1. Invalid PostgreSQL credentials. + + invalid_credentials = ( + f"127.0.0.1:5432:*:{USERNAME}:" + f"{secrets.token_hex(32)}\n" + ).encode() + + self.assertNotEqual( + invalid_credentials, + credentials, + ) + + isolation() + + command( + "docker", "exec", "-i", cid, + "sh", "-c", + "umask 077; " + "cat > /run/secrets/absdev-invalid-pgpass", + data=invalid_credentials, + ) + + def invalid_auth(args): + return [ + "PGPASSFILE=/run/secrets/absdev-invalid-pgpass" + if arg == "PGPASSFILE=/run/secrets/absdev-pgpass" + else arg + for arg in bounded(args) + ] + + failed_command( + invalid_auth(adapter.ping_command()), + b"password authentication failed", + (2,), + ) + + failure_pass("invalid_credentials") + + # 2. Unavailable endpoint inside the isolated container. + + unavailable = [ + "--port=1" if arg == "--port=5432" else arg + for arg in bounded(adapter.ping_command()) + ] + + failed_command( + unavailable, + b"Connection refused", + (2,), + ) + + failure_pass("unavailable_database_endpoint") + + # 3. Real pg_dump authentication failure. + + invalid_dump = invalid_auth(adapter.backup_command()) + + bad_runner = CommandRunner( + allowed_commands=[invalid_dump], + timeout=75, + ) + + output = io.BytesIO() + + isolation() + + with self.assertRaisesRegex( + ExecutionError, + "Command exited with status", + ): + bad_runner(invalid_dump, output) + + self.assertEqual(output.getvalue(), b"") + + failure_pass("real_dump_failure_no_output") + + # 4. Failed backup must not be published. + + failed_root = work / "failed-dump" + failed_root.mkdir(mode=0o700) + + def failed_runner(args, output): + isolation() + + if args == adapter.backup_command(): + bad_runner(invalid_dump, output) + else: + guarded_runner(args, output) + + failed_engine = BackupEngine( + adapter, + failed_root, + failed_runner, + ) + + with self.assertRaises(BackupError) as failure: + failed_engine.create() + + self.assertIsInstance( + failure.exception.__cause__, + ExecutionError, + ) + + self.assertEqual(list(failed_root.iterdir()), []) + + failure_pass("failed_backup_not_published") + + # 5. Inject partial backup output. + + partial_root = work / "partial-backup" + partial_root.mkdir(mode=0o700) + + def partial_runner(args, output): + isolation() + + if args == adapter.backup_command(): + output.write(b"partial PostgreSQL archive") + raise ExecutionError("Injected dump failure") + + guarded_runner(args, output) + + partial_engine = BackupEngine( + adapter, + partial_root, + partial_runner, + ) + + with self.assertRaises(BackupError): + partial_engine.create() + + self.assertEqual(list(partial_root.iterdir()), []) + + failure_pass("partial_backup_cleanup") + + # 6. Host execution timeout and output staging. + + slow = [ + sys.executable, + "-B", + "-c", + "import time; print('partial', flush=True); time.sleep(10)", + ] + + timeout_runner = CommandRunner( + allowed_commands=[slow], + timeout=1, + ) + + output = io.BytesIO() + + with self.assertRaisesRegex( + ExecutionError, + "Command execution timed out", + ): + timeout_runner(slow, output) + + self.assertEqual(output.getvalue(), b"") + + failure_pass("command_timeout_no_output") + + # 7. PostgreSQL server-side statement timeout. + + def query_args(statement, database): + self.assertIn( + database, + (SOURCE_DATABASE, RESTORE_DATABASE), + ) + + args = bounded(adapter.query_command(statement)) + + args = [ + "--dbname=" + database + if arg == "--dbname=" + SOURCE_DATABASE + else arg + for arg in args + ] + + args.extend([ + "--set=VERBOSITY=verbose", + ]) + + return args + + failed_command( + query_args( + "SET statement_timeout='500ms'; " + "SELECT pg_sleep(10)", + SOURCE_DATABASE, + ), + b"57014", + (1, 3), + ) + + failure_pass("server_statement_timeout") + + # 8. Reject unauthorised execution. + + output = io.BytesIO() + + with self.assertRaisesRegex( + ExecutionError, + "Command is not authorised", + ): + runner( + [sys.executable, "-c", "print('unauthorised')"], + output, + ) + + self.assertEqual(output.getvalue(), b"") + + failure_pass("unauthorised_command_rejected") + + # 9. Reject a corrupted PostgreSQL backup. + + corrupt_root = work / "corrupt-backup" + corrupt_root.mkdir(mode=0o700) + + corrupt_backup = corrupt_root / backup.name + + shutil.copytree(backup, corrupt_backup) + + corrupt_dump = corrupt_backup / "database.dump" + + content = bytearray(corrupt_dump.read_bytes()) + + content[len(content) // 2] ^= 1 + + corrupt_dump.write_bytes(content) + + def forbidden(*args): + raise AssertionError("External execution prohibited") + + corrupt_engine = BackupEngine( + adapter, + corrupt_root, + forbidden, + ) + + with self.assertRaises(BackupError): + corrupt_engine.verify(corrupt_backup) + + shutil.rmtree(corrupt_backup) + + failure_pass("corrupted_archive_rejected") + + # 10. Foreign key enforcement. + + # Explicit IDs avoid changing sequence state during + # deliberately unsuccessful INSERT operations. + + failed_command( + query_args( + "INSERT INTO orders " + "(id,user_id,amount,metadata) " + "VALUES (999,999,1.00,'{}')", + RESTORE_DATABASE, + ), + b"23503", + (1, 3), + ) + + failure_pass("foreign_key_sqlstate_23503") + + # 11. Unique constraint enforcement. + + failed_command( + query_args( + "INSERT INTO users (id,name,email) " + "VALUES (999,'Duplicate','alice@example.invalid')", + RESTORE_DATABASE, + ), + b"23505", + (1, 3), + ) + + failure_pass("unique_constraint_sqlstate_23505") + + # 12. Verify neither database changed after failures. + + for label, query in queries.items(): + self.assertEqual( + sql(query, SOURCE_DATABASE), + source_snapshot[label], + f"Source changed: {label}", + ) + + self.assertEqual( + sql(query, RESTORE_DATABASE), + restore_snapshot[label], + f"Restore target changed: {label}", + ) + + failure_pass("database_contents_preserved") + + # 13. Successful backup following 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"], + ) + + failure_pass("backup_recovery_after_failure") + + self.assertEqual(engine.verify(backup), manifest) + + failure_pass("original_backup_integrity") + + self.assertEqual(len(failure_checks), 14) + + evidence["failure_checks"] = failure_checks + + evidence["recovery_backup"] = str( + recovery_backup.relative_to(ROOT) + ) + + evidence["recovery_backup_sha256"] = ( + recovery_manifest["sha256"] + ) + + print("\n=== TRANSACTIONAL RESTORATION ROLLBACK ===") + + rollback_checks = [] + + def rollback_pass(label): + rollback_checks.append(label) + print("PASS:", label, flush=True) + + # Reset only the verified disposable restore database. + + self.assertEqual( + RESTORE_DATABASE, + "isolated_restore_pgsql", + ) + + self.assertNotEqual( + SOURCE_DATABASE, + RESTORE_DATABASE, + ) + + adapter.validate_restore_target(RESTORE_DATABASE) + + def reset_restore_target(): + isolation() + + self.assertEqual( + sql( + "SELECT current_database()", + SOURCE_DATABASE, + ).strip(), + SOURCE_DATABASE.encode(), + ) + + sql("DROP DATABASE isolated_restore_pgsql") + sql("CREATE DATABASE isolated_restore_pgsql") + + self.assertEqual( + sql( + "SELECT COUNT(*) FROM information_schema.tables " + "WHERE table_schema='public'", + RESTORE_DATABASE, + ).strip(), + b"0", + ) + + reset_restore_target() + + rollback_pass("initial_target_empty") + + # Inspect the genuine archive's table ordering. + + isolation() + + listing = command( + "docker", "exec", "-i", cid, + "timeout", "-k", "5s", "30s", + "pg_restore", "--list", + data=dump.read_bytes(), + ).decode() + + table_order = [] + + for line in listing.splitlines(): + if " TABLE public " in line: + table_order.append( + line.split(" TABLE public ", 1)[1].split()[0] + ) + + self.assertEqual( + set(table_order), + {"users", "orders", "migrations"}, + ) + + self.assertEqual(len(table_order), 3) + + conflict = table_order[-1] + + self.assertIn( + conflict, + ("users", "orders", "migrations"), + ) + + rollback_pass("archive_table_order_verified") + + # The conflicting table is intentionally the final + # table in the archive's TABLE creation order. + + sql( + f"CREATE TABLE public.{conflict} " + "(marker TEXT PRIMARY KEY)", + RESTORE_DATABASE, + ) + + sql( + f"INSERT INTO public.{conflict} " + "VALUES ('preserve-existing-data')", + RESTORE_DATABASE, + ) + + self.assertEqual( + sql( + "SELECT table_name FROM information_schema.tables " + "WHERE table_schema='public' ORDER BY table_name", + RESTORE_DATABASE, + ).strip(), + conflict.encode(), + ) + + rollback_pass("conflicting_target_prepared") + + engine.verify(backup) + + # Capture the database's actual duplicate-relation + # error from pg_restore, not merely a generic failure. + + failed_command( + restore, + f'relation "{conflict}" already exists'.encode(), + (1,), + data=dump.read_bytes(), + ) + + rollback_pass("transactional_restore_failure_detected") + + # Earlier table creation must have been rolled back. + + self.assertEqual( + sql( + "SELECT table_name FROM information_schema.tables " + "WHERE table_schema='public' ORDER BY table_name", + RESTORE_DATABASE, + ).strip(), + conflict.encode(), + ) + + rollback_pass("partial_schema_changes_rolled_back") + + self.assertEqual( + sql( + f"SELECT marker FROM public.{conflict}", + RESTORE_DATABASE, + ).strip(), + b"preserve-existing-data", + ) + + rollback_pass("existing_target_data_preserved") + + self.assertEqual( + sql( + "SELECT COUNT(*) FROM pg_sequences " + "WHERE schemaname='public'", + RESTORE_DATABASE, + ).strip(), + b"0", + ) + + rollback_pass("partial_sequence_changes_rolled_back") + + reset_restore_target() + + rollback_pass("restore_target_recreated_empty") + + engine.verify(backup) + + isolation() + + with dump.open("rb") as handle: + recovered = subprocess.run( + restore, + stdin=handle, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=75, + ) + + self.assertEqual(recovered.returncode, 0) + + rollback_pass("recovery_restore_completed") + + for label, query in queries.items(): + self.assertEqual( + sql(query, SOURCE_DATABASE), + source_snapshot[label], + f"Source changed during rollback: {label}", + ) + + self.assertEqual( + sql(query, RESTORE_DATABASE), + source_snapshot[label], + f"Recovery mismatch: {label}", + ) + + rollback_pass("all_eight_data_and_schema_comparisons") + + self.assertEqual(engine.verify(backup), manifest) + + self.assertEqual( + engine.verify(recovery_backup), + recovery_manifest, + ) + + rollback_pass("original_and_recovery_backups_preserved") + + self.assertEqual(len(rollback_checks), 11) + + evidence["transaction_rollback_checks"] = rollback_checks + + print("PASS: All 14 PostgreSQL failure-path checks") + print("PASS: All 11 transactional recovery checks") + evidence["verified_checks"] = list(queries) evidence["result"] = (