import io import json import os import secrets import subprocess import sys import time from pathlib import Path from core.database import get_adapter from core.execution import CommandRunner, ExecutionError IMAGES = { "mysql": "sha256:8c233bad33d520a7aae1c1e619c3a9775f4a1ba2d463d692fada04ec7f40be00", "pgsql": "sha256:e742a2668255221388004f3a42b6150a2103f5054ab3a4a93ae9e4f01e551c35", } KEY_PATHS = {"mysql": "/run/secrets/absdev-client.cnf", "pgsql": "/run/secrets/absdev-pgpass"} containers = [] event_count = 0 def docker(*args, input_data=None): return subprocess.run(("docker", *args), input=input_data, capture_output=True, text=True, timeout=120) def good(*args, input_data=None): result = docker(*args, input_data=input_data) if result.returncode: raise RuntimeError(f"Docker {args[0]} failed with status {result.returncode}") return result.stdout.strip() def record(engine, check): global event_count event_count += 1 print(json.dumps(dict(engine=engine, result="PASS", check=check)), flush=True) def start(engine): name = "absdev-secret-" + engine + "-" + secrets.token_hex(5) variable = "MYSQL_ROOT_PASSWORD" if engine == "mysql" else "POSTGRES_PASSWORD" environment = Path.cwd().parent / (name + ".env") environment.write_text(variable + "=" + secrets.token_hex(24) + "\n") environment.chmod(0o600) with environment.open("a") as handle: if engine == "pgsql": handle.write("POSTGRES_INITDB_ARGS=--auth-host=scram-sha-256\n") try: cid = good("create", "--pull", "never", "--name", name, "--network", "none", "--security-opt", "no-new-privileges", "--cap-drop", "NET_RAW", "--memory", "1g", "--pids-limit", "256", "--env-file", str(environment), IMAGES[engine]) finally: environment.unlink() containers.append(cid) good("start", cid) details = json.loads(good("inspect", "--format", "{{json .HostConfig}}", cid)) assert details["NetworkMode"] == "none" and not details["Privileged"] assert not details["PortBindings"] and not details["Binds"] record(engine, "disposable container has no external network, host mounts or published ports") return name, cid def admin(engine, cid, sql): if engine == "mysql": return docker("exec", "-i", cid, "sh", "-c", 'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" exec mysql --no-defaults -uroot --batch', input_data=sql) return docker("exec", "-i", "--user", "postgres", cid, "psql", "-X", "-U", "postgres", "-d", "postgres", "-v", "ON_ERROR_STOP=1", input_data=sql) def ready(engine, cid): for _ in range(90): if engine == "pgsql": status = docker("exec", cid, "pg_isready", "-h", "127.0.0.1", "-U", "postgres") if status.returncode: time.sleep(1) continue else: status = docker("exec", cid, "sh", "-c", 'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" mysql --no-defaults --protocol=TCP -h127.0.0.1 -uroot -e "SELECT 1"') if status.returncode: time.sleep(1) continue if admin(engine, cid, "SELECT 1;").returncode == 0: return time.sleep(1) raise RuntimeError(f"{engine} did not become ready") def write_key(engine, cid, password): path = KEY_PATHS[engine] data = ("[client]\npassword=" + password + "\n" if engine == "mysql" else "127.0.0.1:5432:fixture:fixture:" + password + "\n") good("exec", "-i", cid, "sh", "-ceu", 'mkdir -p /run/secrets; umask 077; tmp=$(mktemp "$1.XXXXXX"); cat > "$tmp"; mv -f "$tmp" "$1"', "sh", path, input_data=data) assert good("exec", cid, "stat", "-c", "%a:%u", path) == "600:0" def check_command(runner, command, success): output = io.BytesIO() try: runner(command, output) except ExecutionError: assert not success and not output.getvalue() else: assert success and output.getvalue().strip() == b"1" def qualify(engine): name, cid = start(engine) ready(engine, cid) original, rotated = secrets.token_hex(24), secrets.token_hex(24) if engine == "mysql": setup = ("CREATE DATABASE fixture; " f"CREATE USER 'fixture'@'127.0.0.1' IDENTIFIED BY '{original}'; " "GRANT SELECT ON fixture.* TO 'fixture'@'127.0.0.1';") change = f"ALTER USER 'fixture'@'127.0.0.1' IDENTIFIED BY '{rotated}';" else: setup = f"CREATE ROLE fixture LOGIN PASSWORD '{original}';\nCREATE DATABASE fixture OWNER fixture;" change = f"ALTER ROLE fixture PASSWORD '{rotated}';" assert admin(engine, cid, setup).returncode == 0, f"{engine} fixture setup failed" config = json.loads(Path("config/site.example.json").read_text()) config["database"].update(driver=engine, container=name, host="127.0.0.1", port=3306 if engine == "mysql" else 5432, name="fixture", username="fixture") command = get_adapter(config).ping_command() assert not any(value in arg for arg in command for value in (original, rotated)) runner = CommandRunner([command], timeout=15) check_command(runner, command, False) record(engine, "missing credential file rejects authentication without publishing output") write_key(engine, cid, original) path = KEY_PATHS[engine] assert docker("exec", "--user", "65534:65534", cid, "cat", path).returncode != 0 check_command(runner, command, True) record(engine, "adapter authenticates with mode 0600 credential file and unrelated UID cannot read it") good("exec", cid, "chmod", "0666", path) check_command(runner, command, False) record(engine, "database client rejects world-writable credential file") good("exec", cid, "chmod", "0600", path) assert admin(engine, cid, change).returncode == 0, f"{engine} password rotation failed" check_command(runner, command, False) record(engine, "old credential file is rejected after server-side rotation") write_key(engine, cid, rotated) check_command(runner, command, True) record(engine, "atomic credential replacement restores authentication") write_key(engine, cid, original) check_command(runner, command, False) record(engine, "rolling file back to retired credential does not restore access") try: os.environ.update(PATH="/untrusted", ABSDEV_TEST_SECRET="synthetic", DOCKER_HOST="synthetic", PGPASSWORD="synthetic", MYSQL_PWD="synthetic") argv = [sys.executable, "-I", "-c", "import json, os; print(json.dumps(dict(os.environ)))"] output = io.BytesIO() CommandRunner([argv])(argv, output) assert json.loads(output.getvalue()) == {"PATH": os.defpath, "LC_ALL": "C"} record("framework", "approved child receives fixed PATH and locale only") # The qualification controller needs its own trusted Docker environment. for name in ("ABSDEV_TEST_SECRET", "DOCKER_HOST", "PGPASSWORD", "MYSQL_PWD"): os.environ.pop(name) os.environ["PATH"] = os.defpath for engine in IMAGES: qualify(engine) finally: cleanup_failed = False for cid in reversed(containers): command = docker("rm", "-fv", cid) if command.returncode: cleanup_failed = True if cleanup_failed: raise RuntimeError("Disposable container cleanup failed") record("framework", "all disposable containers and their anonymous volumes removed")