from contextlib import ExitStack from pathlib import Path from subprocess import DEVNULL, Popen, run from urllib.error import HTTPError from urllib.request import Request, urlopen import getpass import json import os import shutil import socket import time ROOT = Path(__file__).resolve().parents[2] BIN = ROOT / "target/debug" PASSWORD = "fixture-database-password" def command(*args, **kwargs): return run(args, check=True, **kwargs) def port(): with socket.socket() as sock: sock.bind(("127.0.0.1", 0)) return sock.getsockname()[1] def wait_until(probe, seconds=45): deadline = time.monotonic() + seconds while time.monotonic() < deadline: value = probe() if value: return value time.sleep(0.2) raise AssertionError("fixture timed out") def stop(process): if process.poll() is None: process.terminate() process.wait(timeout=15) def fixture_env(): return {name: value for name, value in os.environ.items() if not name.startswith("TESSERA_")} def start_hub(cleanup: ExitStack, root: Path, settings=None, return_handle=False): hub_port = port() env = {**fixture_env(), "TESSERA_VAULT_PASSPHRASE": "fixture-private-vault-key", "TESSERA_LISTEN": f"127.0.0.1:{hub_port}", "TESSERA_DATA_DIR": str(root / "hub"), "TESSERA_ADMIN_TOKEN": "fixture-admin", **(settings or {})} hub_url = f"http://127.0.0.1:{hub_port}" log = cleanup.enter_context((root / "hub.log").open("w+")) hub = Popen([BIN / "tessera-hub"], env=env, stdout=log, stderr=log) cleanup.callback(stop, hub) def api(path, body=None, token=None, expected=200, extra=None, raw=False, method=None): payload = body if isinstance(body, bytes) else json.dumps(body).encode() if body is not None else None headers = {"Authorization": "Bearer fixture-admin", "Content-Type": "application/json"} if token: headers["X-Tessera-Upload-Token"] = token headers.update(extra or {}) request = Request(hub_url + "/api/v1/" + path, payload, headers, method=method) try: with urlopen(request, timeout=30) as response: assert response.status == expected, (path, response.status) data = response.read() return data if raw else (json.loads(data) if data else None) except HTTPError as error: assert error.code == expected, (path, error.code, error.read()) def healthy(): try: with urlopen(hub_url + "/health", timeout=1) as response: return response.status == 200 except OSError: return False wait_until(healthy) result = (api, hub_url, hub_port, log) return (*result, hub) if return_handle else result def pair(api, name): pairing = api("wormhole/pairing", {}) return api("wormhole/claim", {"code": pairing["code"], "outpost_name": name}) def start_agent(cleanup, root, hub_url, token, profiles, credentials=None, settings=None): config = root / "capture.json" config.write_text(json.dumps(profiles)) config.chmod(0o600) log = cleanup.enter_context((root / "agent.log").open("w+")) env = {**fixture_env(), **(settings or {})} args = [BIN / "tessera-agent", "--capture-profiles", config] if credentials: args.extend(["--credentials", credentials]) else: args.extend(["--hub-url", hub_url]) env["TESSERA_UPLOAD_TOKEN"] = token agent = Popen([*args, "run"], env=env, stdout=log, stderr=log) cleanup.callback(stop, agent) return agent, log def terminal(api, job_id): result = api(f"capture-jobs/{job_id}") return result if result["status"] in ("completed", "failed") else None def bastion(cleanup, root): bastion_port = port() for name in ("host", "client", "wrong_host"): command("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", root / name) config = root / "sshd_config" config.write_text( f"ListenAddress 127.0.0.1\nPort {bastion_port}\nHostKey {root / 'host'}\n" f"AuthorizedKeysFile {root / 'client.pub'}\nPidFile {root / 'ssh.pid'}\n" "UsePAM no\nPasswordAuthentication no\nKbdInteractiveAuthentication no\nStrictModes no\n" f"SetEnv PATH={os.environ['PATH']}\n" ) log = cleanup.enter_context((root / "sshd.log").open("w+")) ssh = Popen([shutil.which("sshd") or "/usr/sbin/sshd", "-D", "-e", "-f", config], stdout=log, stderr=log) cleanup.callback(stop, ssh) def listening(): try: with socket.create_connection(("127.0.0.1", bastion_port), timeout=0.25): return True except OSError: return False wait_until(listening) endpoint = {"host": "127.0.0.1", "port": bastion_port, "user": getpass.getuser(), "identity_file": str(root / "client")} results = [] for key in ("host", "wrong_host"): known_hosts = root / (key + ".known_hosts") known_hosts.write_text(f"[127.0.0.1]:{bastion_port} " + (root / (key + ".pub")).read_text()) results.append({**endpoint, "known_hosts_file": str(known_hosts)}) return results def postgres(cleanup, root, databases): data = root / "db" pg_port = port() password = root / "password" password.write_text(PASSWORD + "\n") password.chmod(0o600) command("initdb", "-D", data, "-U", "fixture", "--auth-local=trust", "--auth-host=scram-sha-256", "--pwfile", password, stdout=DEVNULL) ca, key = data / "server.crt", data / "server.key" command("openssl", "req", "-x509", "-newkey", "rsa:2048", "-noenc", "-days", "1", "-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost", "-out", ca, "-keyout", key, stdout=DEVNULL, stderr=DEVNULL) key.chmod(0o600) command("pg_ctl", "-D", data, "-l", root / "postgres.log", "-w", "start", "-o", f"-h 127.0.0.1 -p {pg_port} -k {root} -c ssl=on", stdout=DEVNULL) cleanup.callback(command, "pg_ctl", "-D", data, "-m", "immediate", "-w", "stop", stdout=DEVNULL) pg = ("-h", str(root), "-p", str(pg_port), "-U", "fixture") for database in databases: command("createdb", *pg, database) def connection(database): return {"host": "localhost", "port": pg_port, "database": database, "user": "fixture", "password_file": str(password), "tls": {"mode": "verify_full_with_ca", "ca_file": str(ca)}} return pg, connection def register_capture(api, outpost, name, format): orbit = api("orbits", {"name": name, "provider": "wormhole", "provider_config": {}}) from uuid import uuid4 app = str(uuid4()) api("capture-profiles", {"application_id": app, "orbit_id": orbit["id"], "outpost_id": outpost, "format": format}, expected=201) return app def mysql_container(cleanup, root): from uuid import uuid4 mysql_port = port() container = "tessera-mysql-" + uuid4().hex command("docker", "run", "--rm", "-d", "--name", container, "-p", f"127.0.0.1:{mysql_port}:3306", "-e", "MYSQL_ROOT_PASSWORD=" + PASSWORD, "-e", "MYSQL_DATABASE=fixture", os.environ.get("TESSERA_FIXTURE_MYSQL_IMAGE", "mysql:9.2"), stdout=DEVNULL) cleanup.callback(command, "docker", "stop", "-t", "3", container, stdout=DEVNULL) defaults = root / "mysql.cnf" defaults.write_text(f"[client]\nuser=root\npassword={PASSWORD}\n" f"host=127.0.0.1\nport={mysql_port}\nprotocol=TCP\nssl-mode=REQUIRED\n") defaults.chmod(0o600) mysql = ("mysql", f"--defaults-file={defaults}", "--default-character-set=utf8mb4") def ready(): return run([*mysql, "-e", "SELECT 1"], stdout=DEVNULL, stderr=DEVNULL).returncode == 0 wait_until(ready, seconds=90) return mysql, defaults, mysql_port def s3_container(cleanup, bucket): from uuid import uuid4 endpoint = f"http://127.0.0.1:{port()}" container = "tessera-s3-" + uuid4().hex command("docker", "run", "--rm", "-d", "--name", container, "-p", f"{endpoint.removeprefix('http://')}:5000", "motoserver/moto:5.1.12", stdout=DEVNULL) cleanup.callback(command, "docker", "stop", "-t", "3", container, stdout=DEVNULL) def ready(): try: with urlopen(endpoint, timeout=1) as response: return response.status == 200 except OSError: return False wait_until(ready) settings = {"AWS_ACCESS_KEY_ID": "fixture-s3-key", "AWS_SECRET_ACCESS_KEY": "fixture-s3-secret", "AWS_DEFAULT_REGION": "us-east-1", "AWS_EC2_METADATA_DISABLED": "true"} command("aws", "--endpoint-url", endpoint, "s3api", "create-bucket", "--bucket", bucket, env={**fixture_env(), **settings}, stdout=DEVNULL) return endpoint, settings