bitwarden.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. """Bitwarden Password Manager logins as a vault backend (``bw`` CLI).
  2. This is the personal/org *password* vault (``bw``), distinct from the
  3. Bitwarden Secrets Manager (``bws``) source that hydrates API keys at startup.
  4. Unlock: ``bw unlock --raw --passwordenv VAR`` (the CLI rejects a piped password) mints a
  5. ``BW_SESSION`` token. List: ``bw list items`` filtered to type=1 (login) with
  6. a URI. Resolve: ``bw get password <id>``.
  7. """
  8. from __future__ import annotations
  9. import json
  10. import logging
  11. import os
  12. import shutil
  13. import subprocess
  14. from pathlib import Path
  15. from typing import Dict, List, Optional
  16. from agent.secret_sources.base import run_cli, scrub_ansi
  17. from agent.vault_backends import unlock as _unlock
  18. from agent.vault_backends.base import LoginBackend, UnlockRequired, run_with_secret_env
  19. from agent.vault_store import VaultItemMeta, normalize_origin
  20. logger = logging.getLogger(__name__)
  21. _TIMEOUT = 30.0
  22. _ENV_KEEP = ("PATH", "HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "SystemRoot",
  23. "TMPDIR", "TMP", "TEMP", "XDG_CONFIG_HOME", "BITWARDENCLI_APPDATA_DIR")
  24. class BitwardenLoginBackend(LoginBackend):
  25. name = "bitwarden"
  26. display_name = "Bitwarden"
  27. prefix = "bw:"
  28. needs_unlock = True
  29. def __init__(self, cfg: Optional[dict] = None):
  30. self.cfg = cfg or {}
  31. def _bw(self) -> Path:
  32. explicit = str(self.cfg.get("binary_path") or "")
  33. found = explicit or shutil.which("bw")
  34. if not found:
  35. raise RuntimeError("Bitwarden CLI (bw) not found — install it or set vault.bitwarden.binary_path")
  36. return Path(found)
  37. def _env(self, session_token: Optional[str]) -> dict[str, str]:
  38. env = {k: os.environ[k] for k in _ENV_KEEP if k in os.environ}
  39. env["NO_COLOR"] = "1"
  40. if session_token:
  41. env["BW_SESSION"] = session_token
  42. return env
  43. def is_unlocked(self) -> bool:
  44. return _unlock.is_unlocked(self.name)
  45. def unlock(self, master_password: str) -> None:
  46. # bw refuses a piped password ("Master password is required"); its non-interactive contract is
  47. # --passwordenv: the variable exists only in the child's environment, never in argv or ours.
  48. generation = _unlock.begin_unlock(self.name)
  49. proc = run_with_secret_env([str(self._bw()), "unlock", "--raw", "--nointeraction", "--passwordenv", "HERMES_BW_MASTER"],
  50. env=self._env(None), secret_env="HERMES_BW_MASTER", secret=master_password,
  51. timeout=_TIMEOUT, label="bw")
  52. token = (proc.stdout or "").strip()
  53. if proc.returncode != 0 or not token:
  54. err = scrub_ansi(proc.stderr or "").strip()[:200]
  55. if "not logged in" in err.lower():
  56. err = "not logged in — run `bw login` once in a terminal first"
  57. raise RuntimeError(f"Bitwarden unlock failed: {err or 'no session key'}")
  58. if not _unlock.store_session_token(self.name, token, generation):
  59. raise RuntimeError("Bitwarden was locked while unlocking; try again")
  60. def _run(self, *args: str) -> str:
  61. token = _unlock.get_session_token(self.name)
  62. if not token:
  63. raise UnlockRequired(self)
  64. proc = run_cli([str(self._bw()), *args, "--nointeraction"], env=self._env(token), timeout=_TIMEOUT,
  65. label="bw", timeout_message="bw timed out", stdin=subprocess.DEVNULL)
  66. if proc.returncode != 0:
  67. err = scrub_ansi(proc.stderr or "")
  68. if "locked" in err.lower() or "session" in err.lower():
  69. _unlock.lock(self.name)
  70. raise UnlockRequired(self)
  71. raise RuntimeError(f"bw failed: {err[:200]}")
  72. return proc.stdout or ""
  73. def list_items(self) -> list[VaultItemMeta]:
  74. if not self.is_unlocked():
  75. return []
  76. raw = json.loads(self._run("list", "items") or "[]")
  77. out: list[VaultItemMeta] = []
  78. for item in raw if isinstance(raw, list) else []:
  79. if item.get("type") != 1 or not isinstance(item.get("login"), dict):
  80. continue
  81. login = item["login"]
  82. origins: list[str] = []
  83. for uri in login.get("uris") or []:
  84. if uri.get("match") == 5: # Bitwarden URI match "Never": not a fill target
  85. continue
  86. try:
  87. origin = normalize_origin(str(uri.get("uri") or ""))
  88. except Exception:
  89. continue
  90. if origin and origin not in origins:
  91. origins.append(origin)
  92. if not origins:
  93. continue
  94. username = str(login.get("username") or "").strip() or None
  95. # Fill targets are browser pages, so app URIs (androidapp:// etc.) never widen
  96. # the fill set; an app-URI-only item keeps its single origin exactly as before.
  97. web_origins = tuple(o for o in origins if o.startswith(("http://", "https://"))) or (origins[0],)
  98. out.append(VaultItemMeta(
  99. id=f"{self.prefix}{item.get('id')}", kind="login", label=str(item.get("name") or origins[0]),
  100. origin=origins[0], created_at=str(item.get("creationDate") or ""),
  101. identifier_type="username" if username else None, identifier=username,
  102. allowed_origins=web_origins))
  103. return out
  104. def get_meta(self, handle: str) -> Optional[VaultItemMeta]:
  105. return next((m for m in self.list_items() if m.id == handle), None)
  106. def resolve_password(self, handle: str) -> str:
  107. return self._run("get", "password", handle[len(self.prefix):]).rstrip("\r\n")
  108. def resolve_otp(self, handle: str) -> Optional[str]:
  109. # `bw get totp <id>` mints the current code from the item's TOTP seed; "No TOTP available" otherwise.
  110. try:
  111. code = self._run("get", "totp", handle[len(self.prefix):]).strip()
  112. except Exception:
  113. return None
  114. return code if code.isdigit() else None