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

37
tests/mbu/README.md Normal file
View File

@@ -0,0 +1,37 @@
# MBU backup fixtures
Use a clean development host with Restic, PostgreSQL client/server tools, MySQL client tools, OpenSSL, OpenSSH, Docker, AWS CLI, Node.js and Python 3.9+. The SSH fixture uses a temporary loopback `sshd` and generated keys. Some Linux hosts require the distro's SSH privilege separation directory to exist before a non-root fixture can start.
```sh
rtk proxy npm --prefix web run build
rtk cargo build --workspace
rtk cargo test --workspace
rtk cargo test -p tessera-store -- --ignored
rtk proxy python3 tests/mbu/restic-orbits.py
rtk proxy python3 tests/mbu/capture-postgres.py
rtk proxy python3 tests/mbu/capture-mysql.py
rtk proxy python3 tests/mbu/restore-postgres.py
rtk proxy python3 tests/mbu/offsite.py
rtk proxy python3 tests/mbu/browser.py
rtk proxy python3 tests/mbu/legacy-import.py
rtk proxy python3 tests/mbu/matrix.py
```
- Restic orbits requires `rest-server` and `htpasswd` on PATH. It checks the four source/access combinations with a TLS Rest Server, re-runs after small changes, and verifies filesystem and PostgreSQL restores. Add `--mysql` to include MySQL capture and restore through both access modes.
- PostgreSQL covers direct TLS, verified PostgreSQL TLS through a pinned bastion, a mismatched hostname, a wrong host key, partial upload, a competing outpost, retry after a dropped reply, and a real restore to a second database.
- MySQL starts `mysql:9.2` by default. Use the matching `mysqldump` on PATH. Set `TESSERA_FIXTURE_MYSQL_IMAGE` to test a different server with a compatible client. The fixture covers direct and SSH capture, host-key failure, an engine error, and restore of data with a view, routine, and event.
- S3 starts `motoserver/moto:5.1.12` on loopback. It checks failed copy, retry, and export with the primary Restic repository offline.
- The browser test uses Playwright from Node's resolution path or `TESSERA_PLAYWRIGHT_MODULE` and its bundled Chromium or `TESSERA_FIXTURE_CHROME`. The fixture submits backup and restore jobs as an operator, exercises a capture-only profile, and verifies recovery status, the safety ID, and filesystem export. A fixture outpost handles the scoped job protocol.
- PostgreSQL restore verifies target identity, scoped payload access, checksum rejection, safety pinning, schema and recreate modes, a PostgreSQL 17 dump restored to PostgreSQL 14, restricted psql commands, and restart after reset. The fixture uses the PostgreSQL 14 host tools and the postgres:17 container for the newer source.
- The legacy import fixture reads compressed SQL archives from S3, restores synthetic samples, and verifies history access and idempotency after local GC.
- The matrix pairs three outposts, runs ten application profiles against isolated databases, exercises a scheduler tick for 02.00 WIB, and checks manual capture, scheduled capture, registered restore targets, and S3 copies. Its JSON output records durations, freshness, size and restore results.
## Placement inventory and fixture mapping
Read-only Teleport inventory on 10 November 2026 showed `odoo-clone`, `production-FTA`, `fta-prod`, `broiler-production`, `broiler-staging` and `mbu-backup-jumphost`. Database inventory reported the Broiler resource `mbu-production` with the MySQL protocol. MAS and FTA had no matching database resource in the approved inventory. The returned metadata had no server-version labels. The approved Machine ID could list resources, but the attempted `devops` OS login returned `unknown user devops` on `odoo-clone`, `production-FTA`, `broiler-production`, and `mbu-backup-jumphost`. Verification of deployed client/server versions, routes and privileges requires an authorized existing OS login on the applicable nodes.
| Case | Fixture | Placement to validate |
| --- | --- | --- |
| MAS and FTA | PostgreSQL TLS behind a loopback SSH bastion, wrong host key case | Run near the database if there is direct access. Otherwise use a pinned SSH forward to the database and validate the PostgreSQL server hostname. |
| Boiler | MySQL behind a pinned SSH login, wrong host key and engine-error cases | Use the matched MySQL client on the SSH host and a private client options file. |

115
tests/mbu/browser.mjs Normal file
View File

