diff --git a/tests/integration/test_postgresql.py b/tests/integration/test_postgresql.py new file mode 100644 index 0000000..02b512d --- /dev/null +++ b/tests/integration/test_postgresql.py @@ -0,0 +1,880 @@ +"""Disposable PostgreSQL 18 integration qualification.""" + +import io +import json +import os +import secrets +import socket +import subprocess +import tempfile +import time +import unittest + +from datetime import datetime, timezone +from pathlib import Path + +from core.backup import BackupEngine +from core.database import get_adapter +from core.execution import CommandRunner + + +ROOT = Path.cwd() + +IMAGE = ( + "sha256:" + "e742a2668255221388004f3a42b6150a21" + "03f5054ab3a4a93ae9e4f01e551c35" +) + +IMAGE_REF = "postgres@" + IMAGE + +LABEL = "absdev.framework.integration" + +SOURCE_DATABASE = "example_db" + +RESTORE_DATABASE = "isolated_restore_pgsql" + +USERNAME = "example_app" + + +def require(condition, message): + + if not condition: + raise RuntimeError(message) + + +def command(*args, data=None, timeout=75): + + result = subprocess.run( + args, + input=data, + stdin=( + subprocess.DEVNULL + if 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(): + + item = inspect(cid) + + if ( + item["Config"]["Labels"] or {} + ).get(LABEL) == "true": + continue + + inventory[cid] = { + "name": item["Name"], + "running": item["State"]["Running"], + "started": item["State"]["StartedAt"], + "restart_policy": ( + item["HostConfig"]["RestartPolicy"] + ), + } + + return inventory + + +class PostgreSQLIntegrationTests(unittest.TestCase): + + def test_backup_and_restore(self): + + if socket.gethostname().split(".")[0].lower() != "absdev-ci": + self.skipTest( + "Database integration requires ABSDEV-CI" + ) + + if os.environ.get("ABSDEV_INTEGRATION_TESTS") != "1": + self.skipTest( + "Explicit integration authorisation required" + ) + + require( + command( + "docker", "info", + "--format", "{{.Name}}", + ).strip() == b"absdev-ci", + "Unexpected Docker engine", + ) + + before = production_inventory() + + token = secrets.token_hex(8) + + password = secrets.token_hex(32) + + name = f"absdev-integration-pgsql-{token}" + + cid = None + + checks = [] + + 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) + + evidence = { + "driver": "pgsql", + "image": IMAGE, + "started_at": datetime.now( + timezone.utc + ).isoformat(), + "result": "INCOMPLETE", + } + + def passed(label): + checks.append(label) + print("PASS:", label, flush=True) + + def isolation(): + + item = inspect(cid) + + host = item["HostConfig"] + + labels = item["Config"]["Labels"] + + require( + item["Id"] == cid + and item["Name"] == "/" + name + and item["Image"] == IMAGE, + "Unexpected container identity", + ) + + require( + labels.get(LABEL) == "true" + and labels.get( + "absdev.integration.token" + ) == token, + "Unexpected 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" + and host["PidMode"] != "host" + and host["IpcMode"] != "host", + "PostgreSQL container isolation failed", + ) + + require( + host["Memory"] == 1073741824 + and host["MemorySwap"] == 1073741824 + and host["NanoCpus"] == 1000000000 + and host["PidsLimit"] == 256, + "PostgreSQL resource limits changed", + ) + + require( + any( + option in ( + "no-new-privileges", + "no-new-privileges:true", + "no-new-privileges=true", + ) + for option in host.get("SecurityOpt") or [] + ), + "Missing no-new-privileges restriction", + ) + + mounts = item["Mounts"] + + require( + len(mounts) == 1 + and mounts[0]["Type"] == "volume" + and mounts[0]["Destination"] + == "/var/lib/postgresql", + "Unexpected PostgreSQL storage", + ) + + for existing in before: + + for mount in inspect(existing)["Mounts"]: + + require( + mount["Source"] != mounts[0]["Source"], + "Shared database storage detected", + ) + + return item + + def sql(statement, database=SOURCE_DATABASE): + + isolation() + + require( + database in ( + SOURCE_DATABASE, + RESTORE_DATABASE, + ), + "Unsafe PostgreSQL database target", + ) + + return command( + "docker", "exec", cid, + "timeout", "-k", "5s", "30s", + "env", + "PGPASSFILE=/run/secrets/absdev-pgpass", + "psql", + "--no-password", + "--no-psqlrc", + "--tuples-only", + "--no-align", + "--set=ON_ERROR_STOP=1", + "--host=127.0.0.1", + "--port=5432", + "--username=" + USERNAME, + "--dbname=" + database, + "--command", statement, + timeout=40, + ) + + 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", + ) + + image = json.loads( + command( + "docker", "image", "inspect", IMAGE_REF + ) + )[0] + + require( + image["Id"] == IMAGE + and IMAGE_REF in image["RepoDigests"], + "Unexpected PostgreSQL image", + ) + + passed("immutable_image_verified") + + print("\n=== CREATE DISPOSABLE POSTGRESQL ===") + + with tempfile.TemporaryDirectory( + dir=work + ) as directory: + + envfile = Path(directory) / "postgres.env" + + envfile.write_text( + f"POSTGRES_USER={USERNAME}\n" + f"POSTGRES_PASSWORD={password}\n" + f"POSTGRES_DB={SOURCE_DATABASE}\n" + "POSTGRES_INITDB_ARGS=" + "--auth-host=scram-sha-256\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, + "-c", "shared_buffers=64MB", + "-c", "max_connections=20", + "-c", "work_mem=4MB", + "-c", "maintenance_work_mem=32MB", + "-c", "password_encryption=scram-sha-256", + ).decode().strip() + + isolation() + + command("docker", "start", cid) + + isolation() + + passed("isolated_container_started") + + credentials = ( + f"127.0.0.1:5432:*:{USERNAME}:{password}\n" + ).encode() + + command( + "docker", "exec", "-i", cid, + "sh", "-c", + "umask 077; " + "mkdir -p /run/secrets; " + "cat > /run/secrets/absdev-pgpass", + data=credentials, + ) + + deadline = time.monotonic() + 120 + + while time.monotonic() < deadline: + + state = isolation()["State"] + + require( + state["Running"] + and not state["OOMKilled"], + "PostgreSQL stopped unexpectedly", + ) + + try: + + if sql("SELECT 1").strip() == b"1": + break + + except ( + RuntimeError, + subprocess.TimeoutExpired, + ): + pass + + time.sleep(2) + + else: + + raise RuntimeError( + "PostgreSQL readiness timed out" + ) + + passed("authenticated_tcp_readiness") + + config = json.loads( + (ROOT / "config/site.example.json") + .read_text() + ) + + config["database"].update({ + "driver": "pgsql", + "container": name, + "host": "127.0.0.1", + "port": 5432, + "name": SOURCE_DATABASE, + "username": USERNAME, + }) + + adapter = get_adapter(config) + + 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 adapter container", + ) + + result[index] = cid + + result[index + 1:index + 1] = [ + "timeout", "-k", "5s", "60s", + ] + + return result + + allowed = [ + bounded(adapter.identity_command()), + bounded(adapter.ping_command()), + bounded(adapter.version_command()), + bounded(adapter.backup_command()), + ] + + runner = CommandRunner( + allowed_commands=allowed, + timeout=75, + ) + + def guarded_runner(args, output): + + isolation() + + runner(bounded(args), output) + + output = io.BytesIO() + + guarded_runner( + adapter.ping_command(), + output, + ) + + self.assertEqual( + output.getvalue().strip(), + b"1", + ) + + passed("adapter_connectivity") + + output = io.BytesIO() + + guarded_runner( + adapter.version_command(), + output, + ) + + evidence["database_version"] = ( + output.getvalue().decode().strip() + ) + + print( + "PostgreSQL version:", + evidence["database_version"], + ) + + cluster = sql( + "SELECT system_identifier " + "FROM pg_control_system()" + ).decode().strip() + + self.assertTrue(cluster.isdigit()) + + evidence["cluster_system_identifier"] = cluster + + passed("cluster_identity_recorded") + + print("\n=== CREATE SYNTHETIC DATABASE ===") + + sql(""" + CREATE TABLE users ( + id BIGINT GENERATED BY DEFAULT + AS IDENTITY PRIMARY KEY, + name VARCHAR(255) NOT NULL, + email VARCHAR(255) NOT NULL UNIQUE + ); + + CREATE TABLE orders ( + id BIGINT GENERATED BY DEFAULT + AS IDENTITY PRIMARY KEY, + user_id BIGINT NOT NULL + REFERENCES users(id), + amount NUMERIC(12,2) NOT NULL, + payload BYTEA, + metadata JSONB NOT NULL + ); + + CREATE TABLE migrations ( + id INTEGER PRIMARY KEY, + migration VARCHAR(255) NOT NULL, + batch INTEGER NOT NULL + ); + + INSERT INTO users (name,email) VALUES + ('Alice','alice@example.invalid'), + ('José','jose@example.invalid'); + + INSERT INTO orders + (user_id,amount,payload,metadata) + VALUES + ( + 1,12.50, + decode('000102FF','hex'), + '{"status":"paid","quantity":2}' + ), + ( + 2,99.95, + decode('AABBCCDD','hex'), + '{"status":"pending","quantity":1}' + ); + + INSERT INTO migrations VALUES + (1,'create_users_table',1), + (2,'create_orders_table',1), + (3,'add_metadata_column',2); + + CREATE INDEX orders_user_idx + ON orders(user_id); + """) + + passed("synthetic_database_created") + + print("\n=== EXECUTE POSTGRESQL BACKUP ===") + + engine = BackupEngine( + adapter, + backup_root, + guarded_runner, + ) + + backup = engine.create() + + manifest = engine.verify(backup) + + dump = backup / "database.dump" + + with dump.open("rb") as handle: + + self.assertEqual( + handle.read(5), + b"PGDMP", + ) + + passed("custom_format_backup_verified") + + evidence["backup"] = str( + backup.relative_to(ROOT) + ) + + evidence["backup_sha256"] = manifest["sha256"] + + evidence["backup_bytes"] = manifest["bytes"] + + self.assertEqual( + manifest["identity"], + SOURCE_DATABASE + "|" + USERNAME, + ) + + passed("backup_manifest_identity") + + print("Backup bytes:", manifest["bytes"]) + print("SHA-256:", manifest["sha256"]) + + print("\n=== TRANSACTIONAL RESTORATION ===") + + sql( + "CREATE DATABASE isolated_restore_pgsql" + ) + + self.assertEqual( + sql( + "SELECT COUNT(*) " + "FROM information_schema.tables " + "WHERE table_schema='public'", + RESTORE_DATABASE, + ).strip(), + b"0", + ) + + passed("restore_target_empty") + + restore = bounded( + adapter.restore_command(RESTORE_DATABASE) + ) + + self.assertIn( + "--single-transaction", + restore, + ) + + self.assertIn( + "--exit-on-error", + restore, + ) + + engine.verify(backup) + + isolation() + + with dump.open("rb") as handle: + + result = subprocess.run( + restore, + stdin=handle, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=75, + ) + + require( + result.returncode == 0, + "PostgreSQL restoration failed", + ) + + passed("transactional_restore_completed") + + queries = { + "users": ( + "SELECT id,name,email " + "FROM users ORDER BY id" + ), + "orders": ( + "SELECT id,user_id,amount," + "encode(payload,'hex'),metadata " + "FROM orders ORDER BY id" + ), + "migrations": ( + "SELECT id,migration,batch " + "FROM migrations ORDER BY id" + ), + "table_columns": ( + "SELECT table_name,column_name," + "data_type,is_nullable,is_identity " + "FROM information_schema.columns " + "WHERE table_schema='public' " + "ORDER BY table_name,ordinal_position" + ), + "indexes": ( + "SELECT tablename,indexname,indexdef " + "FROM pg_indexes " + "WHERE schemaname='public' " + "ORDER BY tablename,indexname" + ), + "constraints": ( + "SELECT c.relname,k.conname," + "pg_get_constraintdef(k.oid) " + "FROM pg_constraint k " + "JOIN pg_class c ON c.oid=k.conrelid " + "JOIN pg_namespace n " + "ON n.oid=c.relnamespace " + "WHERE n.nspname='public' " + "ORDER BY c.relname,k.conname" + ), + "user_sequence": ( + "SELECT last_value,is_called " + "FROM users_id_seq" + ), + "order_sequence": ( + "SELECT last_value,is_called " + "FROM orders_id_seq" + ), + } + + for label, query in queries.items(): + + original = sql(query, SOURCE_DATABASE) + + restored = sql(query, RESTORE_DATABASE) + + self.assertTrue(original.strip()) + + self.assertEqual( + original, + restored, + f"Restoration mismatch: {label}", + ) + + passed(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", + ) + + passed("expected_record_counts") + + self.assertEqual( + sql( + "SELECT name FROM users WHERE id=2", + RESTORE_DATABASE, + ).strip(), + "José".encode(), + ) + + passed("unicode_data_preserved") + + self.assertEqual( + sql( + "SELECT encode(payload,'hex') " + "FROM orders ORDER BY id", + RESTORE_DATABASE, + ).strip(), + b"000102ff\naabbccdd", + ) + + passed("binary_data_preserved") + + self.assertEqual( + sql( + "SELECT metadata->>'status' " + "FROM orders ORDER BY id", + RESTORE_DATABASE, + ).strip(), + b"paid\npending", + ) + + passed("jsonb_data_preserved") + + self.assertEqual( + sql( + "INSERT INTO users (name,email) " + "VALUES ('Sequence Probe'," + "'probe@example.invalid') " + "RETURNING id", + RESTORE_DATABASE, + ).splitlines()[0], + b"3", + ) + + passed("identity_sequence_continues") + + self.assertEqual( + sql( + "SELECT COUNT(*) FROM users", + SOURCE_DATABASE, + ).strip(), + b"2", + ) + + passed("source_database_preserved") + + self.assertEqual( + engine.verify(backup), + manifest, + ) + + passed("original_backup_integrity") + + evidence["verified_checks"] = list(queries) + + evidence["result"] = ( + "POSTGRESQL_RESTORE_VERIFIED" + ) + + finally: + + print("\n=== REMOVE DISPOSABLE POSTGRESQL ===") + + if cid is not None: + + item = inspect(cid) + + labels = item["Config"]["Labels"] + + require( + item["Id"] == cid + and item["Name"] == "/" + name + and labels.get(LABEL) == "true" + and labels.get( + "absdev.integration.token" + ) == token, + "Unsafe cleanup target", + ) + + command( + "docker", "rm", "-f", "-v", cid + ) + + passed("disposable_container_removed") + + after = production_inventory() + + evidence["production_inventory_unchanged"] = ( + before == after + ) + + evidence["checks"] = checks + + 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, + "Existing container inventory changed", + ) + + print("PASS: Existing container inventory preserved") + + +if __name__ == "__main__": + unittest.main(verbosity=2)