#!/usr/bin/env python3 """Run the operator UI against a fixture outpost that commits a small SQL archive.""" from contextlib import ExitStack from hashlib import sha256 from pathlib import Path from subprocess import Popen from tempfile import TemporaryDirectory from uuid import uuid4 import base64 import json import sqlite3 import tarfile from fixture import BIN, command, pair, register_capture, start_hub, stop, wait_until def main(): with ExitStack() as cleanup: root = Path(cleanup.enter_context(TemporaryDirectory(prefix="tessera-browser-"))) password = "fixture-browser-password" digest = command(BIN / "tessera-hub", "--hash-operator-password", input=password + "\n", text=True, capture_output=True).stdout.strip() api, url, _, _ = start_hub(cleanup, root, { "TESSERA_OPERATOR_PASSWORD_HASH": digest, "TESSERA_OPERATOR_NAME": "fixture-browser", }) agent = pair(api, "Browser fixture outpost") app = register_capture(api, agent["outpost_id"], "Browser fixture database", "mysql_sql") capture_only_app = register_capture(api, agent["outpost_id"], "Browser capture-only", "mysql_sql") token = agent["upload_token"] server_id = str(uuid4()) target = str(uuid4()) api("restore-targets", { "id": target, "application_id": app, "outpost_id": agent["outpost_id"], "name": "Browser staging target", "engine": "mysql", "identity": {"instance": server_id, "database": "staging"}, }, expected=201) identity = base64.urlsafe_b64encode(json.dumps({"instance": server_id, "database": "source"}).encode()).decode().rstrip("=") payload = b"CREATE TABLE browser_fixture(value integer);\nINSERT INTO browser_fixture VALUES (42);\n" def commit_capture(lease): job = lease["job_id"] for phase in ("dumping", "uploading"): api(f"wormhole/capture/{job}/report", {"lease_id": lease["lease_id"], "progress": phase}, token, expected=204) headers = {"X-Tessera-Lease-Id": lease["lease_id"], "X-Tessera-Sha256": sha256(payload).hexdigest(), "X-Tessera-Source-Identity": identity} api(f"wormhole/capture/{job}/payload", payload, token, extra=headers) capture_only = api(f"capture-profiles/{capture_only_app}/jobs", {}, expected=202)["id"] commit_capture(api(f"wormhole/capture/{capture_only_app}/claim", {}, token)) document = root / "filesystem.txt" document.write_text("legacy filesystem fixture") filesystem = api("orbits", {"name": "Browser filesystem", "provider": "filesystem", "provider_config": {"paths": [str(document)]}}) api(f"orbits/{filesystem['id']}/run", {}, expected=204) filesystem_snapshot = next(snap["id"] for snap in api("snapshots") if snap["orbit_id"] == filesystem["id"]) failed = api(f"capture-profiles/{app}/jobs", {}, expected=202)["id"] failed_lease = api(f"wormhole/capture/{app}/claim", {}, token) assert failed_lease["job_id"] == failed for phase in ("dumping", "dump_failed"): api(f"wormhole/capture/{failed}/report", {"lease_id": failed_lease["lease_id"], "progress": phase}, token, expected=204) browser = Popen(["node", Path(__file__).with_name("browser.mjs"), url, password, capture_only, filesystem_snapshot]) cleanup.callback(stop, browser) def claim(): assert browser.poll() is None, "browser failed before queueing capture" return api(f"wormhole/capture/{app}/claim", {}, token) lease = wait_until(claim) job = lease["job_id"] assert api(f"capture-jobs/{job}")["actor"] == "fixture-browser" commit_capture(lease) def claim_restore(): assert browser.poll() is None, "browser failed before queueing restore" return api(f"wormhole/restore-targets/{target}/claim", {}, token) restore = wait_until(claim_restore) restore_id = restore["job"]["id"] assert restore["job"]["actor"] == "fixture-browser" scoped = {"X-Tessera-Restore-Token": restore["token"]} restore_path = f"wormhole/restore/{restore_id}" api(f"{restore_path}/report", "checking", token, expected=204, extra=scoped) assert api(f"{restore_path}/payload", token=token, extra=scoped, raw=True) == payload api(f"{restore_path}/report", "safety", token, expected=204, extra=scoped) safety = b"CREATE TABLE browser_before_restore(value integer);\n" safety_id = api(f"{restore_path}/safety", safety, token, extra={**scoped, "X-Tessera-Sha256": sha256(safety).hexdigest()})["snapshot_id"] api(f"{restore_path}/apply", {}, token, expected=204, extra=scoped) api(f"{restore_path}/report", "apply_failed", token, expected=204, extra=scoped) assert browser.wait(timeout=90) == 0 assert api(f"restore-jobs/{restore_id}")["status"] == "reconciled" assert api(f"snapshots/{safety_id}/download", raw=True) == safety with tarfile.open(root / "hub" / "exports" / "filesystem.tar") as archive: entry = next(member for member in archive.getmembers() if member.name.endswith("filesystem.txt")) assert archive.extractfile(entry).read() == b"legacy filesystem fixture" with sqlite3.connect(root / "hub" / "tessera.db") as db: count = db.execute("SELECT count(*) FROM audit_log WHERE event='snapshot.deleted' AND detail=?", (f"actor=fixture-browser snapshot={job}",)).fetchone()[0] assert count == 1 assert {snapshot["id"] for snapshot in api("snapshots")} == {capture_only, filesystem_snapshot, safety_id} if __name__ == "__main__": main()