@@ -0,0 +1,115 @@
import assert from "node:assert/strict";
import { createRequire } from "node:module";
const { chromium } = createRequire(import.meta.url)(process.env.TESSERA_PLAYWRIGHT_MODULE || "playwright");
const [baseURL, password, captureOnly, filesystemSnapshot] = process.argv.slice(2);
const browser = await chromium.launch({
executablePath: process.env.TESSERA_FIXTURE_CHROME || undefined,
});
try {
const context = await browser.newContext({ baseURL, viewport: { width: 1100, height: 820 } });
const page = await context.newPage();
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
await page.goto("/");
await page.getByRole("heading", { name: "Operator sign-in" }).waitFor();
const orbitsStatus = () => page.evaluate(async () => (await fetch("/api/v1/orbits")).status);
assert.equal(await orbitsStatus(), 401);
await page.getByLabel("Operator password").fill(password);
await page.getByRole("button", { name: "Sign in", exact: true }).click();
await page.getByRole("heading", { name: "Orbital vault" }).waitFor();
assert.equal(await orbitsStatus(), 200);
const pairingWithoutCsrf = await page.evaluate(async () =>
(await fetch("/api/v1/wormhole/pairing", { method: "POST" })).status);
assert.equal(pairingWithoutCsrf, 403);
await page.getByRole("button", { name: "Restore", exact: true }).click();
await page.getByRole("heading", { name: "Restore snapshot" }).waitFor();
await page.getByRole("combobox", { name: "Snapshot", exact: true }).selectOption(captureOnly);
await page.getByText("This application has no registered restore targets.").waitFor();
assert.equal(await page.getByRole("button", { name: "Queue database restore" }).count(), 0);
await page.getByRole("button", { name: "Close", exact: true }).click();
await page.getByRole("button", { name: "Orbits", exact: true }).click();
await page.getByRole("heading", { name: "Outpost backup jobs" }).waitFor();
await page.getByRole("button", { name: "Add an orbit" }).click();
await page.getByLabel("Backup source").selectOption("database");
await page.getByLabel("Database engine").selectOption("mysql");
assert.equal(await page.getByLabel("Database host").count(), 1);
await page.getByLabel(/^Access/).selectOption("outpost");
assert.equal(await page.getByLabel("Database host").count(), 0);
await page.getByLabel("Backup source").selectOption("filesystem");
await page.getByLabel("Name", { exact: true }).fill("Browser Outpost folder");
const savedOrbit = page.waitForResponse((response) =>
response.url().endsWith("/api/v1/orbits") && response.request().method() === "POST");
await page.getByRole("button", { name: "Save orbit" }).click();
const saved = await savedOrbit;
assert.equal(saved.ok(), true);
const orbit = await saved.json();
assert.equal(orbit.source, "filesystem");
assert.equal(orbit.access, "outpost");
const profile = page.getByRole("heading", { name: "Register Outpost backup profile" }).locator("..");
assert.equal(await profile.getByLabel("Database engine").count(), 0);
const outpost = profile.getByLabel("Assigned Outpost");
await outpost.getByRole("option", { name: /Browser fixture outpost/ }).waitFor({ state: "attached" });
await outpost.selectOption(await outpost.getByRole("option", { name: /Browser fixture outpost/ }).getAttribute("value"));
const registeredProfile = page.waitForResponse((response) =>
response.url().endsWith("/api/v1/capture-profiles") && response.request().method() === "POST");
await profile.getByRole("button", { name: "Register profile" }).click();
const registered = await registeredProfile;
assert.equal(registered.ok(), true);
assert.equal((await registered.json()).format, "filesystem");
await page.getByRole("combobox", { name: "Application", exact: true })
.selectOption({ label: "Browser fixture database" });
await page.getByRole("combobox", { name: "Job status" }).selectOption("failed");
await page.getByRole("button", { name: /Source preparation failed or timed out/ }).click();
await page.getByText("Preparing source", { exact: true }).waitFor();
await page.getByRole("combobox", { name: "Job status" }).selectOption("running");
await page.getByText("No jobs match these filters.").waitFor();
await page.getByRole("button", { name: "Back up selected application" }).click();
await page.getByText("Backup queued.").waitFor();
await page.getByRole("button", { name: "Open snapshot" }).click();
await page.getByRole("heading", { name: "Snapshot detail" }).waitFor();
const received = page.waitForEvent("download");
await page.getByRole("link", { name: "Download snapshot" }).click();
const download = await received;
const stream = await download.createReadStream();
const chunks = [];
for await (const chunk of stream) chunks.push(chunk);
assert.match(Buffer.concat(chunks).toString(), /INSERT INTO browser_fixture VALUES \(42\)/);
await page.getByRole("button", { name: "Recovery options" }).click();
const targetField = page.getByRole("combobox", { name: "Registered target" });
const targetOption = targetField.getByRole("option", { name: /^Browser staging target/ });
await targetOption.waitFor({ state: "attached" });
await targetField.selectOption(await targetOption.getAttribute("value"));
const restoreCode = await page.getByText(/^RESTORE [a-f0-9-]+ TO [a-f0-9-]+$/).textContent();
assert.equal(await page.getByRole("button", { name: "Queue database restore" }).isDisabled(), true);
await page.getByLabel("Restore confirmation").fill(restoreCode);
await page.getByRole("button", { name: "Queue database restore" }).click();
await page.getByText("Apply failed. Recovery required.", { exact: true }).waitFor();
await page.getByRole("link", { name: /^Safety backup [a-f0-9-]+$/ }).waitFor();
const recoveryCode = await page.getByText(/^RECONCILE [a-f0-9-]+$/).textContent();
await page.getByLabel("Reconciliation confirmation").fill(recoveryCode);
await page.getByRole("button", { name: "Mark target recovered" }).click();
await page.getByText("Recovery verified by operator", { exact: true }).waitFor();
await page.getByRole("combobox", { name: "Snapshot", exact: true }).selectOption(filesystemSnapshot);
await page.getByLabel("Export filename on hub").fill("filesystem.tar");
await page.getByRole("button", { name: "Begin file export" }).click();
await page.getByText("File export complete.", { exact: true }).waitFor();
await page.getByRole("button", { name: "Close", exact: true }).click();
await page.getByRole("button", { name: "Orbits", exact: true }).click();
await page.getByRole("button", { name: /Browser fixture database Backup completed/ }).click();
await page.getByRole("button", { name: "Open snapshot" }).click();
await page.getByRole("button", { name: "Delete snapshot" }).click();
await page.getByRole("button", { name: "Confirm deletion" }).click();
await page.getByRole("heading", { name: "Snapshot detail" }).waitFor({ state: "hidden" });
await page.setViewportSize({ width: 390, height: 844 });
await page.getByRole("button", { name: "Sign out" }).click();
await page.getByRole("heading", { name: "Operator sign-in" }).waitFor();
assert.equal(await orbitsStatus(), 401);
assert.deepEqual(errors, []);
console.log("Browser sign-in, backup, download, database restore/reconciliation, filesystem export, and deletion verified");
} finally {
await browser.close();
}

108
tests/mbu/browser.py Normal file
View File

@@ -0,0 +1,108 @@
#!/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()

135
tests/mbu/capture-mysql.py Normal file
View File

