onepassword.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. """1Password Login items as a vault backend (``op`` CLI).
  2. Unlock: ``op signin --raw`` with the master password on stdin (desktop-app
  3. integration or account-level auth) mints an ``OP_SESSION_<account>`` token.
  4. A configured service-account token skips the prompt entirely (headless).
  5. List: ``op item list --categories Login --format json`` → title, urls,
  6. username, vault. Resolve: ``op item get <id> --vault <vault-id> ...`` (service
  7. accounts reject an item read without a vault query).
  8. """
  9. from __future__ import annotations
  10. import json
  11. import logging
  12. import os
  13. import subprocess
  14. from pathlib import Path
  15. from typing import Dict, List, Optional
  16. from agent.secret_sources.base import run_cli
  17. from agent.secret_sources.onepassword import _OP_ENV_ALLOWLIST, _scrub, find_op
  18. from agent.vault_backends.base import LoginBackend, UnlockRequired, run_with_stdin_secret
  19. from agent.vault_backends import unlock as _unlock
  20. from agent.vault_store import VaultItemMeta, normalize_origin
  21. logger = logging.getLogger(__name__)
  22. _TIMEOUT = 30.0
  23. class OnePasswordLoginBackend(LoginBackend):
  24. name = "onepassword"
  25. display_name = "1Password"
  26. prefix = "op:"
  27. needs_unlock = True
  28. def __init__(self, cfg: Optional[dict] = None):
  29. self.cfg = cfg or {}
  30. from agent.secret_scope import get_secret
  31. env_name = str(self.cfg.get("service_account_token_env") or "OP_SERVICE_ACCOUNT_TOKEN")
  32. self._service_token = get_secret(env_name, "") or ""
  33. self._item_vaults: dict[str, str] = {} # item id -> vault id from the latest ``item list``
  34. # ── auth ────────────────────────────────────────────────────────────────
  35. def _op(self) -> Path:
  36. op = find_op(str(self.cfg.get("binary_path") or ""))
  37. if op is None:
  38. raise RuntimeError("1Password CLI (op) not found — install it or set vault.onepassword.binary_path")
  39. return op
  40. def _env(self, session_token: Optional[str]) -> dict[str, str]:
  41. from agent.secret_scope import get_secret
  42. env = {k: os.environ[k] for k in _OP_ENV_ALLOWLIST if k in os.environ and not k.startswith("OP_CONNECT_")}
  43. # Connect credentials outrank OP_SERVICE_ACCOUNT_TOKEN inside op, so they must come from the
  44. # profile's own secret scope like the service token does — never from the launch environment.
  45. for k in ("OP_CONNECT_HOST", "OP_CONNECT_TOKEN"):
  46. if v := get_secret(k, ""):
  47. env[k] = v
  48. env["NO_COLOR"] = "1"
  49. account = str(self.cfg.get("account") or "")
  50. if account:
  51. env["OP_ACCOUNT"] = account
  52. if self._service_token:
  53. env["OP_SERVICE_ACCOUNT_TOKEN"] = self._service_token
  54. elif session_token:
  55. # op signin --raw prints the bare token; the env var name carries the account shorthand,
  56. # which op also accepts as plain OP_SESSION for the default account.
  57. env[f"OP_SESSION_{account}" if account else "OP_SESSION"] = session_token
  58. return env
  59. def is_unlocked(self) -> bool:
  60. return bool(self._service_token) or _unlock.is_unlocked(self.name)
  61. def unlock(self, master_password: str) -> None:
  62. """Mint a session token from the master password (consumed on stdin, never argv)."""
  63. generation = _unlock.begin_unlock(self.name)
  64. cmd = [str(self._op()), "signin", "--raw"]
  65. if account := str(self.cfg.get("account") or ""):
  66. cmd += ["--account", account]
  67. proc = run_with_stdin_secret(cmd, env=self._env(None), secret=master_password, timeout=_TIMEOUT, label="op")
  68. token = (proc.stdout or "").strip()
  69. if proc.returncode != 0 or not token:
  70. raise RuntimeError(f"1Password unlock failed: {_scrub(proc.stderr or '')[:200] or 'no session token'}")
  71. if not _unlock.store_session_token(self.name, token, generation):
  72. raise RuntimeError("1Password was locked while unlocking; try again")
  73. def _run(self, *args: str) -> str:
  74. token = None if self._service_token else _unlock.get_session_token(self.name)
  75. if not self._service_token and not token:
  76. raise UnlockRequired(self)
  77. proc = run_cli([str(self._op()), *args], env=self._env(token), timeout=_TIMEOUT, label="op",
  78. timeout_message="op timed out", stdin=subprocess.DEVNULL)
  79. if proc.returncode != 0:
  80. err = _scrub(proc.stderr or "")
  81. # A service account never holds a session, so an auth failure there is not a lock to undo:
  82. # surface op's own error instead of an unlock prompt that reports "already unlocked".
  83. if not self._service_token and any(w in err.lower() for w in ("session", "sign in", "not signed in")):
  84. _unlock.lock(self.name)
  85. raise UnlockRequired(self)
  86. raise RuntimeError(f"op failed: {err[:200]}")
  87. return proc.stdout or ""
  88. # ── backend contract ───────────────────────────────────────────────────
  89. def list_items(self) -> list[VaultItemMeta]:
  90. if not self.is_unlocked():
  91. return []
  92. raw = json.loads(self._run("item", "list", "--categories", "Login", "--format", "json") or "[]")
  93. out: list[VaultItemMeta] = []
  94. self._item_vaults = {}
  95. for item in raw if isinstance(raw, list) else []:
  96. vault = item.get("vault") or {}
  97. if item.get("id"):
  98. self._item_vaults[str(item["id"])] = str(vault.get("id") or "") if isinstance(vault, dict) else ""
  99. urls = [str(u["href"]) for u in item.get("urls") or [] if isinstance(u, dict) and u.get("href")]
  100. origins = _all_origins(urls)
  101. if not origins:
  102. continue
  103. username = str(item.get("additional_information") or "").strip() or None
  104. out.append(VaultItemMeta(
  105. id=f"{self.prefix}{item.get('id')}", kind="login", label=str(item.get("title") or origins[0]),
  106. origin=origins[0], created_at=str(item.get("created_at") or ""),
  107. identifier_type="username" if username else None, identifier=username,
  108. allowed_origins=_web_origins(origins)))
  109. return out
  110. def get_meta(self, handle: str) -> Optional[VaultItemMeta]:
  111. return next((m for m in self.list_items() if m.id == handle), None)
  112. def _item_selector(self, handle: str) -> list[str]:
  113. """``op item get`` target for a listed login. A service account must name the item's vault
  114. (``--vault``) and ``item list`` reports it, so the vault comes from the same listing that
  115. proved the handle is a Login item; a handle nothing listed is refused before any secret read."""
  116. item_id = handle[len(self.prefix):]
  117. if item_id not in self._item_vaults:
  118. self.list_items()
  119. if item_id not in self._item_vaults:
  120. raise RuntimeError("1Password login not found; list logins again")
  121. vault_id = self._item_vaults[item_id]
  122. return [item_id, "--vault", vault_id] if vault_id else [item_id]
  123. def resolve_password(self, handle: str) -> str:
  124. return self._run("item", "get", *self._item_selector(handle),
  125. "--fields", "label=password", "--reveal").rstrip("\r\n")
  126. def resolve_otp(self, handle: str) -> Optional[str]:
  127. # `--otp` mints the current TOTP from the item's one-time-password field; items without one error out.
  128. try:
  129. code = self._run("item", "get", *self._item_selector(handle), "--otp").strip()
  130. except Exception:
  131. return None
  132. return code if code.isdigit() else None
  133. def _web_origins(origins: list[str]) -> tuple:
  134. """Fill targets are browser pages, so app URIs (``androidapp://`` etc.) never
  135. widen the fill set; an item whose only URI is an app URI keeps its single
  136. (unfillable-from-a-page) origin exactly as before."""
  137. web = tuple(o for o in origins if o.startswith(("http://", "https://")))
  138. return web or (origins[0],)
  139. def _all_origins(urls: list[str]) -> list[str]:
  140. """Every normalized origin saved on the item, deduped, order preserved.
  141. A 1Password Login item can carry several websites; each of them is a place the
  142. user told 1Password the credential belongs, so all of them are valid fill targets.
  143. """
  144. out: list[str] = []
  145. for u in urls:
  146. try:
  147. origin = normalize_origin(u)
  148. except Exception:
  149. continue
  150. if origin not in out:
  151. out.append(origin)
  152. return out