crypto.py 3.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. """At-rest encryption for sensitive files via the `age` binary (optional).
  2. Engaged ONLY when config `encryption: age` AND an age identity key exists AND the
  3. `age`/`age-keygen` binaries are available. When engaged, JSON docs under
  4. `subjects/` (dossier, ledger) are written as `<file>.age` ciphertext; the audit
  5. log (field NAMES + states only, no raw PII values), `config.json`, and the broker
  6. cache stay plaintext so the engine can read them.
  7. Threat model (be honest): this protects against casual disk inspection, accidental
  8. `git add`/commits, screen-shares, and backup/cloud-sync leakage. The identity key
  9. defaults to living beside the data at `$PDD_DATA_DIR/age-identity.txt` (0600); set
  10. `PDD_AGE_IDENTITY` to a separate volume/token for true key separation. It does NOT
  11. protect against an attacker who can already read your whole HERMES_HOME (they get
  12. key + data together).
  13. """
  14. from __future__ import annotations
  15. import json
  16. import subprocess
  17. from pathlib import Path
  18. from shutil import which
  19. import paths
  20. def age_available() -> bool:
  21. return which("age") is not None and which("age-keygen") is not None
  22. def encryption_setting() -> str:
  23. """Read `encryption` straight from config.json (no config/storage import => no cycle)."""
  24. cfg = paths.config_path()
  25. if not cfg.exists():
  26. return "none"
  27. try:
  28. return (json.loads(cfg.read_text(encoding="utf-8")) or {}).get("encryption", "none")
  29. except (ValueError, OSError):
  30. return "none"
  31. def identity_path() -> Path:
  32. return paths.age_identity_path()
  33. def ensure_identity() -> Path:
  34. """Generate an age identity (X25519 keypair) if missing; return its path."""
  35. if not age_available():
  36. raise RuntimeError("`age`/`age-keygen` not found; cannot enable encryption")
  37. p = identity_path()
  38. if not p.exists():
  39. p.parent.mkdir(parents=True, exist_ok=True)
  40. try:
  41. p.parent.chmod(0o700)
  42. except OSError:
  43. pass
  44. # Generate beside the target and move it into place, so a timed-out or failed run
  45. # leaves no partial identity that the exists() check above would accept next time.
  46. partial = p.with_name(f"{p.name}.partial")
  47. partial.unlink(missing_ok=True)
  48. try:
  49. subprocess.run(["age-keygen", "-o", str(partial)], check=True, capture_output=True,
  50. stdin=subprocess.DEVNULL, timeout=30)
  51. partial.replace(p)
  52. finally:
  53. partial.unlink(missing_ok=True)
  54. try:
  55. p.chmod(0o600)
  56. except OSError:
  57. pass
  58. return p
  59. def recipient() -> str:
  60. """The age public key (recipient) for the identity, parsed from its header."""
  61. p = ensure_identity()
  62. for line in p.read_text(encoding="utf-8").splitlines():
  63. s = line.strip()
  64. if s.lower().startswith("# public key:"):
  65. return s.split(":", 1)[1].strip()
  66. if s.startswith("age1"):
  67. return s
  68. raise RuntimeError(f"no public key found in {p}")
  69. def is_engaged() -> bool:
  70. """True only when encryption is actually active (configured + available + key present)."""
  71. return encryption_setting() == "age" and age_available() and identity_path().exists()
  72. def encrypt(data: bytes) -> bytes:
  73. out = subprocess.run(["age", "-r", recipient()], input=data, capture_output=True, check=True)
  74. return out.stdout
  75. def decrypt(data: bytes) -> bytes:
  76. out = subprocess.run(["age", "-d", "-i", str(identity_path())], input=data, capture_output=True, check=True)
  77. return out.stdout