vault_keychain.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. """OS-keychain storage for the local vault key (opt-in: ``vault.key_storage: keychain``).
  2. The vault key normally sits in ``vault.key`` next to the ciphertext. In keychain mode it lives in
  3. the OS credential store instead (macOS Keychain, Windows Credential Manager, Secret Service /
  4. KWallet on Linux, via the ``keyring`` package from the ``keychain`` extra), and the vault directory
  5. keeps only a non-secret pointer, ``vault.keyref``, naming the entry. A backup, a synced folder or
  6. a copied home directory then holds ciphertext without its key.
  7. This does not isolate the key from code running as the same OS user: any such process (including
  8. an in-process plugin) can ask the keychain for it, or simply call the vault API.
  9. """
  10. from __future__ import annotations
  11. import json
  12. import os
  13. import uuid
  14. from contextlib import suppress
  15. from pathlib import Path
  16. from typing import Optional
  17. SERVICE = "Hermes Agent vault key"
  18. # keyring backends that are not an OS credential store: ``fail``/``null`` are what keyring picks on
  19. # a headless Linux box with no Secret Service, and keyrings.alt's plaintext/encrypted-file keyrings
  20. # would only move the key into another file under the same home.
  21. _NOT_A_KEYCHAIN = ("keyring.backends.fail", "keyring.backends.null", "keyrings.alt")
  22. class KeychainUnavailable(Exception):
  23. """No OS keychain is reachable from this process (headless, no keyring extra, plaintext backend)."""
  24. def _is_os_keychain(backend) -> bool:
  25. children = getattr(backend, "backends", None)
  26. if children is not None: # keyring's ChainerBackend writes to its highest-priority child
  27. return bool(children) and _is_os_keychain(children[0])
  28. return not type(backend).__module__.startswith(_NOT_A_KEYCHAIN)
  29. def os_keyring():
  30. """The OS credential store keyring resolves to, or raise :class:`KeychainUnavailable`."""
  31. try:
  32. import keyring
  33. except ImportError as exc:
  34. raise KeychainUnavailable(
  35. "the keychain feature is not installed (`hermes pm install --extra keychain`)") from exc
  36. try:
  37. backend = keyring.get_keyring()
  38. except Exception as exc: # health: allow BLE001 -- backend discovery runs third-party entry points
  39. raise KeychainUnavailable(f"keyring could not pick a backend ({type(exc).__name__})") from exc
  40. if not _is_os_keychain(backend):
  41. raise KeychainUnavailable(
  42. f"no OS keychain is reachable from this session (keyring backend: {type(backend).__module__}.{type(backend).__name__})")
  43. return backend
  44. def backend_label() -> str:
  45. """Human name of the keychain this process would use, for ``hermes vault key``."""
  46. try:
  47. backend = os_keyring()
  48. except KeychainUnavailable as exc:
  49. return f"unavailable: {exc}"
  50. return str(getattr(backend, "name", "") or type(backend).__name__)
  51. def new_ref(vault_dir: Path) -> dict:
  52. """Keychain coordinates for a new entry. The account is random, never derived from the path: a
  53. renamed profile keeps its pointer, and a new profile reusing the old name must not land on (and
  54. overwrite) the renamed vault's entry. ``vault_dir`` records which directory owns the entry."""
  55. return {"storage": "keychain", "service": SERVICE, "account": f"vault-{uuid.uuid4().hex}",
  56. "vault_dir": str(Path(vault_dir).resolve())}
  57. def owns(ref: dict, vault_dir: Path) -> bool:
  58. """False for a pointer copied or moved from another directory (profile clone/rename): the entry
  59. it names may still be another vault's only key, so this vault must not overwrite or delete it."""
  60. return ref.get("vault_dir") == str(Path(vault_dir).resolve())
  61. def read_ref(path: Path) -> Optional[dict]:
  62. try:
  63. data = json.loads(path.read_text(encoding="utf-8-sig"))
  64. except FileNotFoundError:
  65. return None
  66. except (OSError, ValueError) as exc:
  67. from agent.vault_store import VaultError
  68. raise VaultError(f"{path.name} is unreadable ({type(exc).__name__}); see `hermes vault key`") from exc
  69. if not isinstance(data, dict) or data.get("storage") != "keychain" or not data.get("account"):
  70. from agent.vault_store import VaultError
  71. raise VaultError(f"{path.name} does not describe a keychain entry; see `hermes vault key`")
  72. return data
  73. def write_ref(path: Path, ref: dict) -> None:
  74. from utils import atomic_write_bytes
  75. atomic_write_bytes(path, json.dumps(ref, indent=2).encode("utf-8"), mode=0o600, fsync_dir=True)
  76. def save_new_ref(path: Path, ref: dict) -> None:
  77. """Save the pointer to an entry just created. If saving fails, delete the entry unless the pointer
  78. did land (a replace can succeed before a later step errors): every account is random, so an entry
  79. no pointer names is a key Hermes would never find or remove again."""
  80. try:
  81. write_ref(path, ref)
  82. except OSError:
  83. from agent.vault_store import VaultError
  84. with suppress(VaultError):
  85. if (read_ref(path) or {}).get("account") == ref["account"]:
  86. raise
  87. delete_key(ref)
  88. raise
  89. def load_key(ref: dict) -> Optional[bytes]:
  90. """The stored key, or None when the entry is gone. Raises KeychainUnavailable."""
  91. backend = os_keyring()
  92. try:
  93. value = backend.get_password(str(ref.get("service") or SERVICE), str(ref["account"]))
  94. except Exception as exc: # health: allow BLE001 -- a locked or dismissed keychain raises backend-specific types
  95. raise KeychainUnavailable(f"the OS keychain did not answer ({type(exc).__name__})") from exc
  96. return value.encode("ascii") if value else None
  97. def store_key(ref: dict, key: bytes) -> None:
  98. """Write the key and read it back: a store that accepts a write it cannot return is unusable."""
  99. backend = os_keyring()
  100. service, account = str(ref.get("service") or SERVICE), str(ref["account"])
  101. try:
  102. backend.set_password(service, account, key.decode("ascii"))
  103. readback = backend.get_password(service, account)
  104. except Exception as exc: # health: allow BLE001 -- every keyring backend raises its own types
  105. raise KeychainUnavailable(f"the OS keychain refused the key ({type(exc).__name__})") from exc
  106. if readback != key.decode("ascii"):
  107. raise KeychainUnavailable("the OS keychain did not return the key it was given")
  108. def delete_key(ref: dict) -> bool:
  109. """True once the entry is gone, including when an earlier, interrupted cleanup already removed it."""
  110. service, account = str(ref.get("service") or SERVICE), str(ref["account"])
  111. try:
  112. backend = os_keyring()
  113. with suppress(Exception): # a missing entry raises PasswordDeleteError; the read below decides
  114. backend.delete_password(service, account)
  115. return backend.get_password(service, account) is None
  116. except Exception: # health: allow BLE001 -- unreachable keychain: the caller keeps the pointer to retry
  117. return False
  118. def remove_file(path: Path) -> None:
  119. try:
  120. os.remove(path)
  121. except FileNotFoundError:
  122. pass