_secrets_common.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. """Helpers shared by the Bitwarden and 1Password ``hermes secrets`` CLIs.
  2. Import-light on purpose: ``hermes_cli.secrets_cli`` must stay free of the Bitwarden backend
  3. (``cryptography``) at import time, so nothing here touches a secret-source backend.
  4. """
  5. from __future__ import annotations
  6. import argparse
  7. import os
  8. import subprocess
  9. import sys
  10. from pathlib import Path
  11. from typing import Callable, Iterable, Optional, Sequence
  12. from rich.console import Console
  13. from rich.panel import Panel
  14. from rich.table import Table
  15. from hermes_cli.config import load_config, save_config
  16. from hermes_cli.secret_prompt import masked_secret_prompt
  17. def yn(b: bool) -> str:
  18. return "[green]yes[/green]" if b else "[dim]no[/dim]"
  19. def section_cfg(cfg: dict, section: str) -> dict:
  20. """``cfg["secrets"][section]`` or ``{}``."""
  21. return (cfg.get("secrets") or {}).get(section) or {}
  22. def cfg_str(cfg: dict, key: str) -> str:
  23. """A stripped string config value; ``""`` for missing/None."""
  24. return str(cfg.get(key, "") or "").strip()
  25. def arg(name: str, help_text: str, **kwargs) -> tuple:
  26. """One ``add_argument`` spec for :func:`register_subcommands`."""
  27. return name, dict(help=help_text, **kwargs)
  28. def flag(name: str, help_text: str) -> tuple:
  29. """A boolean ``store_true`` spec for :func:`register_subcommands`."""
  30. return arg(name, help_text, action="store_true")
  31. def register_subcommands(parent: argparse.ArgumentParser, dest: str, commands: Iterable) -> None:
  32. """Attach ``(name, help, handler, [arg(...), ...])`` subcommands to ``parent``."""
  33. sub = parent.add_subparsers(dest=dest)
  34. for name, help_text, func, arguments in commands:
  35. parser = sub.add_parser(name, help=help_text)
  36. for arg_name, kwargs in arguments:
  37. parser.add_argument(arg_name, **kwargs)
  38. parser.set_defaults(func=func)
  39. def require_enabled(console: Console, cfg: dict, product: str, command: str) -> bool:
  40. """Print the "integration is disabled" hint and return False unless ``cfg["enabled"]``."""
  41. if cfg.get("enabled"):
  42. return True
  43. console.print(f"[yellow]{product} integration is disabled. Run "
  44. f"`hermes secrets {command} setup` first.[/yellow]")
  45. return False
  46. def print_status_panel(console: Console, title: str, rows: Iterable) -> None:
  47. """Two-column key/value table inside a cyan panel (the ``status`` layout)."""
  48. table = Table(show_header=False, box=None, padding=(0, 2))
  49. table.add_column("", style="bold")
  50. table.add_column("")
  51. for label, value in rows:
  52. table.add_row(label, value)
  53. console.print(Panel(table, title=title, border_style="cyan"))
  54. def print_table(console: Console, columns: Sequence, rows: Iterable,
  55. warnings: Iterable[str] = (), indent: str = "") -> None:
  56. """Headed table; ``columns`` entries are ``header`` or ``(header, add_column kwargs)``.
  57. ``warnings`` are echoed after the table, one ``warning:`` line each.
  58. """
  59. table = Table(show_header=True, header_style="bold")
  60. for col in columns:
  61. header, kwargs = (col, {}) if isinstance(col, str) else col
  62. table.add_column(header, **kwargs)
  63. for row in rows:
  64. table.add_row(*row)
  65. console.print(table)
  66. for w in warnings:
  67. console.print(f"{indent}[yellow]warning:[/yellow] {w}")
  68. def cli_version(binary: Path) -> str:
  69. """Return the first line of ``<binary> --version`` or ``"version unknown"``."""
  70. try:
  71. res = subprocess.run([str(binary), "--version"], capture_output=True, text=True, encoding='utf-8',
  72. errors='replace', timeout=5, check=False)
  73. if res.returncode == 0:
  74. return (res.stdout or res.stderr).strip().splitlines()[0]
  75. except (OSError, subprocess.TimeoutExpired):
  76. pass
  77. return "version unknown"
  78. def secret_cli_env() -> dict:
  79. """Env for a secret-manager CLI child (``bws`` / ``op``).
  80. Intentionally receives tokens — no scrub, no HOME rewrite (both CLIs store state under the
  81. real user home).
  82. """
  83. from tools.environments.local import build_subprocess_env
  84. env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)
  85. env.setdefault("NO_COLOR", "1")
  86. return env
  87. def rotate_token(
  88. console: Console, given: Optional[str], token_env: str, *, flag: str, intro: str, prompt: str,
  89. verify: Optional[Callable[[str], bool]], save: Callable[[str, str], object],
  90. env_path: Callable[[], object], clear_caches: Callable[[], object],
  91. disabled_note: Optional[str],
  92. ) -> int:
  93. """Shared ``token`` subcommand: prompt, optionally verify, then persist. Returns the exit code.
  94. ``verify(token)`` prints its own diagnostics and returns False to abort without touching
  95. .env — so a bad paste never bricks the working token; None skips verification
  96. (``--no-verify``). ``save``/``env_path`` are passed in (not imported here) so each CLI
  97. module's own ``save_env_value``/``get_env_path`` bindings — which tests monkeypatch — stay
  98. in effect. Old cached pulls are keyed on the previous token's fingerprint; clearing them
  99. makes the next startup fetch fresh with the new credential.
  100. """
  101. token = (given or "").strip()
  102. if not token:
  103. if not sys.stdin.isatty():
  104. console.print(f"[red]No TTY — pass the token with {flag}.[/red]")
  105. return 1
  106. console.print(intro)
  107. token = masked_secret_prompt(prompt).strip()
  108. if not token:
  109. console.print("[red]Empty token, aborting.[/red]")
  110. return 1
  111. if verify is not None and not verify(token):
  112. return 1
  113. save(token_env, token)
  114. os.environ[token_env] = token
  115. clear_caches()
  116. console.print(f"[green]✓[/green] stored in {env_path()} as {token_env}. "
  117. "Takes effect on the next Hermes invocation.")
  118. if disabled_note:
  119. console.print(disabled_note)
  120. return 0
  121. def prompt_index(console: Console, prompt: str, count: int, *,
  122. allow_empty: bool = False, empty_message: Optional[str] = None) -> int:
  123. """Loop until the user enters an integer in ``1..count``; return it.
  124. Blank input returns 0 when ``allow_empty``; otherwise ``empty_message`` (if any)
  125. is printed and the prompt repeats.
  126. """
  127. while True:
  128. choice = console.input(prompt).strip()
  129. if not choice:
  130. if allow_empty:
  131. return 0
  132. if empty_message:
  133. console.print(empty_message)
  134. continue
  135. try:
  136. idx = int(choice)
  137. except ValueError:
  138. console.print(" [red]Enter a number.[/red]")
  139. continue
  140. if 1 <= idx <= count:
  141. return idx
  142. console.print(f" [red]Out of range — pick 1-{count}.[/red]")
  143. def disable_secret_source(section: str, message: str) -> int:
  144. """Set ``secrets.<section>.enabled = False`` in config.yaml and print ``message``."""
  145. cfg = load_config()
  146. cfg.setdefault("secrets", {}).setdefault(section, {})["enabled"] = False
  147. save_config(cfg)
  148. Console().print(message)
  149. return 0