#!/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()