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>
261 lines
15 KiB
Python
261 lines
15 KiB
Python
#!/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()
|