teaimforge 0.19.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
teaimforge/backup.py ADDED
@@ -0,0 +1,441 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Encrypted backups of the state folder, and verified restores.
3
+
4
+ A backup is a gzipped tar of the state folder (its git history included; the
5
+ lock and caches left out) streamed straight into ``age``, so no unencrypted copy
6
+ ever touches the disk. The archive ends with ``BACKUP.json``: the forge, the
7
+ time, the log's event count and last hash, and the SHA-256 of every file.
8
+
9
+ A restore decrypts into a private folder beside the target, checks every file
10
+ against the manifest and the log's hash chain against the recorded last hash,
11
+ and only then moves the folder into place. It never restores over an existing
12
+ state folder.
13
+
14
+ Both are operator-only: a backup holds every message and decision, and
15
+ ``--recipient`` chooses who can read it.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import contextlib
21
+ import hashlib
22
+ import io
23
+ import json
24
+ import os
25
+ import shutil
26
+ import subprocess # nosec B404
27
+ import tarfile
28
+ import tempfile
29
+ from collections.abc import Iterator, Mapping, Sequence
30
+ from dataclasses import dataclass
31
+ from datetime import UTC, datetime
32
+ from pathlib import Path, PurePosixPath
33
+ from typing import IO, Any
34
+
35
+ from .config import ensure_gitignored
36
+ from .domain import OPERATOR, Domain
37
+ from .errors import ExitCode, ForgeError
38
+ from .events import EventStore
39
+ from .identity import Identity
40
+ from .paths import CHUNK, Layout, sha256_of
41
+
42
+ MANIFEST = "BACKUP.json"
43
+ PREFIX = "state"
44
+ SUFFIX = ".tar.gz.age"
45
+ #: Not backed up: the lock, the index cache, and interrupted atomic writes.
46
+ SKIPPED = (".lock", ".index.sqlite")
47
+ _RECIPIENT_PREFIXES = ("age1", "ssh-ed25519 ", "ssh-rsa ")
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class BackupResult:
52
+ path: Path
53
+ events: int
54
+ files: int
55
+ recipients: int
56
+ chain_ok: bool
57
+
58
+ def as_dict(self) -> dict[str, Any]:
59
+ return {
60
+ "path": str(self.path),
61
+ "events": self.events,
62
+ "files": self.files,
63
+ "recipients": self.recipients,
64
+ "chain_ok": self.chain_ok,
65
+ }
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class RestoreResult:
70
+ state: Path
71
+ archive: Path
72
+ created: str
73
+ events: int
74
+ files: int
75
+
76
+ def as_dict(self) -> dict[str, Any]:
77
+ return {
78
+ "state": str(self.state),
79
+ "archive": str(self.archive),
80
+ "created": self.created,
81
+ "events": self.events,
82
+ "files": self.files,
83
+ }
84
+
85
+
86
+ def find_age() -> str:
87
+ """The ``age`` executable; NOT_FOUND with how to get it."""
88
+ age = shutil.which("age")
89
+ if age is None:
90
+ raise ForgeError(
91
+ ExitCode.NOT_FOUND,
92
+ "age_missing",
93
+ "backups are encrypted with age; install it (https://age-encryption.org) and retry",
94
+ )
95
+ return age
96
+
97
+
98
+ def check_recipient(recipient: str) -> str:
99
+ """USAGE unless ``recipient`` looks like an age or SSH public key."""
100
+ if not recipient.startswith(_RECIPIENT_PREFIXES) or "\n" in recipient:
101
+ raise ForgeError(
102
+ ExitCode.USAGE,
103
+ "recipient_invalid",
104
+ f"{recipient[:24]!r} is not an age public key (age1…) or an SSH public key",
105
+ )
106
+ return recipient
107
+
108
+
109
+ def _inside(path: Path, folder: Path) -> bool:
110
+ try:
111
+ path.resolve().relative_to(folder.resolve())
112
+ except ValueError:
113
+ return False
114
+ return True
115
+
116
+
117
+ def _require_operator(identity: Identity | None, what: str) -> Identity:
118
+ if identity is None or identity.role != OPERATOR:
119
+ raise ForgeError(ExitCode.REFUSED, "role_not_allowed", f"only the operator {what}")
120
+ return identity
121
+
122
+
123
+ class Backups:
124
+ def __init__(self, layout: Layout, domain: Domain, identity: Identity | None) -> None:
125
+ self.layout = layout
126
+ self.domain = domain
127
+ self.identity = identity
128
+ self.store = EventStore(layout, domain)
129
+
130
+ # ------------------------------------------------------------- backup
131
+
132
+ def files(self) -> Iterator[tuple[str, Path]]:
133
+ """``(path relative to the state folder, path)`` for each file backed up."""
134
+ for top, dirs, names in os.walk(self.layout.state, followlinks=False):
135
+ dirs.sort()
136
+ for name in [*dirs, *names]:
137
+ path = Path(top, name)
138
+ if path.is_symlink():
139
+ rel = path.relative_to(self.layout.state).as_posix()
140
+ raise ForgeError(
141
+ ExitCode.DATA,
142
+ "backup_link",
143
+ f"{self.domain.state_dir}/{rel} is a link; links are not backed up",
144
+ )
145
+ for name in sorted(names):
146
+ path = Path(top, name)
147
+ rel = path.relative_to(self.layout.state).as_posix()
148
+ if rel in SKIPPED or (name.startswith(".") and name.endswith(".tmp")):
149
+ continue
150
+ yield rel, path
151
+
152
+ def create(
153
+ self,
154
+ to: Path,
155
+ recipients: Sequence[str],
156
+ project: str,
157
+ now: datetime | None = None,
158
+ ) -> BackupResult:
159
+ """Write ``<to>/<project>-<UTC time>.tar.gz.age``; operator only."""
160
+ who = _require_operator(self.identity, "makes backups")
161
+ if not recipients:
162
+ raise ForgeError(
163
+ ExitCode.USAGE,
164
+ "no_recipient",
165
+ "name who can decrypt the backup: --recipient, or backup.recipients "
166
+ "in config.yaml (an age public key from age-keygen)",
167
+ )
168
+ keys = [check_recipient(r) for r in recipients]
169
+ to = to.expanduser()
170
+ if _inside(to, self.layout.root):
171
+ raise ForgeError(
172
+ ExitCode.USAGE,
173
+ "backup_inside_project",
174
+ f"{to} is inside the project; choose a folder outside {self.layout.root}",
175
+ )
176
+ if not to.is_dir():
177
+ raise ForgeError(ExitCode.NOT_FOUND, "backup_dir_missing", f"{to} does not exist")
178
+ age = find_age()
179
+ moment = (now or datetime.now(UTC)).astimezone(UTC)
180
+ target = to / f"{project}-{moment.strftime('%Y%m%dT%H%M%SZ')}{SUFFIX}"
181
+ if target.exists():
182
+ raise ForgeError(ExitCode.CONFLICT, "backup_exists", f"{target} already exists")
183
+ with self.store.transaction() as tx:
184
+ check = self.store.verify()
185
+ size, tip = self.store.tip()
186
+ fd, tmp = tempfile.mkstemp(dir=to, prefix=f".{target.name}.", suffix=".tmp")
187
+ try:
188
+ count = self._encrypt(age, keys, fd, moment=moment, events=check.events, tip=tip)
189
+ os.replace(tmp, target)
190
+ except BaseException:
191
+ Path(tmp).unlink(missing_ok=True)
192
+ raise
193
+ tx.append(
194
+ "backed_up",
195
+ actor=who.role,
196
+ session=who.session,
197
+ data={
198
+ "file": target.name,
199
+ "dir": str(to),
200
+ "events": check.events,
201
+ "tip": tip,
202
+ "bytes": size,
203
+ "recipients": len(keys),
204
+ "chain_ok": check.ok,
205
+ },
206
+ )
207
+ return BackupResult(target, check.events, count, len(keys), check.ok)
208
+
209
+ def _encrypt( # noqa: PLR0913 - the pieces of one archive
210
+ self,
211
+ age: str,
212
+ keys: Sequence[str],
213
+ fd: int,
214
+ *,
215
+ moment: datetime,
216
+ events: int,
217
+ tip: str,
218
+ ) -> int:
219
+ args = [age, "--encrypt"]
220
+ for key in keys:
221
+ args += ["--recipient", key]
222
+ with os.fdopen(fd, "wb") as out:
223
+ proc = subprocess.Popen( # noqa: S603 - fixed arguments, age from PATH
224
+ args, stdin=subprocess.PIPE, stdout=out, stderr=subprocess.PIPE
225
+ ) # nosec B603
226
+ if proc.stdin is None: # pragma: no cover - stdin=PIPE above
227
+ raise ForgeError(ExitCode.INTERNAL, "age_failed", "no pipe to age")
228
+ hashes: dict[str, str] = {}
229
+ try:
230
+ self._write_tar(proc.stdin, hashes, moment=moment, events=events, tip=tip)
231
+ except BrokenPipeError:
232
+ pass # age exited early; its status and message say why
233
+ finally:
234
+ with contextlib.suppress(BrokenPipeError):
235
+ proc.stdin.close()
236
+ stderr = proc.stderr.read() if proc.stderr else b""
237
+ code = proc.wait()
238
+ out.flush()
239
+ os.fsync(out.fileno())
240
+ if code != 0:
241
+ raise ForgeError(ExitCode.USAGE, "age_failed", _first_line(stderr))
242
+ return len(hashes)
243
+
244
+ def _write_tar(
245
+ self,
246
+ sink: IO[bytes],
247
+ hashes: dict[str, str],
248
+ moment: datetime,
249
+ events: int,
250
+ tip: str,
251
+ ) -> None:
252
+ with tarfile.open(fileobj=sink, mode="w|gz") as tar:
253
+ for rel, path in self.files():
254
+ hashes[rel] = _add_file(tar, f"{PREFIX}/{rel}", path)
255
+ manifest = {
256
+ "forge": self.domain.name,
257
+ "created": moment.strftime("%Y-%m-%dT%H:%M:%SZ"),
258
+ "events": events,
259
+ "tip": tip,
260
+ "files": hashes,
261
+ }
262
+ _add(tar, MANIFEST, json.dumps(manifest, indent=1, sort_keys=True).encode())
263
+
264
+ # ------------------------------------------------------------ restore
265
+
266
+ def restore(self, archive: Path, identity_file: Path) -> RestoreResult:
267
+ """Decrypt ``archive`` into this layout's state folder, which must not exist."""
268
+ who = _require_operator(self.identity, "restores backups")
269
+ state = self.layout.state
270
+ if state.exists():
271
+ raise ForgeError(
272
+ ExitCode.REFUSED,
273
+ "already_initialized",
274
+ f"{state} exists; move it aside before restoring over it",
275
+ )
276
+ archive, identity_file = archive.expanduser(), identity_file.expanduser()
277
+ for path, what in ((archive, "archive"), (identity_file, "identity")):
278
+ if not path.is_file():
279
+ raise ForgeError(ExitCode.NOT_FOUND, f"{what}_missing", f"{path} does not exist")
280
+ age = find_age()
281
+ work = Path(tempfile.mkdtemp(dir=self.layout.root, prefix=f".{state.name}.restore-"))
282
+ try:
283
+ manifest = self._decrypt(age, archive, identity_file, work)
284
+ staged = Layout(root=self.layout.root, state=work / PREFIX)
285
+ self._check(manifest, staged)
286
+ os.rename(staged.state, state)
287
+ finally:
288
+ shutil.rmtree(work, ignore_errors=True)
289
+ ensure_gitignored(self.layout.root, self.domain)
290
+ self.store.append(
291
+ "restored",
292
+ actor=who.role,
293
+ session=who.session,
294
+ data={
295
+ "archive": archive.name,
296
+ "created": manifest["created"],
297
+ "events": manifest["events"],
298
+ "tip": manifest["tip"],
299
+ },
300
+ )
301
+ return RestoreResult(
302
+ state,
303
+ archive,
304
+ str(manifest["created"]),
305
+ int(manifest["events"]),
306
+ len(manifest["files"]),
307
+ )
308
+
309
+ def _decrypt(self, age: str, archive: Path, identity: Path, work: Path) -> dict[str, Any]:
310
+ args = [age, "--decrypt", "--identity", str(identity), str(archive)]
311
+ proc = subprocess.Popen( # noqa: S603 - fixed arguments, age from PATH
312
+ args, stdout=subprocess.PIPE, stderr=subprocess.PIPE
313
+ ) # nosec B603
314
+ if proc.stdout is None: # pragma: no cover - stdout=PIPE above
315
+ raise ForgeError(ExitCode.INTERNAL, "age_failed", "no pipe from age")
316
+ manifest: dict[str, Any] | None = None
317
+ try:
318
+ with tarfile.open(fileobj=proc.stdout, mode="r|gz") as tar:
319
+ for member in tar:
320
+ if member.name == MANIFEST and member.isfile():
321
+ manifest = json.loads(_read(tar, member))
322
+ continue
323
+ _extract(tar, member, work)
324
+ except (tarfile.TarError, EOFError, OSError, ValueError) as exc:
325
+ proc.kill()
326
+ stderr = proc.stderr.read() if proc.stderr else b""
327
+ proc.wait()
328
+ detail = _first_line(stderr) if stderr.strip() else str(exc)
329
+ raise ForgeError(ExitCode.DATA, "backup_unreadable", f"{archive}: {detail}") from exc
330
+ finally:
331
+ proc.stdout.close()
332
+ stderr = proc.stderr.read() if proc.stderr else b""
333
+ if proc.wait() != 0:
334
+ raise ForgeError(
335
+ ExitCode.DATA, "backup_unreadable", f"{archive}: {_first_line(stderr)}"
336
+ )
337
+ if manifest is None:
338
+ raise ForgeError(ExitCode.DATA, "backup_invalid", f"{archive} has no {MANIFEST}")
339
+ return manifest
340
+
341
+ def _check(self, manifest: Mapping[str, Any], staged: Layout) -> None:
342
+ def bad(detail: str) -> ForgeError:
343
+ return ForgeError(ExitCode.DATA, "backup_invalid", detail)
344
+
345
+ if manifest.get("forge") != self.domain.name:
346
+ raise bad(
347
+ f"the backup is of a {manifest.get('forge')!r} project, not {self.domain.name}"
348
+ )
349
+ files = manifest.get("files")
350
+ if not isinstance(files, dict):
351
+ raise bad(f"{MANIFEST} has no file list")
352
+ found = (
353
+ {
354
+ p.relative_to(staged.state).as_posix(): p
355
+ for p in staged.state.rglob("*")
356
+ if p.is_file()
357
+ }
358
+ if staged.state.is_dir()
359
+ else {}
360
+ )
361
+ if set(found) != set(files):
362
+ extra = sorted(set(found) ^ set(files))
363
+ raise bad(f"files do not match {MANIFEST}: {', '.join(extra[:5])}")
364
+ for rel, path in found.items():
365
+ if sha256_of(path) != files[rel]:
366
+ raise bad(f"{rel} does not match its recorded hash")
367
+ result = EventStore(staged, self.domain).verify()
368
+ if not result.ok:
369
+ raise bad(f"event log line {result.line}: {result.reason}")
370
+ if (result.events, EventStore(staged, self.domain).tip()[1]) != (
371
+ manifest.get("events"),
372
+ manifest.get("tip"),
373
+ ):
374
+ raise bad("the event log does not end where the backup recorded")
375
+
376
+
377
+ def _add(tar: tarfile.TarFile, name: str, data: bytes) -> None:
378
+ info = tarfile.TarInfo(name)
379
+ info.size = len(data)
380
+ info.mode = 0o600
381
+ tar.addfile(info, io.BytesIO(data))
382
+
383
+
384
+ class _Hashing(io.RawIOBase):
385
+ """A file read through once, hashing as it goes."""
386
+
387
+ def __init__(self, handle: IO[bytes]) -> None:
388
+ self.handle = handle
389
+ self.digest = hashlib.sha256()
390
+
391
+ def readable(self) -> bool:
392
+ return True
393
+
394
+ def read(self, size: int = -1) -> bytes:
395
+ data = self.handle.read(size)
396
+ self.digest.update(data)
397
+ return data
398
+
399
+
400
+ def _add_file(tar: tarfile.TarFile, name: str, path: Path) -> str:
401
+ """Stream one file into the archive in chunks; return its SHA-256."""
402
+ with path.open("rb") as handle:
403
+ info = tarfile.TarInfo(name)
404
+ info.size = os.fstat(handle.fileno()).st_size
405
+ info.mode = 0o600
406
+ reader = _Hashing(handle)
407
+ tar.addfile(info, reader)
408
+ return reader.digest.hexdigest()
409
+
410
+
411
+ def _read(tar: tarfile.TarFile, member: tarfile.TarInfo) -> bytes:
412
+ handle: IO[bytes] | None = tar.extractfile(member)
413
+ if handle is None: # pragma: no cover - isfile() was checked
414
+ raise ValueError(f"{member.name} has no data")
415
+ return handle.read()
416
+
417
+
418
+ def _extract(tar: tarfile.TarFile, member: tarfile.TarInfo, work: Path) -> None:
419
+ """Write one regular file under ``work/state``; anything else is refused."""
420
+ name = PurePosixPath(member.name)
421
+ if (
422
+ not member.isfile()
423
+ or name.is_absolute()
424
+ or ".." in name.parts
425
+ or name.parts[:1] != (PREFIX,)
426
+ or len(name.parts) < 2
427
+ ):
428
+ raise ValueError(f"unexpected entry {member.name!r}")
429
+ target = work.joinpath(*name.parts)
430
+ target.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
431
+ handle: IO[bytes] | None = tar.extractfile(member)
432
+ if handle is None: # pragma: no cover - isfile() was checked
433
+ raise ValueError(f"{member.name} has no data")
434
+ fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
435
+ with os.fdopen(fd, "wb") as out:
436
+ shutil.copyfileobj(handle, out, CHUNK)
437
+
438
+
439
+ def _first_line(stderr: bytes) -> str:
440
+ text = stderr.decode("utf-8", "replace").strip()
441
+ return text.splitlines()[0] if text else "age failed"