Skip to content

The agent that grows with you

fix(dashboard): elevate system-scope gateway lifecycle actions (#110820)

Baris Sencaneaf700c67e4c
diff --git a/hermes_cli/web_server_gateway.py b/hermes_cli/web_server_gateway.py
index 63aacbded8a..a96873a85e2 100644
--- a/hermes_cli/web_server_gateway.py
+++ b/hermes_cli/web_server_gateway.py
@@ -395,6 +395,52 @@ def _profile_action_environment(
return action_env
+# Gateway lifecycle verbs the CLI refuses below root on a system-scope install
+# (``gateway.py::_require_root_for_system_service``).
+_ROOT_REQUIRING_GATEWAY_VERBS = frozenset({"restart", "start", "stop"})
+
+
+def _action_targets_system_gateway(subcommand: List[str]) -> bool:
+ """True when *subcommand* is a gateway lifecycle verb that resolves to the SYSTEM unit.
+
+ Scope is decided by the CLI's own picker (``_select_systemd_scope``) evaluated for the profile
+ the action addresses, not by "a system unit exists": a host carrying both units resolves to the
+ user unit, which the dashboard user operates unelevated. Root already has the privilege.
+ """
+ if not hasattr(os, "geteuid") or os.geteuid() == 0:
+ return False
+ try:
+ verb = subcommand[subcommand.index("gateway") + 1]
+ except (ValueError, IndexError):
+ return False
+ if verb not in _ROOT_REQUIRING_GATEWAY_VERBS:
+ return False
+
+ from hermes_cli.gateway import _select_systemd_scope
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ profile = _named_profile_from_action(subcommand)
+ if profile is None:
+ return _select_systemd_scope(False)
+ # Unit names are derived from HERMES_HOME, so a selector-bearing action must be resolved
+ # against the TARGET profile's home (``-p default gateway restart`` from a pooled named
+ # dashboard asks about the default unit, not about its own).
+ from hermes_cli.web_server_profiles import _resolve_profile_dir
+ token = set_hermes_home_override(_resolve_profile_dir(profile))
+ try:
+ return _select_systemd_scope(False)
+ finally:
+ 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:
@@ -405,6 +451,23 @@ def _spawn_hermes_action(
log_file.write(f"\n=== {name} started {time.strftime('%Y-%m-%d %H:%M:%S')} ===\n".encode())
cmd = [_dashboard_spawn_executable(), "-m", "hermes_cli.main", *subcommand]
+ if _action_targets_system_gateway(subcommand):
+ # A system-scope lifecycle verb spawned as the dashboard's own user can only ever write
+ # "System gateway <verb> requires root" into this log, so the button never worked on a
+ # 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():
+ message = (
+ f"{name} targets the system-scope gateway service, which requires root, and "
+ "passwordless sudo is unavailable for the dashboard user. Run "
+ f"'sudo hermes {' '.join(subcommand)}' on the host, or grant that user NOPASSWD sudo."
+ )
+ log_file.write(f"{message}\n".encode())
+ log_file.close()
+ raise RuntimeError(message)
+ cmd = ["sudo", "-n", *cmd]
# Named-profile actions get a scrubbed, pinned environment so the child cannot inherit the
# dashboard profile's credentials; see _profile_action_environment (also drops _HERMES_GATEWAY).
action_env = _profile_action_environment(subcommand, env_overrides)
diff --git a/tests/hermes_cli/test_dashboard_system_gateway_elevation.py b/tests/hermes_cli/test_dashboard_system_gateway_elevation.py
new file mode 100644
index 00000000000..7c3d816a055
--- /dev/null
+++ b/tests/hermes_cli/test_dashboard_system_gateway_elevation.py
@@ -0,0 +1,116 @@
+"""Dashboard gateway lifecycle actions must elevate on a system-scope install.
+
+Regression for #110820: the Restart Gateway button spawned ``hermes gateway restart`` as the
+dashboard's own user, and the CLI refuses system-scope verbs below root, so the button could
+never work on a systemd *system* install — the refusal only reached the action log while the
+endpoint reported a started action.
+"""
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+
+def unprivileged(monkeypatch):
+ """Run the predicate as a non-root user (CI containers can be root)."""
+ monkeypatch.setattr("os.geteuid", lambda: 1000)
+
+
+def system_scope_install(monkeypatch, tmp_path):
+ """Only the SYSTEM unit is installed, the shape that needs root."""
+ system_unit = tmp_path / "etc" / "hermes-gateway.service"
+ system_unit.parent.mkdir(parents=True)
+ system_unit.write_text("[Service]\n")
+ user_unit = tmp_path / "user" / "hermes-gateway.service"
+ monkeypatch.setattr(
+ "hermes_cli.gateway.get_systemd_unit_path",
+ lambda system=False: system_unit if system else user_unit,
+ )
+ return system_unit, user_unit
+
+
+def _spawn_restart(tmp_path, *, sudo_ok: bool):
+ """Run ``_spawn_hermes_action(["gateway", "restart"])`` with the world stubbed out.
+
+ Returns ``(argv, log_text)`` for the attempted spawn; Popen is the only thing faked, so
+ the elevation decision runs through the production helpers.
+ """
+ from hermes_cli import web_server_gateway
+
+ logs = tmp_path / "logs"
+ probe = subprocess.CompletedProcess(["sudo", "-n", "true"], 0 if sudo_ok else 1)
+ child = MagicMock(spec=subprocess.Popen, pid=4242) # spec'd before Popen is patched
+ with patch.object(web_server_gateway, "_ACTION_LOG_DIR", logs), patch.object(
+ web_server_gateway.subprocess, "run", return_value=probe
+ ), patch.object(web_server_gateway.subprocess, "Popen") as popen, patch.object(
+ web_server_gateway, "_dashboard_spawn_executable", return_value="/venv/bin/python"
+ ), patch.object(web_server_gateway, "PROJECT_ROOT", tmp_path, create=True), patch(
+ "hermes_cli.web_server.PROJECT_ROOT", tmp_path
+ ):
+ popen.return_value = child
+ try:
+ web_server_gateway._spawn_hermes_action(["gateway", "restart"], "gateway-restart")
+ finally:
+ log_file = logs / "gateway-restart.log"
+ log_text = log_file.read_text() if log_file.exists() else ""
+ argv = popen.call_args.args[0] if popen.call_args else None
+ return argv, log_text
+
+
+class TestSystemScopeGatewayActionsElevate:
+ def test_restart_on_a_system_install_is_spawned_under_sudo(
+ self, unprivileged, system_scope_install, tmp_path
+ ):
+ argv, _log_text = _spawn_restart(tmp_path, sudo_ok=True)
+ assert argv[:2] == ["sudo", "-n"], (
+ "a system-scope restart spawned as the dashboard user can only be refused by the CLI"
+ )
+ assert argv[2:] == ["/venv/bin/python", "-m", "hermes_cli.main", "gateway", "restart"]
+
+ def test_restart_without_passwordless_sudo_fails_the_request(
+ self, unprivileged, system_scope_install, tmp_path
+ ):
+ with pytest.raises(RuntimeError, match="passwordless sudo is unavailable"):
+ _spawn_restart(tmp_path, sudo_ok=False)
+
+ def test_a_user_scope_install_is_never_elevated(self, unprivileged, system_scope_install, tmp_path):
+ _system_unit, user_unit = system_scope_install
+ user_unit.parent.mkdir(parents=True)
+ user_unit.write_text("[Service]\n") # both units installed -> the CLI picks user scope
+ argv, _log_text = _spawn_restart(tmp_path, sudo_ok=True)
+ assert argv[0] == "/venv/bin/python", "user-scope verbs need no privilege"
+
+
+class TestElevationPredicateScope:
+ """Only the lifecycle verbs the CLI gates on root elevate."""
+
+ @pytest.mark.parametrize(
+ "subcommand, elevated",
+ [
+ (["gateway", "restart"], True),
+ (["-p", "default", "gateway", "start"], True),
+ (["gateway", "stop"], True),
+ (["gateway", "status"], False),
+ (["gateway", "migrate", "--multiplex", "--yes"], False),
+ (["doctor"], False),
+ (["gateway"], False),
+ ],
+ )
+ def test_verbs(self, unprivileged, system_scope_install, monkeypatch, subcommand, elevated, tmp_path):
+ from hermes_cli import web_server_gateway
+
+ monkeypatch.setattr(
+ "hermes_cli.web_server_profiles._resolve_profile_dir", lambda name: Path(tmp_path) / name
+ )
+ assert web_server_gateway._action_targets_system_gateway(subcommand) is elevated
+
+ def test_root_does_not_shell_out_to_sudo(self, system_scope_install, monkeypatch):
+ from hermes_cli import web_server_gateway
+
+ monkeypatch.setattr("os.geteuid", lambda: 0)
+ assert web_server_gateway._action_targets_system_gateway(["gateway", "restart"]) is False