@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""MySQL direct and pinned SSH capture with view/routine/event fixtures."""
from contextlib import ExitStack
from pathlib import Path
from subprocess import DEVNULL
from tempfile import TemporaryDirectory
from uuid import uuid4
from fixture import PASSWORD, bastion, command, mysql_container, pair, start_agent, start_hub, terminal, wait_until
def main():
with ExitStack() as cleanup:
root = Path(cleanup.enter_context(TemporaryDirectory(prefix="tessera-mysql-")))
mysql, defaults, mysql_port = mysql_container(cleanup, root)
password = root / "mysql-password"
password.write_text(PASSWORD + "\n")
password.chmod(0o600)
command(*mysql, "-D", "fixture", "-e",
"CREATE TABLE sample(id INT PRIMARY KEY, label VARCHAR(40)) CHARSET utf8mb4;"
"INSERT INTO sample VALUES(1, 'backup 🛰');"
"CREATE VIEW sample_view AS SELECT label FROM sample;"
"CREATE PROCEDURE sample_routine() SELECT id FROM sample;"
"CREATE EVENT sample_event ON SCHEDULE EVERY 1 DAY DISABLE DO SELECT 1;")
command(*mysql, "-e", """
CREATE DATABASE restored;
CREATE DATABASE managed_target;
CREATE TABLE managed_target.previous(id INT);
INSERT INTO managed_target.previous VALUES (84);
CREATE DATABASE limited_target;
CREATE TABLE limited_target.previous(id INT);
INSERT INTO limited_target.previous VALUES (91);
CREATE USER 'restore_limited'@'%' IDENTIFIED BY 'fixture-limited-password';
GRANT SELECT, SHOW VIEW, EVENT ON limited_target.* TO 'restore_limited'@'%';
GRANT SHOW_ROUTINE ON *.* TO 'restore_limited'@'%';
""")
instance = command(*mysql, "-NB", "-e", "SELECT LOWER(@@server_uuid)",
capture_output=True, text=True).stdout.strip()
limited_password = root / "limited-password"
limited_password.write_text("fixture-limited-password\n")
limited_password.chmod(0o600)
api, hub_url, _, hub_log = start_hub(cleanup, root)
agent = pair(api, "MySQL fixture")
token = agent["upload_token"]
pinned, wrong_key = bastion(cleanup, root)
direct = {"engine": "mysql", "transport": "direct", "host": "127.0.0.1",
"port": mysql_port, "user": "root", "password_file": str(password),
"database": "fixture", "tls": {"mode": "required"}}
remote = {"engine": "mysql", "transport": "ssh", "bastion": pinned,
"defaults_file": str(defaults), "database": "fixture"}
profiles, jobs, targets = {}, {}, {}
for name, source in [
("direct", direct), ("remote", remote),
("engine-error", {**direct, "database": "does_not_exist"}),
("wrong-key", {**remote, "bastion": wrong_key}),
]:
orbit = api("orbits", {"name": name, "provider": "wormhole", "provider_config": {}})
app = str(uuid4())
api("capture-profiles", {"application_id": app, "orbit_id": orbit["id"],
"outpost_id": agent["outpost_id"], "format": "mysql_sql"}, expected=201)
jobs[name] = api(f"capture-profiles/{app}/jobs", {}, expected=202)["id"]
profiles[app] = {"source": source, "timeout_seconds": 45}
if name in ("direct", "remote"):
database = "managed_target" if name == "remote" else "limited_target"
target = str(uuid4())
api("restore-targets", {"id": target, "application_id": app, "outpost_id": agent["outpost_id"],
"name": database, "engine": "mysql", "identity": {"instance": instance, "database": database}},
expected=201)
targets[name] = target
target_connection = {key: value for key, value in source.items() if key != "engine"}
target_connection["database"] = database
if name == "direct":
target_connection.update(user="restore_limited", password_file=str(limited_password))
profiles[app]["targets"] = {target: {
"engine": "mysql", "connection": target_connection,
"recreate_database": True, "use_target_definer": True,
}}
_, agent_log = start_agent(cleanup, root, hub_url, token, profiles)
for name, job in jobs.items():
try:
result = wait_until(lambda: terminal(api, job))
except AssertionError as error:
for log in (hub_log, agent_log):
log.seek(0)
print(log.read().replace(PASSWORD, "<redacted>"))
raise AssertionError((name, api(f"capture-jobs/{job}"))) from error
if name in ("engine-error", "wrong-key"):
assert result["phase"] == "dump_failed" and result["snapshot_id"] is None, result
continue
assert result["status"] == "completed", (name, result)
target = root / f"{name}.sql"
session = api("reconstitute", {"snapshot_id": result["snapshot_id"], "target_path": str(target)})
wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed")
sql = target.read_text()
assert all(marker in sql for marker in ("sample_view", "sample_routine", "sample_event", "backup 🛰"))
if name == "remote":
with target.open("rb") as dump:
command(*mysql, "-D", "restored", stdin=dump)
output = command(*mysql, "-NB", "-D", "restored", "-e", "SELECT label FROM sample_view",
capture_output=True, text=True)
assert output.stdout.strip() == "backup 🛰", output.stdout
assert len(api("snapshots")) == 2
for name, target in targets.items():
snap = jobs[name]
job = api("restore-jobs", {"snapshot_id": snap, "target_id": target,
"confirmation": f"RESTORE {snap} TO {target}"}, expected=202)["id"]
def restored_job():
result = api(f"restore-jobs/{job}")
return result if result["status"] in ("completed", "failed", "recovery_required") else None
result = wait_until(restored_job, seconds=65)
if name == "direct":
assert result["status"] == "recovery_required" and result["safety_snapshot_id"], result
output = command(*mysql, "-NB", "-e", "SELECT id FROM limited_target.previous",
capture_output=True, text=True)
assert output.stdout.strip() == "91"
assert b"previous" in api(f"snapshots/{result['safety_snapshot_id']}/download", raw=True)
else:
assert result["status"] == "completed" and result["safety_snapshot_id"], result
output = command(*mysql, "-NB", "-D", "managed_target", "-e",
"SELECT label FROM sample_view; CALL sample_routine();"
"SELECT EVENT_NAME FROM information_schema.EVENTS WHERE EVENT_SCHEMA='managed_target';",
capture_output=True, text=True)
assert output.stdout.strip().splitlines() == ["backup 🛰", "1", "sample_event"], output.stdout
assert b"previous" in api(f"snapshots/{result['safety_snapshot_id']}/download", raw=True)
for log in (hub_log, agent_log):
log.seek(0)
assert PASSWORD not in log.read()
print("MySQL direct/SSH capture, SSH apply, utf8mb4, view/routine/event, and limited-role failure with safety verified")
if __name__ == "__main__":
main()

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()

229
tests/mbu/fixture.py Normal file
View File

@@ -0,0 +1,229 @@
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

109
tests/mbu/legacy-import.py Normal file
View File

@@ -0,0 +1,109 @@
#!/usr/bin/env python3
"""Reconcile legacy archives and a private SQLite history without writing to S3."""
from contextlib import ExitStack
from pathlib import Path
from subprocess import DEVNULL
from tempfile import TemporaryDirectory
from urllib.request import urlopen
from uuid import uuid4
import gzip
import json
import sqlite3
from fixture import BIN, command, fixture_env, mysql_container, port, postgres, start_hub, wait_until
def main():
with ExitStack() as cleanup:
root = Path(cleanup.enter_context(TemporaryDirectory(prefix="tessera-legacy-")))
endpoint = f"http://127.0.0.1:{port()}"
container = "tessera-legacy-" + 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)
env = {**fixture_env(), "AWS_ACCESS_KEY_ID": "fixture-legacy-key", "AWS_SECRET_ACCESS_KEY": "fixture-legacy-secret",
"AWS_DEFAULT_REGION": "us-east-1", "AWS_EC2_METADATA_DISABLED": "true",
"TESSERA_VAULT_PASSPHRASE": "fixture-private-vault-key"}
bucket = "legacy-fixture"
aws = ("aws", "--endpoint-url", endpoint, "s3api")
command(*aws, "create-bucket", "--bucket", bucket, env=env, stdout=DEVNULL)
postgres_archive = gzip.compress(b"CREATE TABLE sample(value int);\nINSERT INTO sample VALUES (1);\n")
mysql = gzip.compress(b"CREATE TABLE sample(value INT) ENGINE=InnoDB;\nINSERT INTO sample VALUES (2);\n")
payloads = {"postgres": postgres_archive, "mysql": mysql}
for engine, payload in payloads.items():
file = root / f"{engine}.sql.gz"
file.write_bytes(payload)
command(*aws, "put-object", "--bucket", bucket, "--key", f"{engine}/2026-11-10.sql.gz",
"--body", file, env=env, stdout=DEVNULL)
history = root / "history.sqlite"
with sqlite3.connect(history) as db:
db.executescript("CREATE TABLE jobs(id INTEGER PRIMARY KEY, phase TEXT); INSERT INTO jobs VALUES(42,'archived');")
pg_root = root / "pg"
pg_root.mkdir()
pg, _ = postgres(cleanup, pg_root, ["legacy_fixture"])
mysql_client, _, _ = mysql_container(cleanup, root)
api, _, _, _ = start_hub(cleanup, root)
cli = (BIN / "tessera", "--data-dir", root / "hub")
for engine, payload in payloads.items():
orbit = api("orbits", {"name": engine, "provider": "wormhole", "provider_config": {}})
args = (*cli, "legacy-import", "--bucket", bucket, "--prefix", engine + "/", "--endpoint", endpoint,
"--orbit-id", orbit["id"], "--application", engine, "--engine", engine, "--history", history)
def report(*extra):
result = command(*args, *extra, env=env, capture_output=True)
return json.loads(result.stdout)
inventory = report("--inventory-only")
assert inventory["count"] == 1 and inventory["bytes"] == len(payload)
assert inventory["objects"][0]["status"] == "inventoried"
imported = report()
snapshot = imported["objects"][0]["snapshot_id"]
assert imported["objects"][0]["status"] == "imported"
restored = api(f"snapshots/{snapshot}/download", raw=True)
assert restored == payload
if engine == "postgres":
command("psql", *pg, "-d", "legacy_fixture", "-v", "ON_ERROR_STOP=1",
input=gzip.decompress(restored), stdout=DEVNULL)
value = command("psql", *pg, "-d", "legacy_fixture", "-Atc", "SELECT value FROM sample",
text=True, capture_output=True)
assert value.stdout.strip() == "1"
else:
command(*mysql_client, "-D", "fixture", input=gzip.decompress(restored), stdout=DEVNULL)
value = command(*mysql_client, "-D", "fixture", "-NB", "-e", "SELECT value FROM sample",
text=True, capture_output=True)
assert value.stdout.strip() == "2"
visible = next(entry for entry in api("snapshots") if entry["id"] == snapshot)
assert visible["size_bytes"] == len(payload)
assert visible["taken_at"] == imported["objects"][0]["last_modified"]
repeated = report()
assert repeated["objects"][0]["snapshot_id"] == snapshot
assert repeated["objects"][0]["status"] == "already_imported"
history_id = imported["history_snapshot_id"]
api(f"snapshots/{history_id}/download", expected=404)
exported = root / f"{engine}-history.sqlite"
command(*cli, "legacy-history", history_id, exported, env=env, stdout=DEVNULL)
with sqlite3.connect(exported.as_uri() + "?mode=ro", uri=True) as db:
assert db.execute("SELECT phase FROM jobs WHERE id=42").fetchone()[0] == "archived"
api(f"snapshots/{snapshot}", expected=204, method="DELETE")
command(*cli, "gc", env=env, stdout=DEVNULL)
assert report()["objects"][0]["status"] == "already_imported"
api(f"snapshots/{snapshot}/download", expected=404)
original = command(*aws, "head-object", "--bucket", bucket, "--key", f"{engine}/2026-11-10.sql.gz",
env=env, capture_output=True)
assert json.loads(original.stdout)["ContentLength"] == len(payload)
assert api("snapshots") == []
print("Read-only PostgreSQL/MySQL archive reconciliation, idempotency after GC, and private history verified")
if __name__ == "__main__":
main()

160
tests/mbu/matrix.py Normal file
View File

@@ -0,0 +1,160 @@
#!/usr/bin/env python3
"""Isolated rehearsal of the ten application shapes, including scheduled capture."""
from contextlib import ExitStack
from datetime import datetime, timedelta, timezone
from pathlib import Path
from tempfile import TemporaryDirectory
from uuid import uuid4
import json
import sqlite3
from fixture import bastion, command, mysql_container, pair, postgres, s3_container, start_agent, start_hub, wait_until
POSTGRES = [
"lti", "presensi", "sso", "helpdesk", "manbu", "daily_checklist",
"odoo_mas", "odoo_fta", "dashboard_management",
]
CAPTURE_ONLY = {"odoo_fta", "dashboard_management"}
def main():
with ExitStack() as cleanup:
root = Path(cleanup.enter_context(TemporaryDirectory(prefix="tessera-matrix-")))
pg, connection = postgres(cleanup, root, POSTGRES + [
app + "_staging" for app in POSTGRES if app not in CAPTURE_ONLY
])
pinned, _ = bastion(cleanup, root)
mysql, defaults, _ = mysql_container(cleanup, root)
offsite_password = root / "offsite-password"
offsite_password.write_text("fixture-matrix-s3-vault\n")
offsite_password.chmod(0o600)
endpoint, aws = s3_container(cleanup, "tessera-matrix")
api, url, _, _ = start_hub(cleanup, root, {
**aws, "TESSERA_OFFSITE_REPOSITORY": f"s3:{endpoint}/tessera-matrix/rehearsal",
"TESSERA_OFFSITE_PASSWORD_FILE": str(offsite_password),
})
def pg_sql(database, statement):
return command("psql", *pg, "-d", database, "-Atc", statement,
capture_output=True, text=True).stdout.strip()
def mysql_sql(database, statement):
return command(*mysql, "-NB", "-D", database, "-e", statement,
capture_output=True, text=True).stdout.strip()
pg_id = pg_sql("postgres", "SELECT system_identifier FROM pg_control_system()")
mysql_id = mysql_sql("fixture", "SELECT LOWER(@@server_uuid)")
mysql_sql("fixture", "CREATE DATABASE boiler_staging; CREATE TABLE sample(value VARCHAR(40));"
"INSERT INTO sample VALUES ('boiler'); CREATE VIEW sample_view AS SELECT value FROM sample")
mysql_sql("boiler_staging", "CREATE TABLE sample(value VARCHAR(40)); INSERT INTO sample VALUES ('previous')")
groups = {kind: {"agent": pair(api, f"fixture-{kind}"), "profiles": {}}
for kind in ("direct", "bastion", "mysql")}
applications = {}
for app in POSTGRES + ["boiler"]:
mysql_app = app == "boiler"
group = groups["mysql" if mysql_app else "bastion" if app in ("odoo_mas", "odoo_fta") else "direct"]
node = group["agent"]["outpost_id"]
orbit = api("orbits", {"name": app, "provider": "wormhole", "provider_config": {}})
app_id = str(uuid4())
engine = "mysql" if mysql_app else "postgres"
format = "mysql_sql" if mysql_app else "postgres_sql" if app == "daily_checklist" else "postgres_custom"
api("capture-profiles", {"application_id": app_id, "orbit_id": orbit["id"], "outpost_id": node,
"format": format, "schedule": {"hour": 2, "timezone": "Asia/Jakarta"}}, expected=201)
target_db = app + "_staging"
if mysql_app:
source = {"transport": "ssh", "bastion": pinned, "defaults_file": str(defaults), "database": "fixture"}
target = {"engine": engine, "connection": {**source, "database": target_db},
"recreate_database": True, "use_target_definer": True}
else:
pg_sql(app, "CREATE SCHEMA fixture; CREATE TABLE fixture.sample(value text);"
f"INSERT INTO fixture.sample VALUES ('{app}')")
source = connection(app)
if app in ("odoo_mas", "odoo_fta"):
source["bastion"] = pinned
mode = {"reset": "recreate_database"} if app == "odoo_mas" else {"reset": "schema", "schema": "fixture"}
target = {"engine": engine, "connection": {**source, "database": target_db}, "mode": mode}
if app == "daily_checklist":
post = root / "checklist.sql"
post.write_text("INSERT INTO fixture.sample VALUES ('post-restore');")
target["post_restore_sql"] = str(post)
profile = {"source": {"engine": engine, **source}, "timeout_seconds": 120}
target_id = None
if app not in CAPTURE_ONLY:
target_id = str(uuid4())
api("restore-targets", {"id": target_id, "application_id": app_id, "outpost_id": node,
"name": target_db, "engine": engine, "identity": {
"instance": mysql_id if mysql_app else pg_id, "database": target_db,
}}, expected=201)
profile["targets"] = {target_id: target}
group["profiles"][app_id] = profile
manual = api(f"capture-profiles/{app_id}/jobs", {}, expected=202)["id"]
applications[app] = (app_id, target_id, manual, target_db)
# Backdate registration to just before one elapsed slot, then let the real scheduler tick.
now = datetime.now(timezone.utc)
slot = now.replace(hour=19, minute=0, second=0, microsecond=0)
if slot > now:
slot -= timedelta(days=1)
with sqlite3.connect(root / "hub" / "tessera.db") as db:
db.execute("UPDATE capture_profiles SET registered_at = ?", (int(slot.timestamp()) - 1,))
for kind, group in groups.items():
directory = root / kind
directory.mkdir(mode=0o700)
start_agent(cleanup, directory, url, group["agent"]["upload_token"], group["profiles"])
def completed_captures():
jobs = api("capture-jobs?limit=100")
assert all(job["status"] != "failed" for job in jobs), jobs
return jobs if len(jobs) == 20 and all(job["status"] == "completed" and job["offsite_status"] == "copied" for job in jobs) else None
captures = wait_until(completed_captures, seconds=240)
snapshots = {snap["id"]: snap for snap in api("snapshots")}
stats, restores = {}, {}
for app, (app_id, target, manual, _) in applications.items():
jobs = [job for job in captures if job["profile"]["application_id"] == app_id]
assert {job["actor"] for job in jobs} == {"api-token", "scheduler"}
scheduled = next(job for job in jobs if job["actor"] == "scheduler")
current = next(job for job in jobs if job["id"] == manual)
stats[app] = {
"manual_seconds": current["updated_at"] - current["created_at"],
"scheduled_seconds": scheduled["updated_at"] - scheduled["created_at"],
"freshness_seconds": int(datetime.now(timezone.utc).timestamp()) - scheduled["updated_at"],
"bytes": snapshots[scheduled["snapshot_id"]]["size_bytes"],
"offsite": scheduled["offsite_status"],
}
if target:
restores[app] = api("restore-jobs", {"snapshot_id": manual, "target_id": target,
"confirmation": f"RESTORE {manual} TO {target}"}, expected=202)["id"]
else:
assert api(f"capture-profiles/{app_id}/restore-targets") == []
stats[app]["restore"] = "capture_only"
def restores_done():
results = {app: api(f"restore-jobs/{job}") for app, job in restores.items()}
assert all(job["status"] not in ("failed", "recovery_required") for job in results.values()), results
return results if all(job["status"] == "completed" for job in results.values()) else None
results = wait_until(restores_done, seconds=180)
for app, result in results.items():
_, _, _, database = applications[app]
assert result["safety_snapshot_id"]
if app == "boiler":
assert mysql_sql(database, "SELECT value FROM sample_view") == app
else:
expected = app + "\npost-restore" if app == "daily_checklist" else app
assert pg_sql(database, "SELECT value FROM fixture.sample ORDER BY value") == expected
stats[app]["restore"] = "verified"
archive = applications["lti"][2]
expected = api(f"snapshots/{archive}/download", raw=True)
primary = root / "hub" / "vault" / "restic"
primary.rename(primary.with_name("restic-offline"))
assert api(f"snapshots/{archive}/download", raw=True) == expected
print(json.dumps(stats, indent=2, sort_keys=True))
if __name__ == "__main__":
main()

87
tests/mbu/offsite.py Normal file
View File

@@ -0,0 +1,87 @@
#!/usr/bin/env python3
"""Verify retry and recovery from a separate S3-compatible Restic repository."""
from contextlib import ExitStack
from hashlib import sha256
from pathlib import Path
from subprocess import DEVNULL
from tempfile import TemporaryDirectory
from urllib.request import urlopen
from uuid import uuid4
import os
from fixture import command, pair, port, start_hub, wait_until
def main():
with ExitStack() as cleanup:
root = Path(cleanup.enter_context(TemporaryDirectory(prefix="tessera-s3-")))
endpoint = f"http://127.0.0.1:{port()}"
container = "tessera-s3-" + uuid4().hex
def ready():
try:
with urlopen(endpoint, timeout=1) as response:
return response.status == 200
except OSError:
return False
password = root / "offsite-password"
password.write_text("fixture-offsite-encryption\n")
password.chmod(0o600)
aws = {"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"}
api, _, _, hub_log = start_hub(cleanup, root, {
**aws, "TESSERA_OFFSITE_REPOSITORY": f"s3:{endpoint}/tessera-fixture/isolated",
"TESSERA_OFFSITE_PASSWORD_FILE": str(password),
})
agent = pair(api, "offsite fixture")
token = agent["upload_token"]
orbit = api("orbits", {"name": "offsite", "provider": "wormhole", "provider_config": {}})
app = str(uuid4())
api("capture-profiles", {"application_id": app, "orbit_id": orbit["id"],
"outpost_id": agent["outpost_id"], "format": "postgres_sql"}, expected=201)
job = api(f"capture-profiles/{app}/jobs", {}, expected=202)["id"]
lease = api(f"wormhole/capture/{app}/claim", {}, token)
for phase in ("dumping", "uploading"):
api(f"wormhole/capture/{job}/report", {"lease_id": lease["lease_id"], "progress": phase},
token, expected=204)
payload = b"CREATE TABLE archived (value INTEGER);\nINSERT INTO archived VALUES (42);\n"
headers = {"X-Tessera-Lease-Id": lease["lease_id"], "X-Tessera-Sha256": sha256(payload).hexdigest()}
assert api(f"wormhole/capture/{job}/payload", payload, token, extra=headers)["snapshot_id"] == job
wait_until(lambda: api(f"capture-jobs/{job}")["offsite_status"] == "failed", seconds=90)
api(f"snapshots/{job}", expected=409, method="DELETE")
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)
wait_until(ready)
command("aws", "--endpoint-url", endpoint, "s3api", "create-bucket",
"--bucket", "tessera-fixture", env={**os.environ, **aws}, stdout=DEVNULL)
wait_until(lambda: api(f"capture-jobs/{job}")["offsite_status"] == "copied", seconds=45)
assert len(api("snapshots")) == 1
primary = root / "hub" / "vault" / "restic"
primary.rename(primary.with_name("restic-offline"))
assert api(f"snapshots/{job}/download", raw=True) == payload
api(f"snapshots/{job}", expected=204, method="DELETE")
assert api("snapshots") == []
api(f"snapshots/{job}/download", expected=404)
# Recover using only the S3 URL, Restic password, and the Tessera snapshot UUID.
env = {**os.environ, **aws, "RESTIC_PASSWORD_FILE": str(password)}
repo = f"s3:{endpoint}/tessera-fixture/isolated"
import json
listing = command("restic", "-r", repo, "snapshots", "--json", "--tag", f"tessera-{job}",
env=env, capture_output=True)
copies = json.loads(listing.stdout)
assert len(copies) == 1
recovered = command("restic", "-r", repo, "dump", copies[0]["id"], "/payload",
env=env, capture_output=True)
assert recovered.stdout == payload
hub_log.seek(0)
logs = hub_log.read()
assert all(secret not in logs for secret in (*aws.values(), "fixture-offsite-encryption") if secret.startswith("fixture"))
print("Failed S3 copy, retry, and byte-identical download with the primary repository offline verified")
if __name__ == "__main__":
main()

157
tests/mbu/restic-orbits.py Normal file
View File

@@ -0,0 +1,157 @@
#!/usr/bin/env python3
"""Exercise the orbit source/access matrix with a TLS Rest Server and PostgreSQL."""
from contextlib import ExitStack
from io import BytesIO
from pathlib import Path
from subprocess import DEVNULL, Popen, run
from tempfile import TemporaryDirectory
from uuid import uuid4
from argparse import ArgumentParser
import json
import os
import tarfile
from fixture import PASSWORD, command, mysql_container, pair, port, start_agent, start_hub, stop, terminal, wait_until
def main(with_mysql):
with ExitStack() as cleanup:
root = Path(cleanup.enter_context(TemporaryDirectory(prefix="tessera-restic-orbits-")))
password = root / "password"
password.write_text(PASSWORD + "\n")
password.chmod(0o600)
data = root / "db"
pg_port = port()
command("initdb", "-D", data, "-U", "fixture", "--auth-local=trust",
"--auth-host=scram-sha-256", "--pwfile", password, stdout=DEVNULL)
command("pg_ctl", "-D", data, "-l", root / "postgres.log", "-w", "start",
"-o", f"-h 127.0.0.1 -p {pg_port} -k {root}", 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", "restored"):
command("createdb", *pg, database)
command("psql", *pg, "-d", "source", "-v", "ON_ERROR_STOP=1", "-c",
"CREATE TABLE changes (id int PRIMARY KEY, value text);"
"INSERT INTO changes SELECT i, md5(i::text) FROM generate_series(1, 500000) i;",
stdout=DEVNULL)
db = {"engine": "postgres", "host": "127.0.0.1", "port": pg_port, "user": "fixture",
"database": "source", "password_file": str(password), "tls": {"mode": "disable"}}
folder = root / "source"
folder.mkdir()
original = os.urandom(3 * 1024 * 1024)
(folder / "test.bin").write_bytes(original)
cases = [
("filesystem", "filesystem", "filesystem", {"paths": [str(folder)]}),
("postgres", "database", "postgres_sql", {"source": db}),
]
if with_mysql:
mysql, _, mysql_port = mysql_container(cleanup, root)
command(*mysql, "-D", "fixture", "-e",
"CREATE TABLE changes (id INT PRIMARY KEY, value TEXT);"
"INSERT INTO changes VALUES (1, 'restored MySQL'); CREATE DATABASE restored;")
cases.append(("mysql", "database", "mysql_sql", {"source": {
"engine": "mysql", "transport": "direct", "host": "127.0.0.1", "port": mysql_port,
"user": "root", "database": "fixture", "password_file": str(password), "tls": {"mode": "required"},
}}))
api, url, _, hub_log = start_hub(cleanup, root)
paired = pair(api, "Restic fixture")
vault = root / "hub" / "vault"
repos = vault / "outposts"
repos.mkdir(exist_ok=True)
ca, key = root / "server.crt", root / "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)
rest_port = port()
auth = root / "htpasswd"
auth.touch()
configs = {}
outposts = {}
for case, source, fmt, config in cases:
hub_config = config if source == "filesystem" else config["source"]
hub = api("orbits", {"name": f"{case} hub", "source": source, "access": "hub",
"provider_config": hub_config})
assert (hub["source"], hub["access"]) == (source, "hub")
api(f"orbits/{hub['id']}/run", {}, expected=204)
orbit = api("orbits", {"name": f"{case} outpost", "source": source, "access": "outpost",
"provider_config": {}, "retention": {
"keep_daily": 1, "keep_weekly": 0, "keep_monthly": 0, "keep_yearly": 0,
}})
assert (orbit["source"], orbit["access"]) == (source, "outpost")
orbit_id = orbit["id"]
application = str(uuid4())
outposts[case] = application
(vault / "keys" / f"outpost-{orbit_id}.json").write_text(json.dumps({
"outpost_id": paired["outpost_id"], "password": PASSWORD,
}))
command("restic", "-r", repos / orbit_id, "--password-file", password, "init", stdout=DEVNULL)
command("htpasswd", "-Bb", auth, orbit_id, PASSWORD, stdout=DEVNULL, stderr=DEVNULL)
other = "postgres_sql" if source == "filesystem" else "filesystem"
profile = {"orbit_id": orbit_id, "application_id": application, "outpost_id": paired["outpost_id"]}
api("capture-profiles", {**profile, "format": other}, expected=409)
api("capture-profiles", {**profile, "format": fmt}, expected=201)
configs[application] = {**config, "restic_repository": f"rest:https://localhost:{rest_port}/{orbit_id}/",
"restic_password_file": str(password), "rest_server_password_file": str(password)}
rest_log = cleanup.enter_context((root / "rest-server.log").open("w+"))
server = Popen(["rest-server", "--listen", f"127.0.0.1:{rest_port}", "--path", repos,
"--tls", "--tls-cert", ca, "--tls-key", key, "--htpasswd-file", auth,
"--append-only", "--private-repos"], stdout=rest_log, stderr=rest_log)
cleanup.callback(stop, server)
wait_until(lambda: run(["curl", "-s", "--cacert", ca, f"https://localhost:{rest_port}/"],
stdout=DEVNULL).returncode == 0)
_, agent_log = start_agent(cleanup, root, url, paired["upload_token"], configs,
settings={"RESTIC_CACERT": str(ca)})
def capture(application):
job = api(f"capture-profiles/{application}/jobs", {}, expected=202)["id"]
result = wait_until(lambda: terminal(api, job))
assert result["status"] == "completed", result
return next(snapshot for snapshot in api("snapshots") if snapshot["id"] == result["snapshot_id"])
try:
for case, application in outposts.items():
first = capture(application)
if case == "filesystem":
(folder / "tiny.txt").write_text("incremental")
elif case == "postgres":
command("psql", *pg, "-d", "source", "-c",
"UPDATE changes SET value = 'incremental' WHERE id = 50000;", stdout=DEVNULL)
second = capture(application)
assert second["stored_bytes"] < first["stored_bytes"], (first, second)
wait_until(lambda: first["id"] not in {snapshot["id"] for snapshot in api("snapshots")})
payload = api(f"snapshots/{second['id']}/download", raw=True)
if case == "filesystem":
with tarfile.open(fileobj=BytesIO(payload)) as archive:
files = {Path(member.name).name: archive.extractfile(member).read()
for member in archive if member.isfile()}
assert files == {"test.bin": original, "tiny.txt": b"incremental"}
elif case == "postgres":
assert second["capture"]["restore_ready"]
command("psql", *pg, "-d", "restored", "-v", "ON_ERROR_STOP=1",
input=payload, stdout=DEVNULL)
restored = command("psql", *pg, "-d", "restored", "-At", "-c",
"SELECT value FROM changes WHERE id = 50000;", capture_output=True)
assert restored.stdout.strip() == b"incremental"
else:
assert second["capture"]["restore_ready"] and second["new_data_chunks"] == 0
command(*mysql, "-D", "restored", input=payload)
restored = command(*mysql, "-NB", "-D", "restored", "-e",
"SELECT value FROM changes WHERE id = 1;", capture_output=True)
assert restored.stdout.strip() == b"restored MySQL"
print(f"{case}: {first['stored_bytes']} → {second['stored_bytes']} packed bytes, restore verified")
except Exception:
for log in (hub_log, agent_log, rest_log):
log.seek(0)
print(log.read())
raise
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("--mysql", action="store_true")
main(parser.parse_args().mysql)

View File

@@ -0,0 +1,260 @@
#!/usr/bin/env python3
"""Restore authorization, target safety, PostgreSQL reset modes, and recovery."""
from contextlib import ExitStack
from hashlib import sha256
from pathlib import Path
from subprocess import CalledProcessError, DEVNULL
from tempfile import TemporaryDirectory
from uuid import uuid4
import base64
import gzip
import json
import sqlite3
from fixture import bastion, command, pair, postgres, register_capture, start_agent, start_hub, stop, terminal, wait_until
def main():
with ExitStack() as cleanup:
root = Path(cleanup.enter_context(TemporaryDirectory(prefix="tessera-restore-pg-")))
pg, connection = postgres(cleanup, root, ["source_db", "schema_target", "recreate_target",
"wrong_target", "manual_target", "recovery_target",
"compressed_target", "corrupt_target", "meta_target"])
def sql(database, statements):
return command("psql", *pg, "-d", database, "-v", "ON_ERROR_STOP=1", "-Atc", statements,
capture_output=True, text=True).stdout.strip()
create = "CREATE SCHEMA fixture; CREATE TABLE fixture.rows(id int PRIMARY KEY, value text);"
for db in ["source_db", "schema_target", "recreate_target", "wrong_target", "manual_target",
"recovery_target", "compressed_target", "corrupt_target", "meta_target"]:
value = "source data" if db == "source_db" else db
sql(db, create + f"INSERT INTO fixture.rows VALUES (1, '{value}');")
instance = sql("postgres", "SELECT system_identifier FROM pg_control_system()")
pinned, _ = bastion(cleanup, root)
api, hub_url, _, _, hub_process = start_hub(cleanup, root, return_handle=True)
agent = pair(api, "restore outpost")
other = pair(api, "foreign outpost")
token = agent["upload_token"]
app = register_capture(api, agent["outpost_id"], "pg-restore", "postgres_custom")
plain_app = register_capture(api, agent["outpost_id"], "pg-plain", "postgres_sql")
foreign_app = register_capture(api, other["outpost_id"], "foreign", "postgres_custom")
def register_target(application, database, instance_id=instance, outpost=agent["outpost_id"]):
target = str(uuid4())
api("restore-targets", {
"id": target, "application_id": application, "outpost_id": outpost, "name": database,
"engine": "postgres", "identity": {"instance": instance_id, "database": database},
}, expected=201)
return target
schema = register_target(app, "schema_target")
recreate = register_target(app, "recreate_target")
wrong = register_target(app, "wrong_target", str(int(instance) - 1))
manual = register_target(app, "manual_target")
recovery = register_target(app, "recovery_target")
corrupt = register_target(app, "corrupt_target")
sql("recovery_target", "GRANT SELECT ON fixture.rows TO PUBLIC")
compressed = register_target(plain_app, "compressed_target")
meta_target = register_target(plain_app, "meta_target")
source_alias = register_target(app, "source_db")
foreign = register_target(foreign_app, "manual_target", str(int(instance) - 2), other["outpost_id"])
post = root / "post.sql"
post.write_text("INSERT INTO fixture.rows VALUES (2, 'post-restore');\n")
broken = root / "broken.sql"
broken.write_text("SELECT pg_sleep(120);\n")
def local(database, reset, **opts):
target = connection(database)
if reset == "recreate_database":
target["bastion"] = pinned
mode = {"reset": reset}
if reset == "schema":
mode["schema"] = "fixture"
return {"engine": "postgres", "connection": target, "mode": mode, **opts}
capture_id = api(f"capture-profiles/{app}/jobs", {}, expected=202)["id"]
profiles = {
app: {"source": {"engine": "postgres", **connection("source_db")}, "timeout_seconds": 45,
"targets": {
schema: local("schema_target", "schema", post_restore_sql=str(post)),
recreate: local("recreate_target", "recreate_database"),
wrong: local("wrong_target", "schema"),
recovery: local("recovery_target", "recreate_database", post_restore_sql=str(broken)),
corrupt: local("corrupt_target", "schema"),
}},
plain_app: {"timeout_seconds": 45, "targets": {
compressed: local("compressed_target", "schema",
omit_transaction_timeout=True, omit_pg_stat_statements=True),
meta_target: local("meta_target", "schema"),
}},
}
agent_process, agent_log = start_agent(cleanup, root, hub_url, token, profiles)
result = wait_until(lambda: terminal(api, capture_id))
assert result["status"] == "completed", result
def enqueue(snapshot, target, expected=202, confirmation=None):
return api("restore-jobs", {"snapshot_id": snapshot, "target_id": target,
"confirmation": confirmation or f"RESTORE {snapshot} TO {target}"}, expected=expected)
def finished(job):
value = api(f"restore-jobs/{job}")
if value["status"] in ("completed", "failed", "recovery_required"):
return value
enqueue(capture_id, schema, expected=400, confirmation="wrong confirmation")
enqueue(capture_id, foreign, expected=422)
enqueue(capture_id, source_alias, expected=422)
enqueue(capture_id, str(uuid4()), expected=422)
api("restore-targets", {"id": str(uuid4()), "application_id": app,
"outpost_id": agent["outpost_id"], "name": "MySQL mismatch", "engine": "mysql",
"identity": {"instance": str(uuid4()), "database": "mismatch"}}, expected=422)
assert api(f"capture-profiles/{foreign_app}/restore-targets")[0]["id"] == foreign
# Check the scoped payload and prove a failed safety write cannot grant apply.
manual_job = enqueue(capture_id, manual)["id"]
api(f"snapshots/{capture_id}", expected=409, method="DELETE")
assert api(f"wormhole/restore-targets/{manual}/claim", {}, other["upload_token"]) is None
lease = api(f"wormhole/restore-targets/{manual}/claim", {}, token)
assert lease["job"]["id"] == manual_job
auth = {"X-Tessera-Restore-Token": lease["token"]}
path = f"wormhole/restore/{manual_job}"
api(f"{path}/report", "checking", token, expected=204, extra=auth)
api(f"{path}/payload", token=token, expected=401)
api(f"{path}/payload", token=other["upload_token"], expected=403, extra=auth)
api(f"wormhole/restore/{uuid4()}/payload", token=token, expected=403, extra=auth)
archive = api(f"{path}/payload", token=token, extra=auth, raw=True)
assert sha256(archive).hexdigest() == lease["artifact"]["sha256"]
api(f"{path}/report", "safety", token, expected=204, extra=auth)
api(f"{path}/safety", archive, token, expected=422, extra={**auth, "X-Tessera-Sha256": "0" * 64})
api(f"{path}/apply", {}, token, expected=409, extra=auth)
assert sql("manual_target", "SELECT value FROM fixture.rows") == "manual_target"
api(f"restore-jobs/{manual_job}", expected=204, method="DELETE")
for target, name, expected_value in [
(schema, "schema_target", "source data\npost-restore"),
(recreate, "recreate_target", "source data"),
]:
job = enqueue(capture_id, target)["id"]
done = wait_until(lambda: finished(job), seconds=65)
if done["status"] != "completed":
agent_log.seek(0)
print(agent_log.read())
assert done["status"] == "completed" and done["safety_snapshot_id"], done
assert sql(name, "SELECT value FROM fixture.rows ORDER BY id") == expected_value
job = enqueue(capture_id, wrong)["id"]
failed = wait_until(lambda: finished(job))
assert failed["phase"] == "wrong_target" and failed["safety_snapshot_id"] is None, failed
assert sql("wrong_target", "SELECT value FROM fixture.rows") == "wrong_target"
# An operator can recover from the pinned safety artifact after an interrupted apply.
job = enqueue(capture_id, recovery)["id"]
def reset_observed():
state = api(f"restore-jobs/{job}")
if state["status"] != "applying":
return False
try:
return sql("recovery_target", "SELECT to_regclass('fixture.rows')") == ""
except CalledProcessError:
return False
wait_until(reset_observed, seconds=45)
stop(agent_process)
stop(hub_process)
# Advance this fixture lease to its deadline before restarting the hub.
with sqlite3.connect(root / "hub" / "tessera.db") as db:
stale_token = db.execute("SELECT lease_token FROM restore_jobs WHERE id = ?", (job,)).fetchone()[0]
db.execute("UPDATE restore_jobs SET lease_until = 0 WHERE id = ?", (job,))
api, hub_url, _, _ = start_hub(cleanup, root)
interrupted = api(f"restore-jobs/{job}")
assert interrupted["status"] == "recovery_required" and interrupted["phase"] == "lease_lost", interrupted
assert interrupted["safety_snapshot_id"]
api(f"wormhole/restore/{job}/apply", {}, token, expected=409, extra={"X-Tessera-Restore-Token": stale_token})
safety = interrupted["safety_snapshot_id"]
api(f"snapshots/{safety}", expected=409, method="DELETE")
api(f"snapshots/{capture_id}", expected=409, method="DELETE")
assert sql("recovery_target", "SELECT to_regclass('fixture.rows')") == ""
saved = root / "safety.dump"
saved.write_bytes(api(f"snapshots/{safety}/download", raw=True))
command("pg_restore", *pg, "-d", "recovery_target", "--exit-on-error", saved, stdout=DEVNULL)
assert sql("recovery_target", "SELECT value FROM fixture.rows") == "recovery_target"
assert "=r/" in sql("recovery_target", "SELECT relacl FROM pg_class WHERE oid = 'fixture.rows'::regclass")
api(f"restore-jobs/{job}/reconcile", {"confirmation": f"RECONCILE {job}"}, expected=204)
assert api(f"restore-jobs/{job}")["status"] == "reconciled"
# Restore a real PostgreSQL 17 dump into the older fixture.
container = "tessera-pg17-" + uuid4().hex
command("docker", "run", "--rm", "-d", "--name", container,
"-e", "POSTGRES_PASSWORD=fixture-pg17", "-e", "POSTGRES_USER=fixture",
"-e", "POSTGRES_DB=source17", "postgres:17", stdout=DEVNULL)
cleanup.callback(command, "docker", "stop", "-t", "3", container, stdout=DEVNULL)
def postgres17_ready():
try:
command("docker", "exec", container, "pg_isready", "-U", "fixture", "-d", "source17",
stdout=DEVNULL, stderr=DEVNULL)
return True
except CalledProcessError:
return False
wait_until(postgres17_ready, seconds=90)
pg17 = ("docker", "exec", container, "psql", "-X", "-U", "fixture", "-d", "source17",
"-v", "ON_ERROR_STOP=1", "-Atc")
command(*pg17, "CREATE EXTENSION pg_stat_statements; CREATE ROLE fixture_dump_owner;"
"CREATE SCHEMA fixture; CREATE TABLE fixture.rows(id int, value text);"
"ALTER TABLE fixture.rows OWNER TO fixture_dump_owner;"
"GRANT SELECT ON fixture.rows TO PUBLIC; INSERT INTO fixture.rows VALUES (1, 'compressed');",
stdout=DEVNULL)
source17_id = command(*pg17, "SELECT system_identifier FROM pg_control_system()",
capture_output=True, text=True).stdout.strip()
text = command("docker", "exec", container, "pg_dump", "-U", "fixture", "-d", "source17",
"--no-owner", "--no-acl", capture_output=True).stdout
assert b"SET transaction_timeout = 0;" in text and b"pg_stat_statements" in text
assert b"OWNER TO fixture_dump_owner" not in text and b"GRANT SELECT" not in text
plain_id = api(f"capture-profiles/{plain_app}/jobs", {}, expected=202)["id"]
claim = api(f"wormhole/capture/{plain_app}/claim", {}, token)
for phase in ("dumping", "uploading"):
api(f"wormhole/capture/{plain_id}/report", {"lease_id": claim["lease_id"], "progress": phase},
token, expected=204)
data = gzip.compress(text)
identity = base64.urlsafe_b64encode(json.dumps({"instance": source17_id, "database": "source17"}).encode()).decode().rstrip("=")
api(f"wormhole/capture/{plain_id}/payload", data, token, extra={
"X-Tessera-Lease-Id": claim["lease_id"], "X-Tessera-Sha256": sha256(data).hexdigest(),
"X-Tessera-Source-Identity": identity,
})
corrupted = enqueue(capture_id, corrupt)["id"]
with sqlite3.connect(root / "hub" / "tessera.db") as db:
db.execute("UPDATE restore_jobs SET artifact = json_set(artifact, '$.sha256', ?) WHERE id = ?",
("0" * 64, corrupted))
agent_process, _ = start_agent(cleanup, root, hub_url, token, profiles)
invalid = wait_until(lambda: finished(corrupted))
assert invalid["phase"] == "invalid_payload" and invalid["safety_snapshot_id"] is None, invalid
assert sql("corrupt_target", "SELECT value FROM fixture.rows") == "corrupt_target"
job = enqueue(plain_id, compressed)["id"]
done = wait_until(lambda: finished(job), seconds=65)
assert done["status"] == "completed", done
assert sql("compressed_target", "SELECT value FROM fixture.rows") == "compressed"
marker = root / "unexpected-shell-execution"
bad_archive = f"\\! touch {marker}\n".encode()
bad_id = api(f"capture-profiles/{plain_app}/jobs", {}, expected=202)["id"]
claim = api(f"wormhole/capture/{plain_app}/claim", {}, token)
for phase in ("dumping", "uploading"):
api(f"wormhole/capture/{bad_id}/report", {"lease_id": claim["lease_id"], "progress": phase},
token, expected=204)
api(f"wormhole/capture/{bad_id}/payload", bad_archive, token, extra={
"X-Tessera-Lease-Id": claim["lease_id"], "X-Tessera-Sha256": sha256(bad_archive).hexdigest(),
"X-Tessera-Source-Identity": identity,
})
job = enqueue(bad_id, meta_target)["id"]
guarded = wait_until(lambda: finished(job), seconds=65)
assert guarded["status"] == "recovery_required", guarded
assert not marker.exists() and sql("meta_target", "SELECT value FROM fixture.rows") == "meta_target"
print("PostgreSQL scoped restore, verified safety, schema/recreate, compatibility, restricted client, and recovery verified")
if __name__ == "__main__":
main()