diff --git a/hermes_cli/_secrets_common.py b/hermes_cli/_secrets_common.py index 68bc6ba1d4..f6e8121b43 100644 --- a/hermes_cli/_secrets_common.py +++ b/hermes_cli/_secrets_common.py @@ -8,12 +8,14 @@ from __future__ import annotations import argparse import os +import re import subprocess import sys from pathlib import Path from typing import Callable, Iterable, Optional, Sequence from rich.console import Console +from rich.markup import escape as _escape_markup from rich.panel import Panel from rich.table import Table @@ -21,6 +23,19 @@ from hermes_cli.config import load_config, save_config from hermes_cli.secret_prompt import masked_secret_prompt +_CONTROL_CHARS_RE = re.compile(r"[\x00-\x08\x0b-\x1f\x7f-\x9f]") + + +def console_safe(text: str) -> str: + """Make externally-derived text safe for a markup console. + + Strips terminal control characters (C0 other than tab/newline, DEL, C1) so + embedded ANSI/OSC sequences cannot reach the terminal, then escapes Rich + markup so ``[...]`` sequences print literally. + """ + return _escape_markup(_CONTROL_CHARS_RE.sub("", text)) + + def yn(b: bool) -> str: return "[green]yes[/green]" if b else "[dim]no[/dim]" @@ -88,7 +103,7 @@ def print_table(console: Console, columns: Sequence, rows: Iterable, table.add_row(*row) console.print(table) for w in warnings: - console.print(f"{indent}[yellow]warning:[/yellow] {w}") + console.print(f"{indent}[yellow]warning:[/yellow] {console_safe(w)}") def cli_version(binary: Path) -> str: diff --git a/hermes_cli/onepassword_secrets_cli.py b/hermes_cli/onepassword_secrets_cli.py index 69365a769d..3360e769e3 100644 --- a/hermes_cli/onepassword_secrets_cli.py +++ b/hermes_cli/onepassword_secrets_cli.py @@ -21,6 +21,7 @@ from hermes_cli._secrets_common import ( arg, cfg_str, cli_version, + console_safe, disable_secret_source, flag, print_status_panel, @@ -132,7 +133,7 @@ def cmd_setup(args: argparse.Namespace) -> int: else: who = _op_whoami(binary, op_cfg.get("account", "")) if who: - console.print(f" [green]✓[/green] using existing op session ({who})") + console.print(f" [green]✓[/green] using existing op session ({console_safe(who)})") else: console.print( " [yellow]No service-account token and no active op session " @@ -192,7 +193,7 @@ def cmd_status(args: argparse.Namespace) -> int: if binary and not token_set: who = _op_whoami(binary, account) if who: - console.print(f"\n [green]Active op session:[/green] {who}") + console.print(f"\n [green]Active op session:[/green] {console_safe(who)}") else: console.print( f"\n [yellow]No active op session and {token_env} is unset — " @@ -212,7 +213,7 @@ def cmd_set(args: argparse.Namespace) -> int: valid, warnings = op_src._validate_references({args.env_var: args.reference}) if args.env_var not in valid: for w in warnings: - console.print(f"[red]{w}[/red]") + console.print(f"[red]{console_safe(w)}[/red]") return 1 cfg = load_config() @@ -266,7 +267,7 @@ def cmd_token(args: argparse.Namespace) -> int: if who is None: console.print("[red]✗ New token was rejected by op — nothing was changed.[/red]") return False - console.print(f"[green]✓ Token accepted[/green] ({who}).") + console.print(f"[green]✓ Token accepted[/green] ({console_safe(who)}).") return True return rotate_token( @@ -316,7 +317,7 @@ def cmd_sync(args: argparse.Namespace) -> int: cache_ttl_seconds=0, # an explicit sync always resolves fresh ) if result.error: - console.print(f"[red]{result.error}[/red]") + console.print(f"[red]{console_safe(result.error)}[/red]") return 1 print_table( console, (("Env var", {"style": "cyan"}), "Action"), @@ -337,7 +338,7 @@ def cmd_sync(args: argparse.Namespace) -> int: use_cache=False, ) except RuntimeError as exc: - console.print(f"[red]{exc}[/red]") + console.print(f"[red]{console_safe(str(exc))}[/red]") return 1 override = bool(op_cfg.get("override_existing", True)) diff --git a/hermes_cli/secrets_cli.py b/hermes_cli/secrets_cli.py index c31ac8f48b..1bff5972ac 100644 --- a/hermes_cli/secrets_cli.py +++ b/hermes_cli/secrets_cli.py @@ -17,9 +17,9 @@ from rich.table import Table from hermes_constants import is_launch_only_env_key from hermes_cli._secrets_common import ( - arg, cfg_str, cli_version, disable_secret_source, flag, print_status_panel, print_table, - prompt_index, register_subcommands, require_enabled, rotate_token, secret_cli_env, section_cfg, - yn, + arg, cfg_str, cli_version, console_safe, disable_secret_source, flag, print_status_panel, + print_table, prompt_index, register_subcommands, require_enabled, rotate_token, secret_cli_env, + section_cfg, yn, ) from hermes_cli.config import get_env_path, load_config, save_config, save_env_value from hermes_cli.secret_prompt import masked_secret_prompt @@ -150,7 +150,8 @@ def _setup_project(binary: Path, token: str, console: Console, server_url: str) "and grant it access to at least one project.") return None print_table(console, (("#", {"style": "cyan", "width": 4}), "Name", ("ID", {"style": "dim"})), - ((str(i), p.get("name", "?"), p.get("id", "?")) for i, p in enumerate(projects, 1))) + ((str(i), console_safe(str(p.get("name", "?"))), console_safe(str(p.get("id", "?")))) + for i, p in enumerate(projects, 1))) idx = prompt_index(console, f" Select project [1-{len(projects)}]: ", len(projects)) return projects[idx - 1]["id"] @@ -209,9 +210,9 @@ def cmd_setup(args: argparse.Namespace) -> int: console.print(" [yellow]Fetch succeeded but the project has no secrets.[/yellow]") else: print_table(console, (("Name", {"style": "cyan"}), "Status"), - ((key, _fetch_status(key, token_env)) for key in sorted(secrets))) + ((console_safe(key), _fetch_status(key, token_env)) for key in sorted(secrets))) for w in warnings: - console.print(f" [yellow]warning:[/yellow] {w}") + console.print(f" [yellow]warning:[/yellow] {console_safe(w)}") secrets_cfg.update(enabled=True, project_id=project_id, server_url=server_url) for key, default in (("access_token_env", token_env), ("cache_ttl_seconds", 300), ("override_existing", True), ("auto_install", True)): @@ -348,7 +349,7 @@ def cmd_sync(args: argparse.Namespace) -> int: access_token=token, project_id=project_id, use_cache=False, server_url=cfg_str(bw_cfg, "server_url"), ) except Exception as exc: - console.print(f"[red]Fetch failed: {exc}[/red]") + console.print(f"[red]Fetch failed: {console_safe(str(exc))}[/red]") return 1 if not secrets: console.print("[yellow]No secrets in project.[/yellow]") @@ -370,7 +371,7 @@ def cmd_sync(args: argparse.Namespace) -> int: action = "[green]exported[/green]" + (" (overrode)" if already else "") else: action = "[green]would export[/green]" + (" (overrides)" if already else "") - rows.append((key, action)) + rows.append((console_safe(key), action)) print_table(console, (("Name", {"style": "cyan"}), "Action"), rows, warnings) if not args.apply: console.print("\n This was a dry-run — secrets are picked up automatically on the " @@ -423,7 +424,9 @@ def _token_validation_status( # they must not be left with. details = probe_console.export_text(styles=False).strip() if details: - messages.extend(line.rstrip() for line in details.splitlines()) + # The exported lines are plain text: re-escape so console.print does not + # re-parse literal markup the probe rendered verbatim. + messages.extend(console_safe(line.rstrip()) for line in details.splitlines()) if projects is None: return "[red]failed[/red]", messages return "[green]passed[/green]", messages @@ -456,11 +459,11 @@ def _list_projects( [str(binary), "project", "list", "--output", "json"], env=env, capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=15, check=False) except (OSError, subprocess.TimeoutExpired) as exc: - console.print(f" [red]Couldn't list projects: {exc}[/red]") + console.print(f" [red]Couldn't list projects: {console_safe(str(exc))}[/red]") return None if res.returncode != 0: err = (res.stderr or res.stdout).strip()[:300] - console.print(f" [red]bws project list failed: {err}[/red]") + console.print(f" [red]bws project list failed: {console_safe(err)}[/red]") lowered = err.lower() for needles, hint in _PROJECT_LIST_HINTS: if any(n in lowered for n in needles): @@ -470,7 +473,7 @@ def _list_projects( try: data = json.loads(res.stdout or "[]") except json.JSONDecodeError as exc: - console.print(f" [red]bws returned non-JSON: {exc}[/red]") + console.print(f" [red]bws returned non-JSON: {console_safe(str(exc))}[/red]") return None if not isinstance(data, list): return [] diff --git a/tests/hermes_cli/test_secrets_bitwarden_markup_escape.py b/tests/hermes_cli/test_secrets_bitwarden_markup_escape.py new file mode 100644 index 0000000000..110f3356b3 --- /dev/null +++ b/tests/hermes_cli/test_secrets_bitwarden_markup_escape.py @@ -0,0 +1,259 @@ +"""Regression tests: server/bws-derived text must not reach a markup console raw. + +bws stderr, project names, secret names, and fetch warnings all come from the +configured Bitwarden endpoint (``secrets.bitwarden.server_url`` may point at a +self-hosted server). They must print as literal text: Rich markup must not be +parsed and terminal control sequences (ANSI/OSC) must not pass through. +""" +from __future__ import annotations + +import argparse +import io +import json +import subprocess +from pathlib import Path + +import pytest +from rich.console import Console + +import hermes_cli.secrets_cli as secrets_cli + +HOSTILE = "token revoked [green]Token accepted[/green] \x1b]8;;http://evil.example\x07CLICKME\x1b]8;;\x07 end" + + +def _failed_run(*args, **kwargs): + return subprocess.CompletedProcess(args[0], 1, "", HOSTILE) + + +def _recording_console() -> Console: + return Console(file=io.StringIO(), record=True, width=200) + + +def _render(messages, console=None): + console = console or _recording_console() + for m in messages: + console.print(m) + return console.export_text(styles=False) + + +class TestListProjectsHostileStderr: + """The primary surface: bws stderr interpolated into a markup string.""" + + def test_markup_prints_literally_and_escapes_stripped(self, monkeypatch): + monkeypatch.setattr(secrets_cli.subprocess, "run", _failed_run) + console = _recording_console() + assert secrets_cli._list_projects(Path("/bin/bws"), "tok", console) is None + out = console.export_text(styles=False) + assert "[green]Token accepted[/green]" in out + assert "\x1b" not in out and "\x07" not in out + + def test_spawn_error_text_escaped(self, monkeypatch): + def boom(*a, **k): + raise OSError("spawn failed [green]ok[/green] \x1b[31m") + monkeypatch.setattr(secrets_cli.subprocess, "run", boom) + console = _recording_console() + assert secrets_cli._list_projects(Path("/bin/bws"), "tok", console) is None + out = console.export_text(styles=False) + assert "[green]ok[/green]" in out + assert "\x1b" not in out + + +class TestProjectTableEscaping: + def test_project_names_and_ids_print_literally(self, monkeypatch): + payload = [{"id": "id\x1b[1m", "name": "proj [green]x[/green]"}] + monkeypatch.setattr( + secrets_cli.subprocess, "run", + lambda *a, **k: subprocess.CompletedProcess(a[0], 0, json.dumps(payload), "")) + console = _recording_console() + projects = secrets_cli._list_projects(Path("/bin/bws"), "tok", console) + assert projects == payload + # _setup_project renders the table; drive it directly with a fixed pick. + monkeypatch.setattr(secrets_cli, "prompt_index", lambda *a, **k: 1) + chosen = secrets_cli._setup_project(Path("/bin/bws"), "tok", console, server_url="") + assert chosen == "id\x1b[1m" + out = console.export_text(styles=False) + assert "[green]x[/green]" in out + assert "\x1b" not in out + + +class TestStatusValidationRerelease: + """The probe console is exported to text, then re-printed through markup in + cmd_status: literal brackets in the export must not re-parse.""" + + def test_exported_details_survive_reprint_literally(self, monkeypatch): + monkeypatch.setattr(secrets_cli.subprocess, "run", _failed_run) + status, messages = secrets_cli._token_validation_status( + enabled=True, binary=Path("/bin/bws"), token="0.abc", server_url="") + assert status == "[red]failed[/red]" + out = _render(messages) + assert "[green]Token accepted[/green]" in out + assert "\x1b" not in out + + +class TestSetupAndSyncSurfaces: + def _setup_stubs(self, monkeypatch, secrets, warnings): + monkeypatch.setattr("sys.stdin.isatty", lambda: False) + monkeypatch.setattr(secrets_cli.bw, "find_bws", + lambda install_if_missing=False: Path("/bin/bws")) + monkeypatch.setattr(secrets_cli, "_bws_version", lambda _b: "2.0.0") + monkeypatch.setattr(secrets_cli.bw, "fetch_bitwarden_secrets", + lambda **k: (secrets, warnings)) + monkeypatch.setattr(secrets_cli, "save_config", lambda _c: None) + monkeypatch.setattr(secrets_cli, "load_config", lambda: {}) + + def test_setup_escapes_secret_names_and_warnings(self, monkeypatch, capsys): + hostile_key = "K[green]spoof[/green]" + self._setup_stubs( + monkeypatch, + {hostile_key: "v"}, + ["Skipping secret 'n[red]x[/red]': not a valid env-var name \x1b]8;;u\x07"], + ) + monkeypatch.setattr(secrets_cli.subprocess, "run", + lambda *a, **k: subprocess.CompletedProcess( + a[0], 0, json.dumps([{"id": "p1", "name": "n"}]), "")) + args = argparse.Namespace(access_token="0.t", server_url="https://vault.example", + project_id="p1") + assert secrets_cli.cmd_setup(args) == 0 + out = capsys.readouterr().out + assert "[green]spoof[/green]" in out + assert "[red]x[/red]" in out + assert "\x1b" not in out and "\x07" not in out + + def test_sync_escapes_secret_names_and_warnings(self, monkeypatch, capsys): + hostile_key = "K[green]spoof[/green]" + monkeypatch.setattr( + secrets_cli, "load_config", + lambda: {"secrets": {"bitwarden": {"enabled": True, "project_id": "p1", + "access_token_env": "BWS_ACCESS_TOKEN"}}}) + monkeypatch.setenv("BWS_ACCESS_TOKEN", "0.t") + monkeypatch.setattr(secrets_cli.bw, "fetch_bitwarden_secrets", + lambda **k: ({hostile_key: "v"}, ["w [green]x[/green] \x1b[31m"])) + args = argparse.Namespace(apply=False) + assert secrets_cli.cmd_sync(args) == 0 + out = capsys.readouterr().out + assert "[green]spoof[/green]" in out + assert "[green]x[/green]" in out + assert "\x1b" not in out + + def test_sync_fetch_error_text_escaped(self, monkeypatch, capsys): + monkeypatch.setattr( + secrets_cli, "load_config", + lambda: {"secrets": {"bitwarden": {"enabled": True, "project_id": "p1", + "access_token_env": "BWS_ACCESS_TOKEN"}}}) + monkeypatch.setenv("BWS_ACCESS_TOKEN", "0.t") + + def boom(**k): + raise RuntimeError("bws failed [green]ok[/green] \x1b]8;;u\x07") + monkeypatch.setattr(secrets_cli.bw, "fetch_bitwarden_secrets", boom) + args = argparse.Namespace(apply=False) + assert secrets_cli.cmd_sync(args) == 1 + out = capsys.readouterr().out + assert "[green]ok[/green]" in out + assert "\x1b" not in out and "\x07" not in out + + +class TestStatusAuthoredMarkupBoundary: + """Only probe-derived lines get escaped; authored markup in the messages + list (the '0.' prefix warning) must still render as markup.""" + + def test_authored_warning_renders_while_injected_stays_literal(self, monkeypatch): + monkeypatch.setattr(secrets_cli.subprocess, "run", _failed_run) + status, messages = secrets_cli._token_validation_status( + enabled=True, binary=Path("/bin/bws"), token="not-a-bsm-token", + server_url="") + assert status == "[red]failed[/red]" + out = _render(messages) + # authored [yellow] markup rendered (not shown literally) + assert "[yellow]" not in out + assert "doesn't start with '0.'" in out + # injected markup stayed literal + assert "[green]Token accepted[/green]" in out + + def test_hint_matching_uses_unescaped_stderr(self, monkeypatch): + """_PROJECT_LIST_HINTS must match the raw stderr: a fix that escaped + before matching would silently drop the hints.""" + monkeypatch.setattr( + secrets_cli.subprocess, "run", + lambda *a, **k: subprocess.CompletedProcess( + a[0], 1, "", "Error: invalid_client [green]x[/green]")) + console = _recording_console() + assert secrets_cli._list_projects(Path("/bin/bws"), "tok", console) is None + out = console.export_text(styles=False) + assert "invalid_client" in out + assert "from the US identity endpoint" in out + assert "[green]x[/green]" in out + + +class TestTokenCommandE2E: + """`bitwarden token --access-token` verifies through _list_projects on the + real console — the exact spot where a spoofed 'Token accepted' misleads.""" + + def test_token_verify_hostile_stderr_literal(self, monkeypatch, capsys): + import argparse as _ap + + from hermes_cli.subcommands.secrets import build_secrets_parser + monkeypatch.setattr( + secrets_cli, "load_config", + lambda: {"secrets": {"bitwarden": {"enabled": True, "project_id": "p1", + "access_token_env": "BWS_ACCESS_TOKEN"}}}) + monkeypatch.setattr(secrets_cli.bw, "find_bws", + lambda install_if_missing=True: Path("/bin/bws")) + monkeypatch.setattr(secrets_cli.subprocess, "run", _failed_run) + saved = [] + monkeypatch.setattr(secrets_cli, "save_env_value", + lambda k, v: saved.append((k, v))) + parser = _ap.ArgumentParser() + build_secrets_parser(parser.add_subparsers()) + args = parser.parse_args( + ["secrets", "bitwarden", "token", "--access-token", "0.new"]) + assert args.func(args) == 1 + assert saved == [] # rejected token must not persist + out = capsys.readouterr().out + assert "[green]Token accepted[/green]" in out + assert "\x1b" not in out and "\x07" not in out + + +class TestOnepasswordSiblingSurfaces: + """Same defect class in the 1Password secrets CLI (op stderr/server text).""" + + def test_sync_fetch_error_text_escaped(self, monkeypatch, capsys): + import hermes_cli.onepassword_secrets_cli as op_cli + + monkeypatch.setattr( + op_cli, "load_config", + lambda: {"secrets": {"onepassword": { + "enabled": True, "env": {"K": "op://v/i/f"}}}}) + + def boom(**k): + raise RuntimeError("op failed [green]ok[/green] \x1b]8;;u\x07") + monkeypatch.setattr(op_cli.op_src, "fetch_onepassword_secrets", boom) + args = argparse.Namespace(apply=False) + assert op_cli.cmd_sync(args) == 1 + out = capsys.readouterr().out + assert "[green]ok[/green]" in out + assert "\x1b" not in out and "\x07" not in out + + +class TestStatusCommandE2E: + """Real parser + dispatcher: hermes secrets bitwarden status.""" + + def test_status_e2e_hostile_stderr_literal(self, monkeypatch, capsys): + import argparse as _ap + + from hermes_cli.subcommands.secrets import build_secrets_parser + monkeypatch.setattr( + secrets_cli, "load_config", + lambda: {"secrets": {"bitwarden": {"enabled": True, "project_id": "p1", + "access_token_env": "BWS_ACCESS_TOKEN"}}}) + monkeypatch.setenv("BWS_ACCESS_TOKEN", "0.t") + monkeypatch.setattr(secrets_cli.bw, "find_bws", + lambda install_if_missing=False: Path("/bin/bws")) + monkeypatch.setattr(secrets_cli, "_bws_version", lambda _b: "2.0.0") + monkeypatch.setattr(secrets_cli.subprocess, "run", _failed_run) + parser = _ap.ArgumentParser() + build_secrets_parser(parser.add_subparsers()) + args = parser.parse_args(["secrets", "bitwarden", "status"]) + assert args.func(args) == 0 + out = capsys.readouterr().out + assert "[green]Token accepted[/green]" in out + assert "\x1b" not in out and "\x07" not in out