fix(dashboard): accept command-scoped NOPASSWD sudo for system gateway actions

The dashboard's system-scope elevation gate hard-failed on a refused
`sudo -n true`, but the `hermes update` fleet restart it claims to
mirror treats that blanket probe as inconclusive and falls back to
probing the targeted command. A host with a sudoers entry scoped to
the hermes command (the hardened shape) therefore updated fine from
the CLI while the dashboard reported "passwordless sudo is
unavailable".

Factor the fleet's two-step probe into update_cmd_fleet
._sudo_noninteractive_ok and call it from both sites: the fleet keeps
its `reset-failed <unit>` fallback, the dashboard falls back to a
non-destructive `sudo -n -l -- <exact argv>` check before spawning.

Review finding: dashboard sudo gate diverged from the fleet posture it
borrowed (_needs_sudo only) and rejected targeted NOPASSWD sudoers.
This commit is contained in:
teknium1
2026-09-14 20:59:29 -07:00
committed by Teknium
parent 05fb879609
commit b2577df807
3 changed files with 47 additions and 26 deletions
+18 -10
View File
@@ -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_: s
cmd = 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 None
cache[scope_] = cmd
return cmd
+7 -11
View File
@@ -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 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. 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 "
@@ -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 patched
web_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]]