1785 lines
49 KiB
Python
1785 lines
49 KiB
Python
"""Disposable PostgreSQL 18 integration qualification."""
|
|
|
|
import io
|
|
import json
|
|
import os
|
|
import secrets
|
|
import shutil
|
|
import sys
|
|
import socket
|
|
import subprocess
|
|
import tempfile
|
|
import time
|
|
import unittest
|
|
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
from core.backup import BackupEngine, BackupError
|
|
from core.database import get_adapter
|
|
from core.execution import CommandRunner, ExecutionError
|
|
|
|
|
|
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','[email protected]'),
|
|
('José','[email protected]');
|
|
|
|
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',"
|
|
"'[email protected]') "
|
|
"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")
|
|
|
|
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','[email protected]')",
|
|
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")
|
|
|
|
print("\n=== POSTGRESQL CROSS-INSTANCE RECOVERY ===")
|
|
|
|
cross_checks = []
|
|
|
|
def cross_pass(label):
|
|
cross_checks.append(label)
|
|
print("PASS:", label, flush=True)
|
|
|
|
# Record the original cluster and storage identity.
|
|
|
|
original_cluster = sql(
|
|
"SELECT system_identifier FROM pg_control_system()",
|
|
SOURCE_DATABASE,
|
|
).decode().strip()
|
|
|
|
self.assertTrue(original_cluster.isdigit())
|
|
|
|
self.assertEqual(
|
|
original_cluster,
|
|
evidence["cluster_system_identifier"],
|
|
)
|
|
|
|
original_item = isolation()
|
|
|
|
original_mounts = {
|
|
mount["Source"]
|
|
for mount in original_item["Mounts"]
|
|
}
|
|
|
|
self.assertTrue(original_mounts)
|
|
|
|
engine.verify(backup)
|
|
engine.verify(recovery_backup)
|
|
|
|
cross_pass("original_cluster_identity_recorded")
|
|
|
|
# Remove the original disposable cluster.
|
|
# Recovery must not depend on the original server.
|
|
|
|
old_cid = cid
|
|
|
|
isolation()
|
|
|
|
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_cluster_removed")
|
|
|
|
# Create an independent PostgreSQL cluster.
|
|
|
|
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={RESTORE_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()
|
|
|
|
self.assertNotEqual(cid, old_cid)
|
|
|
|
replacement = 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)
|
|
|
|
isolation()
|
|
|
|
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"],
|
|
"Replacement PostgreSQL cluster stopped",
|
|
)
|
|
|
|
try:
|
|
if sql(
|
|
"SELECT 1",
|
|
RESTORE_DATABASE,
|
|
).strip() == b"1":
|
|
break
|
|
|
|
except (
|
|
RuntimeError,
|
|
subprocess.TimeoutExpired,
|
|
):
|
|
pass
|
|
|
|
time.sleep(2)
|
|
|
|
else:
|
|
raise RuntimeError(
|
|
"Replacement PostgreSQL readiness timed out"
|
|
)
|
|
|
|
cross_pass("replacement_authenticated_readiness")
|
|
|
|
replacement_cluster = sql(
|
|
"SELECT system_identifier FROM pg_control_system()",
|
|
RESTORE_DATABASE,
|
|
).decode().strip()
|
|
|
|
self.assertTrue(replacement_cluster.isdigit())
|
|
|
|
self.assertNotEqual(
|
|
replacement_cluster,
|
|
original_cluster,
|
|
)
|
|
|
|
cross_pass("independent_cluster_identifier")
|
|
|
|
self.assertEqual(
|
|
sql(
|
|
"SELECT COUNT(*) FROM information_schema.tables "
|
|
"WHERE table_schema='public'",
|
|
RESTORE_DATABASE,
|
|
).strip(),
|
|
b"0",
|
|
)
|
|
|
|
cross_pass("replacement_restore_target_empty")
|
|
|
|
self.assertEqual(
|
|
sql(
|
|
"SELECT COUNT(*) FROM pg_database "
|
|
"WHERE datname='example_db'",
|
|
RESTORE_DATABASE,
|
|
).strip(),
|
|
b"0",
|
|
)
|
|
|
|
cross_pass("original_source_database_absent")
|
|
|
|
# Bind the restoration command to the replacement ID.
|
|
|
|
cross_restore = bounded(
|
|
adapter.restore_command(RESTORE_DATABASE)
|
|
)
|
|
|
|
self.assertIn(cid, cross_restore)
|
|
self.assertNotIn(old_cid, cross_restore)
|
|
|
|
self.assertIn("--single-transaction", cross_restore)
|
|
self.assertIn("--exit-on-error", cross_restore)
|
|
|
|
engine.verify(backup)
|
|
|
|
isolation()
|
|
|
|
with dump.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 PostgreSQL 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 cluster mismatch: {label}",
|
|
)
|
|
|
|
cross_pass("all_eight_cross_instance_comparisons")
|
|
|
|
# Verify that constraints remain active.
|
|
|
|
failed_command(
|
|
query_args(
|
|
"INSERT INTO orders "
|
|
"(id,user_id,amount,metadata) "
|
|
"VALUES (999,999,1.00,'{}')",
|
|
RESTORE_DATABASE,
|
|
),
|
|
b"23503",
|
|
(1, 3),
|
|
)
|
|
|
|
cross_pass("cross_instance_foreign_key_enforcement")
|
|
|
|
failed_command(
|
|
query_args(
|
|
"INSERT INTO users (id,name,email) "
|
|
"VALUES (999,'Duplicate','[email protected]')",
|
|
RESTORE_DATABASE,
|
|
),
|
|
b"23505",
|
|
(1, 3),
|
|
)
|
|
|
|
cross_pass("cross_instance_unique_constraint")
|
|
|
|
# Constraint failures must not alter recovered contents.
|
|
|
|
for label, query in queries.items():
|
|
|
|
self.assertEqual(
|
|
sql(query, RESTORE_DATABASE),
|
|
source_snapshot[label],
|
|
f"Recovered data changed: {label}",
|
|
)
|
|
|
|
cross_pass("cross_instance_data_preserved")
|
|
|
|
# Both identity sequences must continue correctly.
|
|
|
|
self.assertEqual(
|
|
sql(
|
|
"INSERT INTO users (name,email) "
|
|
"VALUES ('Recovery Probe','[email protected]') "
|
|
"RETURNING id",
|
|
RESTORE_DATABASE,
|
|
).splitlines()[0],
|
|
b"3",
|
|
)
|
|
|
|
self.assertEqual(
|
|
sql(
|
|
"INSERT INTO orders "
|
|
"(user_id,amount,payload,metadata) "
|
|
"VALUES (3,1.25,decode('FF','hex'),'{}') "
|
|
"RETURNING id",
|
|
RESTORE_DATABASE,
|
|
).splitlines()[0],
|
|
b"3",
|
|
)
|
|
|
|
cross_pass("cross_instance_identity_sequences_continue")
|
|
|
|
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), 14)
|
|
|
|
evidence["cross_instance_checks"] = cross_checks
|
|
|
|
evidence["original_cluster_system_identifier"] = (
|
|
original_cluster
|
|
)
|
|
|
|
evidence["restored_cluster_system_identifier"] = (
|
|
replacement_cluster
|
|
)
|
|
|
|
print("PASS: All 14 PostgreSQL cross-instance checks")
|
|
|
|
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)
|