command.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. """``command`` secret source — resolve secrets via a user-configured helper.
  2. Ports the desktop app's TypeScript ``CommandSecretsProvider`` semantics. The
  3. helper (``keepassxc-cli``, ``secret-tool``, a script that cats a tmpfs env
  4. file, ...) comes from ``secrets.command`` in ``config.yaml`` — NEVER from
  5. ``.env``, which holds only secret values.
  6. Security model: the command string is the USER'S OWN configuration, so it runs
  7. via ``/bin/sh -c``; the requested key reaches the child ONLY via
  8. ``HERMES_SECRET_KEY`` (never interpolated, so a hostile key name is inert); hard
  9. timeout (default 3s) + 1 MiB output cap, every failure degrades to "no value";
  10. failure logs carry ONLY structured fields (exit code / signal / errno), never
  11. the command, the helper's stderr (captured and DISCARDED) or any value; startup
  12. runs the helper exactly ONCE with an empty key; POSIX-only (needs ``/bin/sh``).
  13. """
  14. from __future__ import annotations
  15. import os
  16. import platform
  17. import re
  18. import signal as _signal
  19. import subprocess
  20. import sys
  21. from pathlib import Path
  22. from typing import Dict, Optional
  23. from agent.secret_sources.base import ErrorKind, FetchResult, SecretSource, coerce_float, source_child_env
  24. __all__ = ["FetchResult", "unquote_dotenv_value"]
  25. # TIGHT on purpose: a helper MUST be fast and NON-INTERACTIVE (an already
  26. # unlocked DB, `secret-tool lookup`, `cat` of a tmpfs file) — not a PIN prompt.
  27. _COMMAND_TIMEOUT_SECONDS = 3.0
  28. _MAX_OUTPUT_BYTES = 1024 * 1024 # a misbehaving helper can't OOM us
  29. # Anchored; `.` does not cross newlines, so a multi-line blob never matches.
  30. _ENV_LINE = re.compile(r"^([A-Za-z_][A-Za-z0-9_]*)=(.*)$")
  31. def _is_windows() -> bool:
  32. return os.name == "nt" or platform.system() == "Windows"
  33. def _log(message: str) -> None:
  34. print(f"[secrets:command] {message}", file=sys.stderr)
  35. def unquote_dotenv_value(raw: str) -> str:
  36. """Strip one layer of matching surrounding quotes from a dotenv value.
  37. Requires length >= 2 so a lone ``"`` stays intact while ``""``/``''``
  38. correctly yield an empty string.
  39. """
  40. t = raw.strip()
  41. if len(t) >= 2 and t[0] == t[-1] and t[0] in "\"'":
  42. return t[1:-1]
  43. return t
  44. def _run_helper(command: str, secret_key: str, timeout_seconds: float, max_output_bytes: int) -> Optional[str]:
  45. """Run the helper via ``/bin/sh -c`` and return its stdout, or None.
  46. The key travels as DATA in ``HERMES_SECRET_KEY``. stdout/stderr are piped
  47. (never inherited); stderr is discarded. Any failure logs structured fields
  48. only and returns None — never raises.
  49. """
  50. if _is_windows():
  51. _log("the 'command' provider is POSIX-only (needs /bin/sh); resolving no value on Windows")
  52. return None
  53. # The helper legitimately gets the user's shell env (it may need any
  54. # credential to resolve the secret) — but a multiplex profile only its own.
  55. env = source_child_env()
  56. env["HERMES_SECRET_KEY"] = secret_key
  57. try:
  58. proc = subprocess.Popen(
  59. ["/bin/sh", "-c", command], env=env, stdin=subprocess.DEVNULL,
  60. stdout=subprocess.PIPE, stderr=subprocess.PIPE, # stderr captured and DISCARDED — never inherited
  61. # detached-spawn: ok — awaited; a hard timeout (default 3 s) kills the whole group
  62. start_new_session=True, # so the hard timeout can kill the whole group
  63. )
  64. except OSError as exc:
  65. _log(f"helper failed to spawn; resolving no value: errno={exc.errno}")
  66. return None
  67. try:
  68. stdout_bytes, _stderr_discarded = proc.communicate(timeout=timeout_seconds)
  69. except subprocess.TimeoutExpired:
  70. # Kill the whole group: a helper may have forked children that would
  71. # otherwise keep the pipe open. POSIX-only by the early return above.
  72. try:
  73. os.killpg(os.getpgid(proc.pid), _signal.SIGKILL) # windows-footgun: ok
  74. except (ProcessLookupError, PermissionError, OSError):
  75. proc.kill()
  76. try:
  77. proc.communicate(timeout=1.0)
  78. except (subprocess.TimeoutExpired, ValueError, OSError):
  79. pass
  80. _log(f"helper timed out after {timeout_seconds:g}s; resolving no value")
  81. return None
  82. if proc.returncode != 0:
  83. code, signame = str(proc.returncode), "none"
  84. if proc.returncode < 0:
  85. try:
  86. signame = _signal.Signals(-proc.returncode).name
  87. except ValueError:
  88. signame = str(-proc.returncode)
  89. code = "?"
  90. _log(f"helper failed; resolving no value: code={code} signal={signame}")
  91. return None
  92. if len(stdout_bytes) > max_output_bytes:
  93. _log(f"helper output exceeded the {max_output_bytes}-byte cap; resolving no value")
  94. return None
  95. return stdout_bytes.decode("utf-8", errors="replace")
  96. def _parse_dotenv_map(stdout: str) -> dict[str, str]:
  97. """Parse a KEY=VALUE blob; comments and non-env-shaped lines are skipped."""
  98. out: dict[str, str] = {}
  99. for raw in stdout.replace("\r\n", "\n").split("\n"):
  100. line = raw.strip()
  101. if not line or line.startswith("#"):
  102. continue
  103. m = _ENV_LINE.match(line)
  104. if m:
  105. out[m.group(1)] = unquote_dotenv_value(m.group(2))
  106. return out
  107. class CommandSource(SecretSource):
  108. """User-configured helper command as a registered **bulk** source.
  109. Composes with the other sources through ``apply_all()``; there is
  110. deliberately NO single-provider selector. The helper enumerates a
  111. KEY=VALUE blob in one run. Config::
  112. secrets:
  113. command:
  114. enabled: true
  115. command: "cat /run/user/1000/hermes-secrets.env"
  116. """
  117. name = "command"
  118. label = "Command helper"
  119. shape = "bulk"
  120. remediation_hints = {
  121. ErrorKind.NOT_CONFIGURED: "Set secrets.command.command in config.yaml to a fast, "
  122. "non-interactive helper that prints KEY=VALUE lines.",
  123. ErrorKind.INTERNAL: "Run the helper manually in a shell to see its real error — "
  124. "Hermes discards helper stderr so diagnostics can't leak "
  125. "secret material.",
  126. }
  127. def config_schema(self) -> dict:
  128. return {
  129. "enabled": {"description": "Master switch", "default": False},
  130. "command": {"description": "Helper run via /bin/sh -c; must print a KEY=VALUE blob on stdout",
  131. "default": ""},
  132. "helper_timeout_seconds": {"description": "Hard timeout for one helper run",
  133. "default": _COMMAND_TIMEOUT_SECONDS},
  134. "override_existing": {"description": "Helper values overwrite .env/shell values", "default": False},
  135. }
  136. def fetch(self, cfg: dict, home_path: Path) -> FetchResult:
  137. cfg = cfg if isinstance(cfg, dict) else {}
  138. result = FetchResult()
  139. command = str(cfg.get("command") or "").strip()
  140. if not command:
  141. return result.fail("secrets.command.enabled is true but secrets.command.command "
  142. "is empty. Set the helper command in config.yaml.", ErrorKind.NOT_CONFIGURED)
  143. if _is_windows():
  144. return result.fail("the 'command' secret source is POSIX-only (needs /bin/sh); skipping on Windows",
  145. ErrorKind.NOT_CONFIGURED)
  146. timeout = coerce_float(cfg.get("helper_timeout_seconds", _COMMAND_TIMEOUT_SECONDS),
  147. _COMMAND_TIMEOUT_SECONDS)
  148. stdout = _run_helper(command, "", timeout, _MAX_OUTPUT_BYTES)
  149. if stdout is None: # _run_helper already logged structured fields
  150. return result.fail("helper command failed (see structured fields above); no secrets applied",
  151. ErrorKind.INTERNAL)
  152. secrets = _parse_dotenv_map(stdout)
  153. if not secrets:
  154. result.warnings.append("helper output was not a KEY=VALUE map; nothing to apply")
  155. return result
  156. result.secrets = secrets
  157. return result