1
+#!/usr/bin/env python3
2
+"""Finora offline-custody PostgreSQL backups. No plaintext archive is written to disk.
3
+
4
+Requirements: Python 3.10+, PostgreSQL client pg_dump/pg_restore matching the
5
+server major version, and age (https://age-encryption.org/).
6
+The backup recipient is public. The age identity/private key never leaves the
7
+owner's trusted restore machine. No production restore command exists.
8
+"""
9
+from __future__ import annotations
10
+
11
+import argparse
12
+import getpass
13
+import hashlib
14
+import json
15
+import os
16
+from pathlib import Path
17
+import re
18
+import secrets
19
+import shutil
20
+import subprocess
21
+import sys
22
+import threading
23
+from datetime import datetime, timezone
24
+
25
+VERSION = 1
26
+DEFAULT_DB = "postgres"
27
+TEST_DB_PREFIX = "finora_restore_test_"
28
+LOCAL_HOSTS = {"localhost", "127.0.0.1", "::1"}
29
+
30
+
31
+class BackupError(RuntimeError):
32
+ pass
33
+
34
+
35
+def safe_executable(value: str) -> str:
36
+ found = shutil.which(value)
37
+ if not found:
38
+ raise BackupError(f"Required executable not found: {value}")
39
+ return found
40
+
41
+
42
+def validate_port(value: int) -> int:
43
+ if not 1 <= value <= 65535:
44
+ raise BackupError("Database port must be between 1 and 65535")
45
+ return value
46
+
47
+
48
+def ensure_outside_checkout(destination: Path) -> Path:
49
+ dest = destination.expanduser().resolve()
50
+ checkout = Path(__file__).resolve().parent.parent
51
+ if dest == checkout or checkout in dest.parents:
52
+ raise BackupError("Refusing backup storage inside source-code checkout")
53
+ dest.mkdir(parents=True, exist_ok=True)
54
+ if not dest.is_dir():
55
+ raise BackupError("Backup destination is not a directory")
56
+ return dest
57
+
58
+
59
+def verify_public_recipient(recipient: str) -> str:
60
+ if not re.fullmatch(r"age1[023456789acdefghjklmnpqrstuvwxyz]{40,120}", recipient):
61
+ raise BackupError("Expected an age X25519 public recipient beginning with age1")
62
+ return recipient
63
+
64
+
65
+def database_environment(args: argparse.Namespace) -> dict[str, str]:
66
+ password = os.environ.get("FINORA_BACKUP_DB_PASSWORD")
67
+ if not password:
68
+ if not sys.stdin.isatty():
69
+ raise BackupError("No database password: set FINORA_BACKUP_DB_PASSWORD securely")
70
+ password = getpass.getpass("Production database password (not saved): ")
71
+ if not password:
72
+ raise BackupError("Empty database password is not allowed")
73
+ if not args.host or not args.user or not args.database:
74
+ raise BackupError("Database host, user, and database are required")
75
+ env = os.environ.copy()
76
+ env.update({
77
+ "PGHOST": args.host,
78
+ "PGPORT": str(validate_port(args.port)),
79
+ "PGUSER": args.user,
80
+ "PGDATABASE": args.database,
81
+ "PGPASSWORD": password,
82
+ "PGSSLMODE": "require",
83
+ "PGCONNECT_TIMEOUT": "15",
84
+ "PGOPTIONS": "-c default_transaction_read_only=on",
85
+ })
86
+ return env
87
+
88
+
89
+def checksum(path: Path) -> str:
90
+ digest = hashlib.sha256()
91
+ with path.open("rb") as fh:
92
+ while chunk := fh.read(1024 * 1024):
93
+ digest.update(chunk)
94
+ return digest.hexdigest()
95
+
96
+
97
+def _read_stderr(proc: subprocess.Popen, target: list[bytes]) -> None:
98
+ try:
99
+ target.append(proc.stderr.read() if proc.stderr else b"")
100
+ except OSError:
101
+ target.append(b"")
102
+
103
+
104
+def backup(args: argparse.Namespace) -> Path:
105
+ recipient = verify_public_recipient(args.recipient)
106
+ dest = ensure_outside_checkout(Path(args.output_dir))
107
+ pg_dump = safe_executable(args.pg_dump)
108
+ age = safe_executable(args.age)
109
+ env = database_environment(args)
110
+ timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
111
+ name = f"finora-postgres-{timestamp}-{secrets.token_hex(4)}.dump.age"
112
+ final = dest / name
113
+ partial = dest / (name + ".partial")
114
+ manifest = dest / (name + ".json")
115
+ manifest_temp = dest / (name + ".json.partial")
116
+ dump_proc = None
117
+ age_proc = None
118
+ dump_errors: list[bytes] = []
119
+ try:
120
+ # pg_dump's custom format is sent directly to age, never to a plaintext file.
121
+ dump_proc = subprocess.Popen(
122
+ [pg_dump, "--format=custom", "--no-owner", "--no-acl", "--file=-", "--dbname=" + args.database],
123
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
124
+ )
125
+ stderr_thread = threading.Thread(target=_read_stderr, args=(dump_proc, dump_errors), daemon=True)
126
+ stderr_thread.start()
127
+ age_proc = subprocess.Popen(
128
+ [age, "--recipient", recipient, "--output", str(partial)],
129
+ stdin=dump_proc.stdout, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
130
+ )
131
+ assert dump_proc.stdout is not None
132
+ dump_proc.stdout.close() # allow pg_dump to see a broken pipe if encryption exits
133
+ _, age_stderr = age_proc.communicate()
134
+ dump_code = dump_proc.wait()
135
+ stderr_thread.join(timeout=5)
136
+ if dump_code != 0:
137
+ raise BackupError(f"pg_dump failed (exit {dump_code}); encrypted partial backup discarded")
138
+ if age_proc.returncode != 0:
139
+ raise BackupError(f"age encryption failed (exit {age_proc.returncode}); partial backup discarded")
140
+ if not partial.is_file() or partial.stat().st_size == 0:
141
+ raise BackupError("Encryption produced no archive")
142
+ os.replace(partial, final)
143
+ details = {
144
+ "format": "finora-encrypted-pg-dump-v1",
145
+ "created_utc": datetime.now(timezone.utc).isoformat(),
146
+ "archive": name,
147
+ "ciphertext_sha256": checksum(final),
148
+ "ciphertext_bytes": final.stat().st_size,
149
+ "compression": "pg_dump custom",
150
+ "encryption": "age X25519",
151
+ "scope": "PostgreSQL database; NOT Supabase Storage file bodies, Edge Function secrets, or off-site copies",
152
+ }
153
+ manifest_temp.write_text(json.dumps(details, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
154
+ os.replace(manifest_temp, manifest)
155
+ print(f"Encrypted backup created: {final}")
156
+ print(f"Integrity manifest: {manifest}")
157
+ print("Copy BOTH files to separate offline storage. Perform a sandbox restore before trusting the backup.")
158
+ return final
159
+ except BaseException:
160
+ for path in (partial, final, manifest_temp, manifest):
161
+ try:
162
+ path.unlink(missing_ok=True)
163
+ except OSError:
164
+ pass
165
+ raise
166
+ finally:
167
+ if age_proc and age_proc.poll() is None:
168
+ age_proc.kill()
169
+ age_proc.wait()
170
+ if dump_proc and dump_proc.poll() is None:
171
+ dump_proc.kill()
172
+ dump_proc.wait()
173
+ # Do not retain production password in process environment after subprocesses finish.
174
+ env.pop("PGPASSWORD", None)
175
+
176
+
177
+def check_integrity(path: Path) -> dict:
178
+ if not path.is_file() or not path.name.endswith(".dump.age"):
179
+ raise BackupError("Expected an encrypted .dump.age archive")
180
+ meta_path = path.with_name(path.name + ".json")
181
+ if not meta_path.is_file():
182
+ raise BackupError("Companion integrity manifest is missing")
183
+ details = json.loads(meta_path.read_text(encoding="utf-8"))
184
+ if details.get("format") != "finora-encrypted-pg-dump-v1" or details.get("archive") != path.name:
185
+ raise BackupError("Integrity manifest does not match this archive")
186
+ if details.get("ciphertext_bytes") != path.stat().st_size:
187
+ raise BackupError("Encrypted backup size mismatch")
188
+ if details.get("ciphertext_sha256") != checksum(path):
189
+ raise BackupError("Encrypted backup SHA-256 mismatch")
190
+ return details
191
+
192
+
193
+def decrypt_into_process(path: Path, identity: Path, age: str, command: list[str], env: dict | None = None) -> None:
194
+ # Never generate decrypted plaintext on disk, even for verification/restore tests.
195
+ dec = subprocess.Popen([age, "--decrypt", "--identity", str(identity), str(path)],
196
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)
197
+ err_parts: list[bytes] = []
198
+ thread = threading.Thread(target=_read_stderr, args=(dec, err_parts), daemon=True)
199
+ thread.start()
200
+ consumer = None
201
+ try:
202
+ consumer = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,
203
+ stderr=subprocess.PIPE, env=env)
204
+ assert dec.stdout is not None and consumer.stdin is not None
205
+ consumer_errors: list[bytes] = []
206
+ consumer_err_thread = threading.Thread(
207
+ target=_read_stderr, args=(consumer, consumer_errors), daemon=True
208
+ )
209
+ consumer_err_thread.start()
210
+ broken = False
211
+ while chunk := dec.stdout.read(256 * 1024):
212
+ if not broken:
213
+ try:
214
+ consumer.stdin.write(chunk)
215
+ consumer.stdin.flush()
216
+ except BrokenPipeError:
217
+ broken = True
218
+ try:
219
+ consumer.stdin.close()
220
+ except BrokenPipeError:
221
+ pass
222
+ consumer_rc = consumer.wait()
223
+ consumer_err_thread.join(timeout=5)
224
+ dec_rc = dec.wait()
225
+ thread.join(timeout=5)
226
+ if dec_rc != 0:
227
+ raise BackupError("age decryption failed; backup is not usable with this identity")
228
+ if consumer_rc != 0:
229
+ raise BackupError(f"PostgreSQL archive reader/restore failed (exit {consumer_rc})")
230
+ finally:
231
+ if consumer and consumer.poll() is None:
232
+ consumer.kill()
233
+ consumer.wait()
234
+ if dec.poll() is None:
235
+ dec.kill()
236
+ dec.wait()
237
+
238
+
239
+def verify(args: argparse.Namespace) -> None:
240
+ archive = Path(args.backup).expanduser().resolve()
241
+ identity = Path(args.identity).expanduser().resolve()
242
+ if not identity.is_file():
243
+ raise BackupError("Age private identity file not found; never upload it to GitHub")
244
+ check_integrity(archive)
245
+ decrypt_into_process(archive, identity, safe_executable(args.age),
246
+ [safe_executable(args.pg_restore), "--list", "--format=custom"])
247
+ print("Integrity hash, age decryption and PostgreSQL archive catalog: PASS")
248
+ print("This is NOT a successful restore test. Restore to an isolated empty database next.")
249
+
250
+
251
+def restore_test(args: argparse.Namespace) -> None:
252
+ if args.test_host not in LOCAL_HOSTS:
253
+ raise BackupError("Restore-test only permits localhost; remote/production targets are prohibited")
254
+ if not re.fullmatch(r"finora_restore_test_[a-z0-9_]+", args.test_database):
255
+ raise BackupError("Restore-test database must start with finora_restore_test_ and be disposable")
256
+ archive = Path(args.backup).expanduser().resolve()
257
+ identity = Path(args.identity).expanduser().resolve()
258
+ if not identity.is_file():
259
+ raise BackupError("Age private identity file not found")
260
+ check_integrity(archive)
261
+ if args.test_port < 1 or args.test_port > 65535:
262
+ raise BackupError("Invalid local PostgreSQL test port")
263
+ if not args.test_user:
264
+ raise BackupError("Test database user required")
265
+ password = os.environ.get("FINORA_RESTORE_TEST_DB_PASSWORD")
266
+ if password is None and sys.stdin.isatty():
267
+ password = getpass.getpass("LOCAL disposable database password (empty for trust auth): ")
268
+ env = os.environ.copy()
269
+ env.update({"PGHOST": args.test_host, "PGPORT": str(args.test_port),
270
+ "PGUSER": args.test_user, "PGDATABASE": args.test_database,
271
+ "PGSSLMODE": "prefer", "PGCONNECT_TIMEOUT": "5"})
272
+ if password:
273
+ env["PGPASSWORD"] = password
274
+ else:
275
+ env.pop("PGPASSWORD", None)
276
+ # Production cannot be a target; no --clean or --create. Database must already
277
+ # exist and be EMPTY and disposable; run with a dedicated local-only account.
278
+ command = [safe_executable(args.pg_restore), "--exit-on-error", "--no-owner", "--no-acl",
279
+ "--format=custom", "--dbname=" + args.test_database]
280
+ decrypt_into_process(archive, identity, safe_executable(args.age), command, env=env)
281
+ env.pop("PGPASSWORD", None)
282
+ print("Isolated localhost PostgreSQL restore: PASS")
283
+ print("Validate application-level rows, roles and RLS separately before marking operational recovery ready.")
284
+
285
+
286
+def main(argv: list[str] | None = None) -> int:
287
+ p = argparse.ArgumentParser(description=__doc__)
288
+ sub = p.add_subparsers(dest="command", required=True)
289
+ b = sub.add_parser("backup", help="Read PostgreSQL and encrypt directly to external/local storage")
290
+ b.add_argument("--host", required=True, help="Production database host, not Supabase REST API URL")
291
+ b.add_argument("--port", type=int, default=5432)
292
+ b.add_argument("--user", required=True)
293
+ b.add_argument("--database", default=DEFAULT_DB)
294
+ b.add_argument("--output-dir", required=True)
295
+ b.add_argument("--recipient", required=True, help="PUBLIC age1 recipient; never the private key")
296
+ b.add_argument("--pg-dump", default="pg_dump")
297
+ b.add_argument("--age", default="age")
298
+ b.set_defaults(func=backup)
299
+ v = sub.add_parser("verify", help="Verify ciphertext, decrypt in memory and inspect pg_restore archive TOC")
300
+ v.add_argument("--backup", required=True)
301
+ v.add_argument("--identity", required=True, help="Private age identity file stored outside repository")
302
+ v.add_argument("--age", default="age")
303
+ v.add_argument("--pg-restore", default="pg_restore")
304
+ v.set_defaults(func=verify)
305
+ t = sub.add_parser("restore-test", help="Restore ONLY to an existing empty localhost disposable database")
306
+ t.add_argument("--backup", required=True)
307
+ t.add_argument("--identity", required=True)
308
+ t.add_argument("--test-host", default="127.0.0.1")
309
+ t.add_argument("--test-port", type=int, default=5432)
310
+ t.add_argument("--test-user", required=True)
311
+ t.add_argument("--test-database", required=True)
312
+ t.add_argument("--age", default="age")
313
+ t.add_argument("--pg-restore", default="pg_restore")
314
+ t.set_defaults(func=restore_test)
315
+ args = p.parse_args(argv)
316
+ try:
317
+ args.func(args)
318
+ return 0
319
+ except (BackupError, OSError, ValueError, json.JSONDecodeError) as exc:
320
+ print(f"BACKUP ERROR: {exc}", file=sys.stderr)
321
+ return 1
322
+
323
+
324
+if __name__ == "__main__":
325
+ sys.exit(main())