unlock.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. """Per-process unlock state for external password managers.
  2. An unlock is a session token minted by the manager's CLI from the master
  3. password (``op signin --raw`` / ``bw unlock --raw``). The token lives in
  4. process memory only, keyed by (profile home, backend), and is dropped at an
  5. idle TTL (by a timer, not at the next call) or an explicit lock. It is held
  6. inside a closure, so no module attribute exposes it to a plain import or a
  7. dump of module state, and it reaches only the manager CLI call that uses it
  8. (as that child's ``BW_SESSION`` / ``OP_SESSION*``), never ``os.environ``.
  9. That stops casual and accidental access, not code running in this process,
  10. which can always read its memory: the boundary for third-party plugins is
  11. ``plugins.isolation: host``. The master password itself is consumed by the
  12. CLI call and dropped; nothing is written to disk or env.
  13. The surface owns the prompt: ``set_unlock_prompt_callback`` is installed by
  14. the CLI panel / TUI gateway bridge for the current thread, exactly like the
  15. sudo-password callback. Headless contexts (cron, webhook, api_server,
  16. single-query) install none and the vault stays locked — the same posture
  17. approvals take where nobody can answer.
  18. """
  19. from __future__ import annotations
  20. import threading
  21. import time
  22. from dataclasses import dataclass, field
  23. from typing import Callable, Dict, NamedTuple, Optional
  24. _IDLE_TTL_S = 30 * 60
  25. _callback_tls = threading.local()
  26. UnlockPrompt = Callable[[str, str], str] # (backend_name, display_name) -> master password ("" = cancelled)
  27. # (origin, site label) -> {"identifier": str, "password": str} or None when the user declines. The
  28. # surface owns the masked fields; the tool stores the answer in the local vault and fills at once.
  29. SaveLoginPrompt = Callable[[str, str], Optional[dict[str, str]]]
  30. def set_unlock_prompt_callback(cb: Optional[UnlockPrompt]) -> None:
  31. """Register the current surface's masked master-password prompt (per-thread slot)."""
  32. _callback_tls.prompt = cb
  33. def get_unlock_prompt_callback() -> Optional[UnlockPrompt]:
  34. return getattr(_callback_tls, "prompt", None)
  35. # (site, hint) -> the one-time code the user reads off their phone/email/app, "" when declined.
  36. CodePrompt = Callable[[str, str], str]
  37. def set_code_prompt_callback(cb: Optional[CodePrompt]) -> None:
  38. """Register the surface's "enter the code {site} sent you" prompt, per thread."""
  39. _callback_tls.code = cb
  40. def get_code_prompt_callback() -> Optional[CodePrompt]:
  41. return getattr(_callback_tls, "code", None)
  42. def set_save_login_prompt_callback(cb: Optional[SaveLoginPrompt]) -> None:
  43. """Register the surface's "save this login" prompt (identifier + masked password), per thread."""
  44. _callback_tls.save_login = cb
  45. def get_save_login_prompt_callback() -> Optional[SaveLoginPrompt]:
  46. return getattr(_callback_tls, "save_login", None)
  47. def _key(backend: str) -> tuple[str, str]:
  48. # Tokens are profile-scoped: a Desktop gateway hosts several profiles in one process and
  49. # profile B must never reuse (or lock) profile A's manager session.
  50. from hermes_constants import get_hermes_home
  51. return (str(get_hermes_home()), backend)
  52. _current_session_tls = threading.local()
  53. def set_current_session_id(session_id: Optional[str]) -> None:
  54. """Gateway surfaces bind the session running on this thread so an unlock records its owner."""
  55. _current_session_tls.sid = session_id
  56. def get_current_session_id() -> Optional[str]:
  57. """The session bound on this thread (``tools.thread_context`` carries it to tool workers)."""
  58. return getattr(_current_session_tls, "sid", None)
  59. _Key = tuple[str, str] # (profile home, backend)
  60. @dataclass(slots=True)
  61. class _Token:
  62. value: str = field(repr=False)
  63. last_used: float
  64. class _TokenOps(NamedTuple):
  65. live: Callable[[_Key, bool], Optional[str]]
  66. begin: Callable[[_Key], int]
  67. commit: Callable[[_Key, str, Optional[int], Optional[str]], bool]
  68. lock_profile: Callable[[str, Optional[str]], None]
  69. release: Callable[[str], None]
  70. lock_everything: Callable[[], None]
  71. def _token_store() -> _TokenOps:
  72. """The token state, reachable only through the closures returned here.
  73. The lock generation per key is bumped by every lock, and an unlock that started before the bump
  74. must not commit its token afterwards (a slow `bw unlock` child would otherwise silently undo an
  75. acknowledged Lock). Sibling sessions in a profile never release each other's tokens.
  76. ``owners`` (which gateway session unlocked a key) is revocation bookkeeping and outlives the token:
  77. the TTL drops only the secret, so a session ending after its token expired still bumps the
  78. generation and fences a replacement unlock that is in flight.
  79. """
  80. guard = threading.Lock()
  81. tokens: dict[_Key, _Token] = {}
  82. owners: dict[_Key, Optional[str]] = {}
  83. generations: dict[_Key, int] = {}
  84. timer: Optional[threading.Timer] = None
  85. def forget(key: _Key) -> None:
  86. tokens.pop(key, None)
  87. owners.pop(key, None)
  88. generations[key] = generations.get(key, 0) + 1
  89. def arm(now: float) -> None:
  90. # One daemon timer for the earliest expiry; a touch only moves expiry later, so the timer may
  91. # fire early, find nothing expired and re-arm.
  92. nonlocal timer
  93. if timer is None and tokens:
  94. delay = min(t.last_used for t in tokens.values()) + _IDLE_TTL_S - now
  95. timer = threading.Timer(max(delay, 0.0) + 0.01, expire)
  96. timer.daemon = True
  97. timer.start()
  98. def settle() -> None:
  99. nonlocal timer
  100. if not tokens and timer is not None:
  101. timer.cancel()
  102. timer = None
  103. def expire() -> None:
  104. nonlocal timer
  105. with guard:
  106. if timer is threading.current_thread(): # not a newer timer armed while this one waited
  107. timer = None
  108. now = time.monotonic()
  109. for key in [k for k, t in tokens.items() if now - t.last_used > _IDLE_TTL_S]:
  110. del tokens[key]
  111. arm(now)
  112. def live(key: _Key, touch: bool) -> Optional[str]:
  113. with guard:
  114. token = tokens.get(key)
  115. if token is None:
  116. return None
  117. now = time.monotonic()
  118. if now - token.last_used > _IDLE_TTL_S:
  119. del tokens[key]
  120. settle()
  121. return None
  122. if touch:
  123. token.last_used = now
  124. return token.value
  125. def begin(key: _Key) -> int:
  126. with guard:
  127. return generations.get(key, 0)
  128. def commit(key: _Key, value: str, generation: Optional[int], owner: Optional[str]) -> bool:
  129. with guard:
  130. if generation is not None and generation != generations.get(key, 0):
  131. return False
  132. now = time.monotonic()
  133. tokens[key] = _Token(value, now)
  134. owners[key] = owner
  135. arm(now)
  136. return True
  137. def lock_profile(home: str, backend: Optional[str]) -> None:
  138. with guard:
  139. # Bump the generation for every key the lock names (not only the ones holding a token):
  140. # an unlock that is still running for this backend must see the lock when it returns.
  141. keys = {k for k in [*tokens, *owners, *generations] if k[0] == home and (backend is None or k[1] == backend)}
  142. if backend is not None:
  143. keys.add((home, backend))
  144. for key in keys:
  145. forget(key)
  146. settle()
  147. def release(session_id: str) -> None:
  148. with guard:
  149. for key in [k for k, owner in owners.items() if owner == session_id]:
  150. forget(key)
  151. settle()
  152. def lock_everything() -> None:
  153. with guard:
  154. for key in {*tokens, *owners}:
  155. forget(key)
  156. settle()
  157. return _TokenOps(live, begin, commit, lock_profile, release, lock_everything)
  158. _tokens = _token_store()
  159. def get_session_token(backend: str) -> Optional[str]:
  160. """Token for a real manager call; refreshes the idle timer."""
  161. return _tokens.live(_key(backend), True)
  162. def begin_unlock(backend: str) -> int:
  163. """Snapshot the lock generation before spawning the manager CLI; pass it to ``store_session_token``."""
  164. return _tokens.begin(_key(backend))
  165. def store_session_token(backend: str, token: str, generation: Optional[int] = None) -> bool:
  166. """Commit an unlock. Returns False (and drops the token) when a Lock happened since ``begin_unlock``."""
  167. return _tokens.commit(_key(backend), token, generation, get_current_session_id())
  168. def lock(backend: Optional[str] = None) -> None:
  169. """Forget the current profile's session for one backend (or all of them when None)."""
  170. _tokens.lock_profile(_key("")[0], backend)
  171. def release_session(session_id: str) -> None:
  172. """A gateway session ended: drop only the tokens that session unlocked."""
  173. _tokens.release(session_id)
  174. def lock_all_profiles() -> None:
  175. """Process shutdown: drop every token."""
  176. _tokens.lock_everything()
  177. def is_unlocked(backend: str) -> bool:
  178. """Status probe: does NOT extend the idle TTL (only real manager calls do)."""
  179. return _tokens.live(_key(backend), False) is not None
  180. def can_prompt_here() -> bool:
  181. """False in contexts where no human can answer (cron, webhook, api_server, -q)."""
  182. from tools.approval_context import _no_user_can_answer
  183. if _no_user_can_answer():
  184. return False
  185. return get_unlock_prompt_callback() is not None