The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(dashboard): accept command-scoped NOPASSWD sudo for system gateway actions
teknium1b2577df8078b
diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.pyindex 2e4cf358a7f..1d02d02578b 100644--- a/hermes_cli/update_cmd_fleet.py+++ b/hermes_cli/update_cmd_fleet.py@@ -853,6 +853,23 @@ def _gateway_home_for_pid(pid: int):return None+def _sudo_noninteractive_ok(targeted_probe: list) -> bool:+ """True when this user can elevate without a prompt.++ ``sudo -n true`` first; a refusal is inconclusive because a NOPASSWD sudoers entry scoped+ to one command (the hardened shape) rejects the blanket probe, so fall back to running+ ``sudo -n <targeted_probe>`` — callers pass a non-destructive stand-in for the argv they+ are about to elevate.+ """+ try:+ if subprocess.run(["sudo", "-n", "true"], capture_output=True, timeout=5).returncode == 0:+ return True+ # Blanket sudo refused — a targeted NOPASSWD sudoers entry may still work.+ return subprocess.run(["sudo", "-n", *targeted_probe], capture_output=True, timeout=5).returncode == 0+ except (OSError, subprocess.TimeoutExpired):+ return False++def _resolve_manage_cmd(cache: dict, scope_: str, scope_cmd_: list, svc_name_: str):"""Resolve the command prefix for manage-units verbs (None ⇒ no privilege path).@@ -868,16 +885,7 @@ def _resolve_manage_cmd(cache: dict, scope_: str, scope_cmd_: list, svc_name_: scmd = scope_cmd_ + ["--no-ask-password"]if _needs_sudo(scope_):sudo_cmd = ["sudo", "-n"] + cmd- try:- sudo_ok = subprocess.run(["sudo", "-n", "true"], capture_output=True, timeout=5).returncode == 0- if not sudo_ok:- # Blanket sudo refused — a targeted NOPASSWD sudoers entry may still work.- sudo_ok = subprocess.run(- sudo_cmd + ["reset-failed", svc_name_], capture_output=True, timeout=5- ).returncode == 0- except (FileNotFoundError, subprocess.TimeoutExpired):- sudo_ok = False- cmd = sudo_cmd if sudo_ok else None+ cmd = sudo_cmd if _sudo_noninteractive_ok(cmd + ["reset-failed", svc_name_]) else Nonecache[scope_] = cmdreturn cmddiff --git a/hermes_cli/web_server_gateway.py b/hermes_cli/web_server_gateway.pyindex df72a2daaff..e928b6d03d5 100644--- a/hermes_cli/web_server_gateway.py+++ b/hermes_cli/web_server_gateway.py@@ -406,7 +406,7 @@ def _action_targets_system_gateway(subcommand: List[str]) -> bool:Scope is decided by the CLI's own picker (``_select_systemd_scope``) evaluated for the profilethe action addresses, not by "a system unit exists": a host carrying both units resolves to theuser unit, which the dashboard user operates unelevated. Same root/sudo posture as the- ``hermes update`` fleet restart (``update_cmd_fleet._needs_sudo``).+ ``hermes update`` fleet restart (``update_cmd_fleet._needs_sudo`` / ``_sudo_noninteractive_ok``)."""from hermes_cli.update_cmd_fleet import _needs_sudo@@ -436,14 +436,6 @@ def _action_targets_system_gateway(subcommand: List[str]) -> bool:reset_hermes_home_override(token)-def _sudo_noninteractive_available() -> bool:- """True when this user can elevate without being prompted (``sudo -n true``)."""- try:- return subprocess.run(["sudo", "-n", "true"], capture_output=True, timeout=5).returncode == 0- except (OSError, subprocess.TimeoutExpired):- return False--def _spawn_hermes_action(subcommand: List[str], name: str, *, env_overrides: Optional[Dict[str, str]] = None) -> subprocess.Popen:@@ -460,8 +452,12 @@ def _spawn_hermes_action(# system install (#110820). Elevate — the CLI is sudo-aware: it adopts the unit's# HERMES_HOME past sudo's env_reset and reads SUDO_USER for the service identity.# ``-n`` never prompts (stdin is DEVNULL anyway); without a passwordless path the- # REQUEST fails instead of reporting a started action whose child refuses.- if not _sudo_noninteractive_available():+ # REQUEST fails instead of reporting a started action whose child refuses. Same+ # two-step gate as the ``hermes update`` fleet restart: a refused blanket probe falls+ # back to ``sudo -l`` on the exact argv, so a command-scoped NOPASSWD entry qualifies.+ from hermes_cli.update_cmd_fleet import _sudo_noninteractive_ok++ if not _sudo_noninteractive_ok(["-l", "--", *cmd]):message = (f"{name} targets the system-scope gateway service, which requires root, and ""passwordless sudo is unavailable for the dashboard user. Run "diff --git a/tests/hermes_cli/test_dashboard_system_gateway_elevation.py b/tests/hermes_cli/test_dashboard_system_gateway_elevation.pyindex 9b50678f8b7..e8097cdbcf7 100644--- a/tests/hermes_cli/test_dashboard_system_gateway_elevation.py+++ b/tests/hermes_cli/test_dashboard_system_gateway_elevation.py@@ -33,16 +33,23 @@ def system_scope_install(monkeypatch, tmp_path):return system_unit, user_unit-def _spawn(tmp_path, subcommand, *, sudo_ok: bool):- """Run ``_spawn_hermes_action(subcommand)`` with Popen (and the ``sudo -n true`` probe) faked;- the elevation decision runs through the production helpers. Returns the attempted argv."""+def _spawn(tmp_path, subcommand, *, sudo_ok: bool, targeted_only: bool = False, probes: list | None = None):+ """Run ``_spawn_hermes_action(subcommand)`` with Popen (and the ``sudo -n`` probes) faked;+ the elevation decision runs through the production helpers. Returns the attempted argv.+ ``targeted_only`` models a command-scoped NOPASSWD sudoers entry: the blanket ``sudo -n true``+ is refused but anything else under ``sudo -n`` is allowed."""from hermes_cli import web_server_gateway- probe = subprocess.CompletedProcess(["sudo", "-n", "true"], 0 if sudo_ok else 1)+ def run(argv, **_kwargs):+ if probes is not None:+ probes.append(list(argv))+ refused = not sudo_ok or (targeted_only and argv[:3] == ["sudo", "-n", "true"])+ return subprocess.CompletedProcess(argv, 1 if refused else 0)+child = MagicMock(spec=subprocess.Popen, pid=4242) # spec'd before Popen is patchedweb_server_gateway._ACTION_LOG_FILES.setdefault("probe", "probe.log")with patch.object(web_server_gateway, "_ACTION_LOG_DIR", tmp_path / "logs"), patch.object(- web_server_gateway.subprocess, "run", return_value=probe+ web_server_gateway.subprocess, "run", side_effect=run), patch.object(web_server_gateway.subprocess, "Popen", return_value=child) as popen, patch.object(web_server_gateway, "_dashboard_spawn_executable", return_value="/venv/bin/python"), patch("hermes_cli.web_server.PROJECT_ROOT", tmp_path):@@ -76,3 +83,13 @@ def test_restart_without_passwordless_sudo_fails_the_request(unprivileged, syste# The endpoint reports Popen success; a child that can only refuse must fail the REQUEST instead.with pytest.raises(RuntimeError, match="passwordless sudo is unavailable"):_spawn(tmp_path, ["gateway", "restart"], sudo_ok=False)+++def test_targeted_nopasswd_sudoers_still_elevates(unprivileged, system_scope_install, tmp_path):+ # Same posture as the ``hermes update`` fleet restart: a refused blanket ``sudo -n true`` is+ # inconclusive; the exact argv is then checked non-destructively (``sudo -n -l -- <argv>``).+ probes: list = []+ argv = _spawn(tmp_path, ["gateway", "restart"], sudo_ok=True, targeted_only=True, probes=probes)+ plain = ["/venv/bin/python", "-m", "hermes_cli.main", "gateway", "restart"]+ assert argv == ["sudo", "-n", *plain]+ assert probes == [["sudo", "-n", "true"], ["sudo", "-n", "-l", "--", *plain]]