feat: add managed database capture and operator restore

PostgreSQL and MySQL backups run through paired outposts, with operator sign-in, off-site copies, and legacy import. Retention stays on each orbit, so the unused retention console is removed.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-10 23:26:49 +07:00
parent 30a1a9b8f0
commit 6320b6f244
96 changed files with 11061 additions and 725 deletions

View File

@@ -0,0 +1,186 @@
#!/usr/bin/env python3
"""Isolated PostgreSQL TLS → Wormhole → Restic → export → PostgreSQL fixture."""
from contextlib import ExitStack
from hashlib import sha256
from pathlib import Path
from subprocess import DEVNULL
from tempfile import TemporaryDirectory
from uuid import uuid4
import json
import os
import socket
import stat
from fixture import BIN, PASSWORD, bastion, command, fixture_env, pair, port, start_agent, start_hub, stop, terminal, wait_until
def main():
with ExitStack() as cleanup:
root = Path(cleanup.enter_context(TemporaryDirectory(prefix="tessera-pg-")))
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 ("source_db", "target_db"):
command("createdb", *pg, database)
command("psql", *pg, "-d", "source_db", "-v", "ON_ERROR_STOP=1", "-c",
"CREATE SCHEMA fixture; CREATE TABLE fixture.rows (id integer PRIMARY KEY, value text);"
"INSERT INTO fixture.rows VALUES (1, 'Wormhole ✓');", stdout=DEVNULL)
api, hub_url, hub_port, hub_log = start_hub(cleanup, root)
credentials = root / "wormhole.json"
code = api("wormhole/pairing", {})["code"]
paired = command(BIN / "tessera-agent", "--hub-url", hub_url, "--credentials", credentials,
"pair", code, "--name", "Postgres fixture", env=fixture_env(),
text=True, capture_output=True)
assert stat.S_IMODE(credentials.stat().st_mode) == 0o600
agent = json.loads(credentials.read_text())
token = agent["upload_token"]
assert token not in paired.stdout and token not in paired.stderr
api("wormhole/claim", {"code": code, "outpost_name": "replay"}, expected=410)
wrong_agent = pair(api, "different fixture")
assert {outpost["id"] for outpost in api("wormhole/outposts")} == {
agent["outpost_id"], wrong_agent["outpost_id"],
}
def profile(host, via=None):
orbit = api("orbits", {"name": "fixture", "provider": "wormhole", "provider_config": {}})
app = str(uuid4())
api("capture-profiles", {"application_id": app, "orbit_id": orbit["id"],
"outpost_id": agent["outpost_id"], "format": "postgres_custom"}, expected=201)
source = {"engine": "postgres", "host": host, "port": pg_port, "database": "source_db",
"user": "fixture", "password_file": str(password),
"tls": {"mode": "verify_full_with_ca", "ca_file": str(ca)}}
if via:
source["bastion"] = via
return app, {"source": source, "timeout_seconds": 15}
app, good = profile("localhost")
bad_app, bad = profile("127.0.0.1")
job = api(f"capture-profiles/{app}/jobs", {}, expected=202)["id"]
bad_job = api(f"capture-profiles/{bad_app}/jobs", {}, expected=202)["id"]
assert api(f"wormhole/capture/{app}/claim", {}, wrong_agent["upload_token"]) is None
pinned, wrong_key = bastion(cleanup, root)
tunnel_app, tunnel = profile("localhost", pinned)
wrong_key_app, bad_tunnel = profile("localhost", wrong_key)
tunnel_job = api(f"capture-profiles/{tunnel_app}/jobs", {}, expected=202)["id"]
wrong_key_job = api(f"capture-profiles/{wrong_key_app}/jobs", {}, expected=202)["id"]
stalled = cleanup.enter_context(socket.socket())
stalled.bind(("127.0.0.1", 0))
stalled.listen(1)
stalled.settimeout(5)
timeout_app, stalled_profile = profile("localhost", pinned)
stalled_profile["source"]["port"] = stalled.getsockname()[1]
stalled_profile["timeout_seconds"] = 2
timeout_job = api(f"capture-profiles/{timeout_app}/jobs", {}, expected=202)["id"]
agent_process, agent_log = start_agent(cleanup, root, hub_url, token, {
app: good, bad_app: bad, tunnel_app: tunnel, wrong_key_app: bad_tunnel,
timeout_app: stalled_profile,
}, credentials=credentials)
replica = root / "second-agent"
replica.mkdir()
second, _ = start_agent(cleanup, replica, hub_url, token, {app: good}, credentials=credentials)
partial_dir = root / "partial-client"
partial_dir.mkdir()
partial_client = partial_dir / "pg_dump"
partial_client.write_text("#!/bin/sh\nprintf PGDMPpartial\nexit 1\n")
partial_client.chmod(0o700)
partial_worker = root / "partial-agent"
partial_worker.mkdir()
partial_app, partial_profile = profile("localhost")
partial_job = api(f"capture-profiles/{partial_app}/jobs", {}, expected=202)["id"]
start_agent(cleanup, partial_worker, hub_url, token, {partial_app: partial_profile},
credentials=credentials, settings={"PATH": f"{partial_dir}:{os.environ['PATH']}"})
partial = wait_until(lambda: terminal(api, partial_job))
assert partial["phase"] == "dump_failed" and partial["snapshot_id"] is None
successful = wait_until(lambda: terminal(api, job))
assert sum(event["phase"] == "claimed" for event in api(f"capture-jobs/{job}/events")) == 1
failed = wait_until(lambda: terminal(api, bad_job))
through_bastion = wait_until(lambda: terminal(api, tunnel_job))
assert through_bastion["status"] == "completed", through_bastion
rejected = wait_until(lambda: terminal(api, wrong_key_job))
assert rejected["phase"] == "dump_failed" and rejected["snapshot_id"] is None, rejected
timed_out = wait_until(lambda: terminal(api, timeout_job))
assert timed_out["phase"] == "dump_failed" and timed_out["snapshot_id"] is None
with stalled.accept()[0] as connection:
connection.settimeout(5)
while connection.recv(1024):
pass
assert successful["status"] == "completed", successful
assert failed["status"] == "failed" and failed["phase"] == "dump_failed", failed
assert failed["snapshot_id"] is None
snapshots = api("snapshots")
assert {snap["id"] for snap in snapshots} == {successful["snapshot_id"], through_bastion["snapshot_id"]}
dump = root / "backup.dump"
session = api("reconstitute", {"snapshot_id": successful["snapshot_id"], "target_path": str(dump)})
wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed")
command("pg_restore", *pg, "-d", "target_db", "--exit-on-error", dump)
restored = command("psql", *pg, "-d", "target_db", "-Atc",
"SELECT id, value FROM fixture.rows;", capture_output=True, text=True)
assert restored.stdout.strip() == "1|Wormhole ✓", restored.stdout
# Stage a second capture manually to exercise the commit protocol with a lost reply.
stop(agent_process)
stop(second)
replay = api(f"capture-profiles/{app}/jobs", {}, expected=202)["id"]
lease = api(f"wormhole/capture/{app}/claim", {}, token)
assert lease["job_id"] == replay
api(f"wormhole/capture/{replay}/report",
{"lease_id": lease["lease_id"], "progress": "synthetic-report-secret\x1b"},
token, expected=422)
assert all("synthetic-report-secret" not in json.dumps(value) for value in (
api(f"capture-jobs/{replay}"), api(f"capture-jobs/{replay}/events"), api("capture-jobs"),
))
for phase in ("dumping", "uploading"):
api(f"wormhole/capture/{replay}/report", {"lease_id": lease["lease_id"], "progress": phase},
token, expected=204)
payload = dump.read_bytes()
headers = {"X-Tessera-Lease-Id": lease["lease_id"], "X-Tessera-Sha256": sha256(payload).hexdigest()}
path = f"wormhole/capture/{replay}/payload"
api(path, payload, wrong_agent["upload_token"], expected=409, extra=headers)
api(path, payload[:-1], token, expected=422, extra=headers)
assert len(api("snapshots")) == 2
with socket.create_connection(("127.0.0.1", hub_port)) as conn:
request = (f"POST /api/v1/{path} HTTP/1.1\r\nHost: localhost\r\n"
f"X-Tessera-Upload-Token: {token}\r\nX-Tessera-Lease-Id: {lease['lease_id']}\r\n"
f"X-Tessera-Sha256: {headers['X-Tessera-Sha256']}\r\nContent-Length: {len(payload)}\r\n"
"Connection: close\r\n\r\n").encode()
conn.sendall(request + payload[:-1])
assert api(f"capture-jobs/{replay}")["snapshot_id"] is None
with socket.create_connection(("127.0.0.1", hub_port)) as conn:
conn.sendall(request + payload)
committed = wait_until(lambda: terminal(api, replay), seconds=10)
# Drop the connection without reading the acknowledgement.
assert committed["snapshot_id"] == replay
assert api(path, payload, token, extra=headers)["snapshot_id"] == replay
assert len(api("snapshots")) == 3
legacy = api("orbits", {
"name": "legacy-fixture", "provider": "postgres",
"provider_config": {"connection_url": f"postgres://fixture:{PASSWORD}@localhost:{pg_port}/source_db"},
})
assert "provider_config" not in legacy
command(BIN / "tessera", "--hub-url", hub_url, "snap", "--orbit", "legacy-fixture",
env={**fixture_env(), "TESSERA_ADMIN_TOKEN": "fixture-admin"}, stdout=DEVNULL)
assert any(snap["orbit_id"] == legacy["id"] for snap in api("snapshots"))
for log in (hub_log, agent_log):
log.seek(0)
assert PASSWORD not in log.read()
print("PostgreSQL direct and pinned SSH capture, TLS and SSH rejection, Restic restore, and replay verified")
if __name__ == "__main__":
main()