base.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. """Login-backend contract + registry for the browser credential vault.
  2. A ``LoginBackend`` lists login metadata (never secrets) and resolves ONE
  3. password at fill time. External managers (1Password, Bitwarden) additionally
  4. need a per-session unlock; ``resolve_password`` raises ``UnlockRequired``
  5. while locked so the tool can ask the surface to prompt. Handles are
  6. namespaced by ``prefix`` so ``backend_for_handle`` needs no lookup table.
  7. """
  8. from __future__ import annotations
  9. import subprocess
  10. from contextlib import AbstractContextManager, nullcontext
  11. from abc import ABC, abstractmethod
  12. from pathlib import Path
  13. from typing import Dict, List, Optional, Sequence
  14. from agent.vault_store import VaultItemMeta
  15. class UnlockRequired(Exception):
  16. """The backend is locked for this session; the surface must prompt for the master password."""
  17. def __init__(self, backend: LoginBackend):
  18. super().__init__(f"{backend.display_name} is locked")
  19. self.backend = backend
  20. class LoginBackend(ABC):
  21. name: str # config key: local | onepassword | bitwarden
  22. display_name: str # user-facing
  23. prefix: str # handle prefix ("vault_", "op:", "bw:")
  24. needs_unlock: bool = False
  25. def owns(self, handle: str) -> bool:
  26. return handle.startswith(self.prefix)
  27. def is_unlocked(self) -> bool:
  28. return True
  29. def fill_context(self) -> AbstractContextManager:
  30. """Optional profile-exclusive context, entered after the origin pre-check: covers the in-context
  31. metadata re-check, secret resolution and the CDP write."""
  32. return nullcontext()
  33. @abstractmethod
  34. def list_items(self) -> list[VaultItemMeta]:
  35. """Metadata only. Locked external backends return [] (the agent sees a lock hint instead)."""
  36. @abstractmethod
  37. def get_meta(self, handle: str) -> Optional[VaultItemMeta]: ...
  38. @abstractmethod
  39. def resolve_password(self, handle: str) -> str:
  40. """Server-side only; raises ``UnlockRequired`` when locked."""
  41. def resolve_otp(self, handle: str) -> Optional[str]:
  42. """Current one-time code for a login that stores a TOTP seed, else None (the user is asked).
  43. Server-side only, like resolve_password."""
  44. return None
  45. def resolve_secret(self, handle: str) -> dict[str, str]:
  46. """Full payload of a payment/address item (server-side only). External managers list only
  47. logins, so the base returns the password-only shape."""
  48. return {"password": self.resolve_password(handle)}
  49. def run_with_stdin_secret(argv: Sequence[str], *, env: dict[str, str], secret: str, timeout: float,
  50. label: str) -> subprocess.CompletedProcess:
  51. """Run a manager CLI feeding *secret* on stdin (never argv, never env). Spawn/timeout → RuntimeError."""
  52. try:
  53. return subprocess.run(
  54. list(argv), env=env, input=secret + "\n", capture_output=True, text=True,
  55. encoding="utf-8", errors="replace", timeout=timeout, check=False)
  56. except subprocess.TimeoutExpired as exc:
  57. raise RuntimeError(f"{label} unlock timed out after {timeout:.0f}s") from exc
  58. except OSError as exc:
  59. raise RuntimeError(f"failed to invoke {label}: {exc}") from exc
  60. def run_with_secret_env(argv: Sequence[str], *, env: dict[str, str], secret_env: str, secret: str, timeout: float,
  61. label: str) -> subprocess.CompletedProcess:
  62. """Run a manager CLI whose non-interactive contract reads the secret from a named env var.
  63. The variable is set on the child's environment only (never argv, never our process)."""
  64. child_env = dict(env)
  65. child_env[secret_env] = secret
  66. try:
  67. return subprocess.run(
  68. list(argv), env=child_env, stdin=subprocess.DEVNULL, capture_output=True, text=True,
  69. encoding="utf-8", errors="replace", timeout=timeout, check=False)
  70. except subprocess.TimeoutExpired as exc:
  71. raise RuntimeError(f"{label} unlock timed out after {timeout:.0f}s") from exc
  72. except OSError as exc:
  73. raise RuntimeError(f"failed to invoke {label}: {exc}") from exc
  74. def _cfg() -> dict:
  75. from hermes_cli.config import load_config_readonly
  76. cfg = load_config_readonly().get("vault") or {}
  77. return cfg if isinstance(cfg, dict) else {}
  78. def external_backend_classes():
  79. from agent.vault_backends.bitwarden import BitwardenLoginBackend
  80. from agent.vault_backends.onepassword import OnePasswordLoginBackend
  81. return (OnePasswordLoginBackend, BitwardenLoginBackend)
  82. def is_installed(name: str) -> bool:
  83. """Is the manager CLI reachable — honouring a configured ``binary_path`` over PATH."""
  84. import shutil
  85. section = _cfg().get(name) or {}
  86. explicit = str(section.get("binary_path") or "") if isinstance(section, dict) else ""
  87. if explicit:
  88. return Path(explicit).is_file()
  89. if name == "onepassword":
  90. from agent.secret_sources.onepassword import find_op
  91. return find_op() is not None
  92. return shutil.which("bw") is not None
  93. def is_enabled(name: str) -> bool:
  94. """An installed manager is a login source unless the user opted out (``vault.<name>.enabled: false``).
  95. Zero-config on purpose: a user with ``bw``/``op`` on PATH should never have to discover a toggle."""
  96. section = _cfg().get(name) or {}
  97. if isinstance(section, dict) and section.get("enabled") is False:
  98. return False
  99. return is_installed(name)
  100. def enabled_backends() -> list[LoginBackend]:
  101. """Local first (always on), then every detected external manager the user has not turned off."""
  102. from agent.vault_backends.local import LocalLoginBackend
  103. cfg = _cfg()
  104. out: list[LoginBackend] = [LocalLoginBackend()]
  105. for cls in external_backend_classes():
  106. if is_enabled(cls.name):
  107. section = cfg.get(cls.name) or {}
  108. out.append(cls(section if isinstance(section, dict) else {}))
  109. from agent.vault_backend_registry import enabled_plugin_backends
  110. return out + enabled_plugin_backends(cfg)
  111. def backend_for_handle(handle: str) -> Optional[LoginBackend]:
  112. return next((b for b in enabled_backends() if b.owns(handle)), None)