diff --git a/pkgs/cold-store-reaper/README.md b/pkgs/cold-store-reaper/README.md index 32982920d7..50cec23c6b 100644 --- a/pkgs/cold-store-reaper/README.md +++ b/pkgs/cold-store-reaper/README.md @@ -171,11 +171,25 @@ environment only): - `scripts/nightly-backup.sh` — the nightly run: `backup-d1`, then `backup-supabase` (only when both R2 credentials are set; a skip notice is printed otherwise — never an error), then - `prune-backups --apply`, then `sync-manifest`, then `status`. Any - failing step aborts the run non-zero. Requires `CLOUDFLARE_API_TOKEN` - in the environment (materialize from Bitwarden into the cron env); + `scripts/export-turso.sh`, then `prune-backups --apply`, then + `sync-manifest`, then `status`. Any failing step aborts the run + non-zero. Requires `CLOUDFLARE_API_TOKEN` in the environment + (materialize from Bitwarden into the cron env); `R2_ACCESS_KEY_ID` / `R2_SECRET_ACCESS_KEY` are optional (they gate - the Supabase step). + the Supabase step), as is `TURSO_PLATFORM_API_TOKEN` (it gates the + Turso step). +- `scripts/export-turso.sh` — the Turso step: discovers every + database in the Turso organization through the Platform API (no + `turso` CLI needed), mints a per-database auth token, downloads + the SQL dump each database's own libsql endpoint serves at + `/dump`, rebuilds it into a standalone SQLite file (filed only + when `PRAGMA integrity_check` passes), gzips it, and files it + with `put-backup turso`. When `TURSO_PLATFORM_API_TOKEN` is + unset it prints a one-line skip notice and exits 0 — the nightly + run never fails for a missing Turso setup — but a database that + fails to export is named in a loud error line and makes the step + exit non-zero once the remaining databases have been attempted. + Token values are never printed. - `scripts/restore-drill.sh` — the quarterly restore drill (design section 8): picks 3 pseudo-random cold objects from the local manifest, fetches each through the rehydrator Worker and verifies its diff --git a/pkgs/cold-store-reaper/scripts/export-turso.sh b/pkgs/cold-store-reaper/scripts/export-turso.sh new file mode 100755 index 0000000000..e96f596737 --- /dev/null +++ b/pkgs/cold-store-reaper/scripts/export-turso.sh @@ -0,0 +1,183 @@ +#!/usr/bin/env bash +# export-turso.sh — file a portable SQLite export of every Turso +# database into the cold store's Drive db-backups/turso/ folder +# (DESIGN.md section 5), via Turso's HTTP APIs — no turso CLI needed. +# +# How: the Platform API (api.turso.tech) has no dump route, but each +# database's own libsql endpoint serves one: GET https:///dump +# with a per-database auth token returns the complete SQL dump. So per +# database: mint a token (POST .../databases//auth/tokens, with +# the platform token), download /dump with curl, rebuild a standalone +# SQLite file with python3, require PRAGMA integrity_check = ok, +# gzip -6, and file it with `cold-store put-backup turso`. +# +# Databases are discovered from the Platform API +# (GET .../organizations//databases — items carry Name and +# Hostname), so new databases are picked up automatically. +# +# Environment — supplied by the operator/cron; the script stores +# nothing and never prints a token value (platform or per-database): +# TURSO_PLATFORM_API_TOKEN required to run. Materialize it from +# Bitwarden (turso.platform-api-token-muse-cli) +# into the cron environment. When unset the +# script prints a skip line and exits 0: +# a missing Turso setup never fails the +# nightly run, but the skip is never silent. +# TURSO_ORG optional; the Turso organization slug +# (default dezren39). +# TURSO_API_BASE optional; Platform API base URL +# (default https://api.turso.tech). +# Test seam, mirrors COLD_STORE_S3_BASE. +# TURSO_DUMP_BASE optional; when set, dumps are fetched +# from //dump +# instead of https:///dump. +# Test seam. +# COLD_STORE_BIN optional; the cold-store executable +# (default: ../cold-store next to this +# script). +# +# A database that fails any stage prints a loud ERROR line naming it; +# the run continues with the remaining databases and exits non-zero +# at the end if any database failed. +set -euo pipefail + +if [[ -z ${TURSO_PLATFORM_API_TOKEN:-} ]]; then + echo "turso export: skipped (TURSO_PLATFORM_API_TOKEN not set)" + exit 0 +fi + +ORG="${TURSO_ORG:-dezren39}" +API_BASE="${TURSO_API_BASE:-https://api.turso.tech}" +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +COLD_STORE="${COLD_STORE_BIN:-${SCRIPT_DIR}/../cold-store}" + +WORK="$(mktemp -d)" +trap 'rm -rf "${WORK}"' EXIT + +# ------------------------------------------------------------ discovery +if ! curl -fsS --max-time 60 \ + -H "Authorization: Bearer ${TURSO_PLATFORM_API_TOKEN}" \ + "${API_BASE}/v1/organizations/${ORG}/databases" \ + -o "${WORK}/databases.json"; then + echo "turso export: ERROR: could not list databases from ${API_BASE} (org ${ORG})" >&2 + exit 1 +fi +# Emit one "NameHostname" line per database. +if ! python3 - "${WORK}/databases.json" >"${WORK}/databases.tsv" <<'PY' +import json +import sys + +with open(sys.argv[1]) as fh: + payload = json.load(fh) +items = payload.get("databases", payload) if isinstance(payload, dict) else payload +for item in items: + print(f"{item['Name']}\t{item['Hostname']}") +PY +then + echo "turso export: ERROR: could not parse the Platform API database list" >&2 + exit 1 +fi +mapfile -t DB_ROWS <"${WORK}/databases.tsv" +if [[ ${#DB_ROWS[@]} -eq 0 ]]; then + echo "turso export: ERROR: Platform API returned no databases for org ${ORG}" >&2 + exit 1 +fi + +# ------------------------------------------------------------ one database +export_one() { + local name="$1" hostname="$2" + local dump_sql="${WORK}/${name}.sql" db_file="${WORK}/${name}.db" + local jwt dump_url + + # Mint a per-database auth token (the value is never printed). + if ! curl -fsS --max-time 60 -X POST \ + -H "Authorization: Bearer ${TURSO_PLATFORM_API_TOKEN}" \ + "${API_BASE}/v1/organizations/${ORG}/databases/${name}/auth/tokens" \ + -o "${WORK}/${name}.token.json"; then + echo "turso export: ERROR: ${name}: could not mint a database auth token" >&2 + return 1 + fi + if ! jwt="$( + python3 - "${WORK}/${name}.token.json" <<'PY' +import json +import sys + +with open(sys.argv[1]) as fh: + print(json.load(fh)["jwt"]) +PY + )" || [[ -z ${jwt} ]]; then + echo "turso export: ERROR: ${name}: token response carried no jwt" >&2 + return 1 + fi + + # Download the SQL dump from the database's own libsql endpoint + # (curl: the proxy-safe transport in the cron sandbox). + if [[ -n ${TURSO_DUMP_BASE:-} ]]; then + dump_url="${TURSO_DUMP_BASE}/${name}/dump" + else + dump_url="https://${hostname}/dump" + fi + if ! curl -fsS --max-time 300 \ + -H "Authorization: Bearer ${jwt}" \ + "${dump_url}" -o "${dump_sql}"; then + echo "turso export: ERROR: ${name}: dump download failed (${dump_url})" >&2 + return 1 + fi + unset jwt + + # Rebuild a standalone SQLite file; integrity must check out. + if ! python3 - "${dump_sql}" "${db_file}" <<'PY' +import sqlite3 +import sys + +src, dst = sys.argv[1], sys.argv[2] +with open(src) as fh: + sql = fh.read() +con = sqlite3.connect(dst) +try: + con.executescript(sql) + row = con.execute("PRAGMA integrity_check").fetchone() +finally: + con.close() +if row is None or row[0] != "ok": + print(f"integrity_check returned {row}", file=sys.stderr) + sys.exit(1) +PY + then + echo "turso export: ERROR: ${name}: dump did not rebuild to an integrity-clean SQLite file" >&2 + return 1 + fi + + if ! gzip -6 -f "${db_file}"; then + echo "turso export: ERROR: ${name}: gzip failed" >&2 + return 1 + fi + if ! "${COLD_STORE}" put-backup turso "${db_file}.gz"; then + echo "turso export: ERROR: ${name}: cold-store put-backup failed" >&2 + return 1 + fi + local gz_size + if ! gz_size="$(stat -c %s "${db_file}.gz")"; then + echo "turso export: ERROR: ${name}: could not stat the gzipped export" >&2 + return 1 + fi + echo "turso export: filed ${name} (${gz_size} bytes gzipped)" +} + +FAILURES=0 +for row in "${DB_ROWS[@]}"; do + name="${row%%$'\t'*}" + hostname="${row##*$'\t'}" + # shellcheck disable=SC2310 # by design: export_one guards every + # stage itself and returns 1, so one database's failure is counted + # here instead of aborting the run via set -e. + if ! export_one "${name}" "${hostname}"; then + FAILURES=$((FAILURES + 1)) + fi +done + +if [[ ${FAILURES} -gt 0 ]]; then + echo "turso export: ${FAILURES} of ${#DB_ROWS[@]} database(s) FAILED" >&2 + exit 1 +fi +echo "turso export: all ${#DB_ROWS[@]} database(s) filed" diff --git a/pkgs/cold-store-reaper/scripts/nightly-backup.sh b/pkgs/cold-store-reaper/scripts/nightly-backup.sh index 4ab171ec4b..5cb0a6c1ca 100755 --- a/pkgs/cold-store-reaper/scripts/nightly-backup.sh +++ b/pkgs/cold-store-reaper/scripts/nightly-backup.sh @@ -11,12 +11,17 @@ # only when the R2 credentials below # are set; skipped (not an error) # otherwise -# 3. cold-store prune-backups --apply +# 3. scripts/export-turso.sh file a portable SQLite export of +# every Turso database in +# db-backups/turso/ — only when the +# Turso platform token below is set; +# skipped (not an error) otherwise +# 4. cold-store prune-backups --apply # enforce 30 daily / 12 weekly / # 12 monthly retention across all DBs -# 4. cold-store sync-manifest push the local manifest (including +# 5. cold-store sync-manifest push the local manifest (including # tonight's ledger rows) to D1 -# 5. cold-store status one-screen summary (head) +# 6. cold-store status one-screen summary (head) # # Environment — the operator/cron supplies these; the script itself # stores nothing and echoes no secret values: @@ -30,6 +35,12 @@ # cloudflare.r2-backups-secret-access-key). # When either is unset, step 2 is skipped with # a one-line notice instead of failing the run. +# TURSO_PLATFORM_API_TOKEN +# optional. Turso Platform API token (Bitwarden: +# turso.platform-api-token-muse-cli). When unset, +# step 3 is skipped with a one-line notice +# instead of failing the run. See +# scripts/export-turso.sh for its own env. # COLD_STORE_HOME optional; the reaper home (default # ~/.config/cold-store). That directory's # credentials.json holds the Drive grant. @@ -48,6 +59,7 @@ if [[ -n ${R2_ACCESS_KEY_ID:-} && -n ${R2_SECRET_ACCESS_KEY:-} ]]; then else echo "nightly-backup: R2 credentials not set — skipping backup-supabase" fi +"${SCRIPT_DIR}/export-turso.sh" "${COLD_STORE}" prune-backups --apply "${COLD_STORE}" sync-manifest "${COLD_STORE}" status | head -n 20 diff --git a/pkgs/cold-store-reaper/tests/test_cold_store.py b/pkgs/cold-store-reaper/tests/test_cold_store.py index 33fcd9d3ad..a7ff31fd1b 100644 --- a/pkgs/cold-store-reaper/tests/test_cold_store.py +++ b/pkgs/cold-store-reaper/tests/test_cold_store.py @@ -6,6 +6,7 @@ """ import contextlib +import gzip import hashlib import io import json @@ -1907,6 +1908,184 @@ def test_pre_v3_manifest_gains_trash_direction(self): self.assertEqual(n, 1) +# ---------------------------------------------------------------- fake Turso +class FakeTurso: + """State for the fake Turso Platform API + libsql dump endpoints.""" + + PLATFORM_TOKEN = "test-platform-token" + ORG = "testorg" + DUMP_SQL = ( + "PRAGMA foreign_keys=OFF;\n" + "BEGIN TRANSACTION;\n" + "CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT);\n" + "INSERT INTO notes VALUES(1,'hello');\n" + "COMMIT;\n" + ) + + def __init__(self): + self.failing_dumps = set() + self.databases = [ + {"Name": "fake-one", "Hostname": "fake-one.example.invalid"}, + {"Name": "fake-two", "Hostname": "fake-two.example.invalid"}, + ] + + +def make_turso_handler(fake: FakeTurso): + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): # silence + pass + + def _send(self, code, body, content_type="application/json"): + data = body.encode() if isinstance(body, str) else body + self.send_response(code) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): + parts = [p for p in self.path.split("/") if p] + if parts == ["v1", "organizations", FakeTurso.ORG, "databases"]: + if ( + self.headers.get("Authorization") + != f"Bearer {FakeTurso.PLATFORM_TOKEN}" + ): + return self._send(401, {"error": "bad platform token"}) + return self._send(200, json.dumps({"databases": fake.databases})) + if len(parts) == 2 and parts[1] == "dump": + name = parts[0] + if self.headers.get("Authorization") != f"Bearer fake-jwt-{name}": + return self._send(401, {"error": "bad db token"}) + if name in fake.failing_dumps: + return self._send(500, "dump exploded", "text/plain") + return self._send(200, FakeTurso.DUMP_SQL, "text/plain") + return self._send(404, {"error": "not found"}) + + def do_POST(self): + length = int(self.headers.get("Content-Length") or 0) + if length: + self.rfile.read(length) + parts = [p for p in self.path.split("/") if p] + if ( + len(parts) == 7 + and parts[:4] == ["v1", "organizations", FakeTurso.ORG, "databases"] + and parts[5:] == ["auth", "tokens"] + ): + if ( + self.headers.get("Authorization") + != f"Bearer {FakeTurso.PLATFORM_TOKEN}" + ): + return self._send(401, {"error": "bad platform token"}) + return self._send(200, json.dumps({"jwt": f"fake-jwt-{parts[4]}"})) + return self._send(404, {"error": "not found"}) + + return Handler + + +class TestTursoExportScript(unittest.TestCase): + """scripts/export-turso.sh against the fake Turso HTTP API and a stub + cold-store executable: databases are discovered, tokens minted, dumps + downloaded and rebuilt, and each export filed via put-backup.""" + + def setUp(self): + self.fake = FakeTurso() + self.server = ThreadingHTTPServer( + ("127.0.0.1", 0), make_turso_handler(self.fake) + ) + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + self.addCleanup(self.server.server_close) + self.addCleanup(self.server.shutdown) + self.base = f"http://127.0.0.1:{self.server.server_address[1]}" + self.tmp = Path(tempfile.mkdtemp(prefix="cold-store-turso-test-")) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.calls_log = self.tmp / "cold-store-calls.log" + self.captured = self.tmp / "captured" + self.captured.mkdir() + self.stub = self.tmp / "cold-store-stub" + self.stub.write_text( + "#!/usr/bin/env bash\n" + f'echo "$@" >>"{self.calls_log}"\n' + f'cp "$3" "{self.captured}/"\n' + ) + self.stub.chmod(0o755) + + def run_export(self, with_token=True): + script = Path(__file__).resolve().parent.parent / "scripts" / "export-turso.sh" + env = dict(os.environ) + env.pop("TURSO_PLATFORM_API_TOKEN", None) + if with_token: + env["TURSO_PLATFORM_API_TOKEN"] = FakeTurso.PLATFORM_TOKEN + env.update( + { + "TURSO_ORG": FakeTurso.ORG, + "TURSO_API_BASE": self.base, + "TURSO_DUMP_BASE": self.base, + "COLD_STORE_BIN": str(self.stub), + "NO_PROXY": "127.0.0.1,localhost", + "no_proxy": "127.0.0.1,localhost", + } + ) + return subprocess.run( + ["bash", str(script)], + env=env, + capture_output=True, + text=True, + timeout=120, + check=False, + ) + + def test_files_every_database(self): + proc = self.run_export() + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn("turso export: all 2 database(s) filed", proc.stdout) + calls = self.calls_log.read_text().splitlines() + self.assertEqual(len(calls), 2) + for name in ("fake-one", "fake-two"): + self.assertTrue( + any( + c.startswith("put-backup turso ") and f"{name}.db.gz" in c + for c in calls + ), + calls, + ) + raw = gzip.decompress((self.captured / f"{name}.db.gz").read_bytes()) + check = self.tmp / f"check-{name}.db" + check.write_bytes(raw) + con = sqlite3.connect(str(check)) + try: + self.assertEqual( + con.execute("PRAGMA integrity_check").fetchone()[0], "ok" + ) + self.assertEqual( + con.execute("SELECT body FROM notes WHERE id=1").fetchone()[0], + "hello", + ) + finally: + con.close() + # No token material (platform or per-database) is ever printed. + self.assertNotIn(FakeTurso.PLATFORM_TOKEN, proc.stdout + proc.stderr) + self.assertNotIn("fake-jwt", proc.stdout + proc.stderr) + + def test_missing_token_skips_cleanly(self): + proc = self.run_export(with_token=False) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn( + "turso export: skipped (TURSO_PLATFORM_API_TOKEN not set)", proc.stdout + ) + self.assertFalse(self.calls_log.exists()) + + def test_one_dump_failure_still_files_the_other(self): + self.fake.failing_dumps = {"fake-two"} + proc = self.run_export() + self.assertNotEqual(proc.returncode, 0) + self.assertIn("fake-two", proc.stderr) + self.assertTrue((self.captured / "fake-one.db.gz").is_file()) + self.assertFalse((self.captured / "fake-two.db.gz").exists()) + + class TestWorkerDecoder(unittest.TestCase): """Local proof for the rehydrator Worker: the exact decoder module the Worker bundles (worker/src/decoder.js, fzstd) decodes one member frame