onepassword_secrets_cli.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. """CLI handlers for ``hermes secrets onepassword ...``.
  2. Unlike Bitwarden, the ``op`` binary is NOT auto-installed: 1Password publishes the CLI through OS
  3. package managers and signed installers, so Hermes expects an already-installed, already-
  4. authenticated ``op`` and never downloads one.
  5. """
  6. from __future__ import annotations
  7. import argparse
  8. import os
  9. import subprocess
  10. from pathlib import Path
  11. from typing import Optional
  12. from rich.console import Console
  13. from rich.panel import Panel
  14. from agent.secret_sources import onepassword as op_src
  15. from hermes_cli._secrets_common import (
  16. arg,
  17. cfg_str,
  18. cli_version,
  19. disable_secret_source,
  20. flag,
  21. print_status_panel,
  22. print_table,
  23. register_subcommands,
  24. require_enabled,
  25. rotate_token,
  26. secret_cli_env,
  27. section_cfg,
  28. yn,
  29. )
  30. from hermes_cli.config import get_env_path, load_config, save_config, save_env_value
  31. _DEFAULT_TOKEN_ENV = "OP_SERVICE_ACCOUNT_TOKEN"
  32. _DOCS_URL = "https://developer.1password.com/docs/cli/get-started/"
  33. # Old name kept bound: tests call ``onepassword_secrets_cli._op_version`` directly.
  34. _op_version = cli_version
  35. def _op_cfg() -> dict:
  36. return section_cfg(load_config(), "onepassword")
  37. def _op_cfg_for_write(cfg: dict) -> dict:
  38. return cfg.setdefault("secrets", {}).setdefault("onepassword", {})
  39. def _references(op_cfg: dict) -> dict:
  40. env = op_cfg.get("env")
  41. return env if isinstance(env, dict) else {}
  42. def register_cli(parent_parser: argparse.ArgumentParser) -> None:
  43. """Attach the ``onepassword`` subcommand tree to a parent parser."""
  44. register_subcommands(parent_parser, "secrets_op_command", (
  45. ("setup", "Verify the op CLI, set account / token env var, and enable", cmd_setup, (
  46. arg("--account", "1Password account shorthand or sign-in address (op --account)"),
  47. arg("--token-env", f"Env var holding a service-account token (default {_DEFAULT_TOKEN_ENV})"),
  48. arg("--token", "Service-account token to store in .env non-interactively"),
  49. arg("--binary-path", "Absolute path to the op binary (skips PATH lookup)"),
  50. )),
  51. ("status", "Show config + op binary + references", cmd_status, ()),
  52. ("token", "Rotate the service-account token: validate and store it in .env", cmd_token, (
  53. arg("--token", "Provide the new token non-interactively (default: masked prompt)"),
  54. flag("--no-verify", "Store without probing 1Password first (not recommended)"),
  55. )),
  56. ("set", "Map an env var to an op:// reference", cmd_set, (
  57. arg("env_var", "Environment variable name, e.g. OPENAI_API_KEY"),
  58. arg("reference", "1Password reference, e.g. op://Private/OpenAI/api key"),
  59. )),
  60. ("remove", "Remove an env-var → reference mapping", cmd_remove, (
  61. arg("env_var", "Environment variable name to unmap"),
  62. )),
  63. ("sync", "Resolve references now and report what changed", cmd_sync, (
  64. flag("--apply", "Actually export resolved values into the current shell (default: dry-run)"),
  65. )),
  66. ("disable", "Turn off the 1Password integration", cmd_disable, ()),
  67. ))
  68. def cmd_setup(args: argparse.Namespace) -> int:
  69. console = Console()
  70. console.print(
  71. Panel.fit(
  72. "[bold]1Password secret source setup[/bold]\n\n"
  73. "Hermes resolves [cyan]op://vault/item/field[/cyan] references through your\n"
  74. "already-installed, already-authenticated 1Password CLI (`op`).\n\n"
  75. f"Don't have it yet? Install + sign in: [cyan]{_DOCS_URL}[/cyan]",
  76. border_style="cyan",
  77. )
  78. )
  79. cfg = load_config()
  80. op_cfg = _op_cfg_for_write(cfg)
  81. console.print()
  82. console.print("[bold]Step 1[/bold] Locate the op CLI")
  83. binary_path = (args.binary_path or op_cfg.get("binary_path", "") or "").strip()
  84. binary = op_src.find_op(binary_path)
  85. if binary is None:
  86. console.print(
  87. f" [red]✗ {binary_path} is not an executable op binary.[/red]"
  88. if binary_path
  89. else " [red]✗ op not found on PATH.[/red]"
  90. )
  91. console.print(f" Install the 1Password CLI: {_DOCS_URL}")
  92. return 1
  93. console.print(f" [green]✓[/green] {binary} ({_op_version(binary)})")
  94. if binary_path:
  95. op_cfg["binary_path"] = binary_path
  96. if args.account and args.account.strip():
  97. op_cfg["account"] = args.account.strip()
  98. console.print(f" Account: [cyan]{op_cfg['account']}[/cyan]")
  99. console.print()
  100. console.print("[bold]Step 2[/bold] Authentication")
  101. token_env = (args.token_env or op_cfg.get("service_account_token_env") or _DEFAULT_TOKEN_ENV).strip()
  102. op_cfg["service_account_token_env"] = token_env
  103. token = (args.token or "").strip()
  104. if token:
  105. save_env_value(token_env, token)
  106. os.environ[token_env] = token
  107. console.print(f" [green]✓[/green] service-account token stored in {get_env_path()} as {token_env}")
  108. elif os.environ.get(token_env):
  109. console.print(f" [green]✓[/green] using service-account token from {token_env}")
  110. else:
  111. who = _op_whoami(binary, op_cfg.get("account", ""))
  112. if who:
  113. console.print(f" [green]✓[/green] using existing op session ({who})")
  114. else:
  115. console.print(
  116. " [yellow]No service-account token and no active op session "
  117. "detected.[/yellow]\n"
  118. " Either run [cyan]op signin[/cyan] (desktop/interactive) or set a "
  119. f"service-account token in {token_env}, then re-run status."
  120. )
  121. op_cfg["enabled"] = True
  122. op_cfg.setdefault("env", {})
  123. op_cfg.setdefault("cache_ttl_seconds", 300)
  124. op_cfg.setdefault("override_existing", True)
  125. save_config(cfg)
  126. console.print()
  127. console.print("[green]✓ 1Password secret source is enabled.[/green]")
  128. console.print(
  129. " Map credentials: [cyan]hermes secrets onepassword set OPENAI_API_KEY "
  130. "\"op://Private/OpenAI/api key\"[/cyan]\n"
  131. " Preview: [cyan]hermes secrets onepassword sync[/cyan]\n"
  132. " Status: [cyan]hermes secrets onepassword status[/cyan]"
  133. )
  134. return 0
  135. def cmd_status(args: argparse.Namespace) -> int:
  136. console = Console()
  137. op_cfg = _op_cfg()
  138. enabled = bool(op_cfg.get("enabled"))
  139. account = cfg_str(op_cfg, "account")
  140. token_env = op_cfg.get("service_account_token_env", _DEFAULT_TOKEN_ENV)
  141. binary_path = cfg_str(op_cfg, "binary_path")
  142. references = _references(op_cfg)
  143. token_set = bool(os.environ.get(token_env))
  144. binary = op_src.find_op(binary_path)
  145. print_status_panel(console, "1Password secret source", (
  146. ("Enabled", yn(enabled)),
  147. ("Account", account or "[dim]default[/dim]"),
  148. ("Token env var", token_env),
  149. ("Token in env", yn(token_set)),
  150. ("Override existing", yn(bool(op_cfg.get("override_existing", True)))),
  151. ("Cache TTL (s)", str(op_cfg.get("cache_ttl_seconds", 300))),
  152. ("op binary", f"{binary} ({_op_version(binary)})" if binary else "[yellow]not found[/yellow]"),
  153. ("References", str(len(references))),
  154. ))
  155. if references:
  156. print_table(console, (("Env var", {"style": "cyan"}), "Reference"),
  157. ((name, str(references[name])) for name in sorted(references)))
  158. if not enabled:
  159. console.print("\n Run [cyan]hermes secrets onepassword setup[/cyan] to enable.")
  160. return 0
  161. if binary and not token_set:
  162. who = _op_whoami(binary, account)
  163. if who:
  164. console.print(f"\n [green]Active op session:[/green] {who}")
  165. else:
  166. console.print(
  167. f"\n [yellow]No active op session and {token_env} is unset — "
  168. "Hermes will warn and skip 1Password on next startup.[/yellow]"
  169. )
  170. if not references:
  171. console.print(
  172. "\n [yellow]No references mapped yet.[/yellow] Add one: "
  173. "[cyan]hermes secrets onepassword set ENV_VAR \"op://…\"[/cyan]"
  174. )
  175. return 0
  176. def cmd_set(args: argparse.Namespace) -> int:
  177. console = Console()
  178. # Backend validator keeps CLI and startup in agreement; store the validated/stripped value.
  179. valid, warnings = op_src._validate_references({args.env_var: args.reference})
  180. if args.env_var not in valid:
  181. for w in warnings:
  182. console.print(f"[red]{w}[/red]")
  183. return 1
  184. cfg = load_config()
  185. op_cfg = _op_cfg_for_write(cfg)
  186. if not isinstance(op_cfg.get("env"), dict):
  187. op_cfg["env"] = {}
  188. op_cfg["env"][args.env_var] = valid[args.env_var]
  189. save_config(cfg)
  190. console.print(f"[green]✓[/green] mapped [cyan]{args.env_var}[/cyan] → {valid[args.env_var]}")
  191. if not op_cfg.get("enabled"):
  192. console.print(
  193. " [yellow]Note: the integration is disabled — run "
  194. "[cyan]hermes secrets onepassword setup[/cyan] to turn it on.[/yellow]"
  195. )
  196. return 0
  197. def cmd_remove(args: argparse.Namespace) -> int:
  198. console = Console()
  199. cfg = load_config()
  200. op_cfg = _op_cfg_for_write(cfg)
  201. env_map = op_cfg.get("env")
  202. if not isinstance(env_map, dict) or args.env_var not in env_map:
  203. console.print(f"[yellow]{args.env_var} is not mapped.[/yellow]")
  204. return 1
  205. del env_map[args.env_var]
  206. save_config(cfg)
  207. console.print(f"[green]✓[/green] removed mapping for [cyan]{args.env_var}[/cyan]")
  208. return 0
  209. def cmd_token(args: argparse.Namespace) -> int:
  210. """Rotate the service-account token: verify with ``op whoami`` (unless ``--no-verify``) and
  211. only then persist to .env, so a bad paste never bricks the working token."""
  212. console = Console()
  213. op_cfg = _op_cfg()
  214. token_env = op_cfg.get("service_account_token_env", _DEFAULT_TOKEN_ENV)
  215. account = cfg_str(op_cfg, "account")
  216. binary_path = cfg_str(op_cfg, "binary_path")
  217. def verify(token: str) -> bool:
  218. binary = op_src.find_op(binary_path)
  219. if binary is None:
  220. console.print(
  221. f"[red]op CLI not found — install it ({_DOCS_URL}) or "
  222. "re-run with --no-verify to store anyway.[/red]"
  223. )
  224. return False
  225. console.print("Verifying with `op whoami`…")
  226. who = _op_whoami(binary, account, token_value=token)
  227. if who is None:
  228. console.print("[red]✗ New token was rejected by op — nothing was changed.[/red]")
  229. return False
  230. console.print(f"[green]✓ Token accepted[/green] ({who}).")
  231. return True
  232. return rotate_token(
  233. console, args.token, token_env,
  234. flag="--token",
  235. intro=(
  236. "Create a new service-account token at "
  237. "https://my.1password.com → Developer → Service Accounts.\n"
  238. ),
  239. prompt=f"Paste new token ({token_env}): ",
  240. verify=None if args.no_verify else verify,
  241. save=save_env_value, env_path=get_env_path, clear_caches=op_src.clear_caches,
  242. disabled_note=None if op_cfg.get("enabled") else (
  243. "[yellow]Note: the 1Password integration is currently disabled — "
  244. "run `hermes secrets onepassword setup` to turn it on.[/yellow]"
  245. ),
  246. )
  247. def cmd_sync(args: argparse.Namespace) -> int:
  248. console = Console()
  249. op_cfg = _op_cfg()
  250. if not require_enabled(console, op_cfg, "1Password", "onepassword"):
  251. return 1
  252. references = _references(op_cfg)
  253. if not references:
  254. console.print(
  255. "[yellow]No op:// references configured. Add one with "
  256. "`hermes secrets onepassword set ENV_VAR \"op://…\"`.[/yellow]"
  257. )
  258. return 0
  259. account = cfg_str(op_cfg, "account")
  260. token_env = op_cfg.get("service_account_token_env", _DEFAULT_TOKEN_ENV)
  261. binary_path = cfg_str(op_cfg, "binary_path")
  262. # --apply uses the startup code path so the skip/override/token-guard policy lives in one place.
  263. if args.apply:
  264. result = op_src.apply_onepassword_secrets(
  265. enabled=True,
  266. env=references,
  267. account=account,
  268. service_account_token_env=token_env,
  269. binary_path=binary_path,
  270. override_existing=bool(op_cfg.get("override_existing", True)),
  271. cache_ttl_seconds=0, # an explicit sync always resolves fresh
  272. )
  273. if result.error:
  274. console.print(f"[red]{result.error}[/red]")
  275. return 1
  276. print_table(
  277. console, (("Env var", {"style": "cyan"}), "Action"),
  278. [(name, "[green]exported[/green]") for name in sorted(result.applied)]
  279. + [(name, "[dim]skipped (already set / token var)[/dim]") for name in sorted(result.skipped)],
  280. result.warnings,
  281. )
  282. console.print(f"\n [green]Exported {len(result.applied)} secret(s) into current process.[/green]")
  283. return 0
  284. # Dry-run: resolve fresh (no cache) and preview, mutating nothing.
  285. try:
  286. secrets, warnings = op_src.fetch_onepassword_secrets(
  287. references=references,
  288. account=account,
  289. token_env=token_env,
  290. binary_path=binary_path,
  291. use_cache=False,
  292. )
  293. except RuntimeError as exc:
  294. console.print(f"[red]{exc}[/red]")
  295. return 1
  296. override = bool(op_cfg.get("override_existing", True))
  297. def action(name: str) -> str:
  298. if name == token_env:
  299. return "[dim]skip (token var)[/dim]"
  300. if name not in secrets:
  301. return "[red]unresolved (see warnings)[/red]"
  302. already = bool(os.environ.get(name))
  303. if already and not override:
  304. return "[dim]skip (already set)[/dim]"
  305. return "[green]would export[/green]" + (" (overrides)" if already else "")
  306. print_table(console, (("Env var", {"style": "cyan"}), "Action"),
  307. ((name, action(name)) for name in sorted(references)), warnings)
  308. console.print(
  309. "\n This was a dry-run — references resolve automatically on the next "
  310. "[cyan]hermes[/cyan] invocation. Re-run with [cyan]--apply[/cyan] to export "
  311. "into the current shell instead."
  312. )
  313. return 0
  314. def cmd_disable(args: argparse.Namespace) -> int:
  315. return disable_secret_source(
  316. "onepassword",
  317. "[green]Disabled.[/green] 1Password references will NOT be resolved on the "
  318. "next Hermes invocation.\n"
  319. " Your reference mappings are left in config.yaml — remove them with "
  320. "[cyan]hermes secrets onepassword remove ENV_VAR[/cyan] if you no longer "
  321. "need them.",
  322. )
  323. def _op_whoami(binary: Path, account: str, *, token_value: str = "") -> Optional[str]:
  324. """Short identity string if op is authenticated, else None. ``token_value`` probes a candidate
  325. token via the child's ``OP_SERVICE_ACCOUNT_TOKEN`` without touching the caller's environment."""
  326. cmd = [str(binary), "whoami"]
  327. if account:
  328. cmd += ["--account", account]
  329. env = secret_cli_env()
  330. if token_value:
  331. env["OP_SERVICE_ACCOUNT_TOKEN"] = token_value
  332. try:
  333. res = subprocess.run(
  334. cmd, env=env, capture_output=True, text=True,
  335. encoding="utf-8", errors="replace", timeout=10,
  336. check=False,
  337. )
  338. except (OSError, subprocess.TimeoutExpired):
  339. return None
  340. if res.returncode != 0:
  341. return None
  342. return (res.stdout or "").strip().replace("\n", " ")[:120] or "authenticated"