The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: decode shell escapes in the systemctl guard and exempt only test-owned units
unsupportedpastels450ad5055eb3
diff --git a/tests/_fixtures/live_system_guard.py b/tests/_fixtures/live_system_guard.pyindex 18fb5ac1d19..5c3531068f8 100644--- a/tests/_fixtures/live_system_guard.py+++ b/tests/_fixtures/live_system_guard.py@@ -223,10 +223,23 @@ def _live_system_guard(request, monkeypatch):low = cmd_str.lower()return any(tok in low for tok in _HERMES_TOKENS)- def _shell_words(cmd_str: str) -> list[str]:+ def _shell_words(cmd_str: str, depth: int = 0) -> set[str]:# Split on whitespace AND quoting/shell punctuation so a unit or verb- # inside ``bash -c "systemctl restart hermes-dashboard"`` is still a word.- return [w for w in _re.split(r"[\s'\"`;&|()<>]+", cmd_str) if w]+ # inside ``bash -c "systemctl restart hermes-dashboard"`` is still a word,+ # and keep the shell's own reading too: ``rest\\art`` runs ``restart``.+ words: set[str] = set()+ for w in _re.split(r"[\s'\"`;&|()<>]+", cmd_str):+ if w:+ words.update((w, w.replace("\\", "")))+ try:+ tokens = _shlex.split(cmd_str)+ except ValueError:+ tokens = []+ for token in tokens:+ words.add(token)+ if depth < 2 and token != cmd_str and _re.search(r"\s", token):+ words |= _shell_words(token, depth + 1) # a ``bash -c`` payload+ return wordsdef _is_hermes_unit(word: str) -> bool:# ``hermes`` / ``hermes-<anything>`` once any path and unit suffix are@@ -242,7 +255,11 @@ def _live_system_guard(request, monkeypatch):if "systemctl" not in cmd_str:return Falsewords = _shell_words(cmd_str)- if not (_matches_hermes_gateway(cmd_str) or any(_is_hermes_unit(w) for w in words)):+ # A unit the test itself created under a unique name (``request.node.+ # live_system_guard_owned_units``) may be cleaned up; nothing else is exempt.+ owned = getattr(request.node, "live_system_guard_owned_units", ())+ if not (_matches_hermes_gateway(cmd_str)+ or any(_is_hermes_unit(w) and w not in owned for w in words)):return Falsereturn any(verb in words for verb in _MUTATING_VERBS)diff --git a/tests/hermes_cli/test_kanban_gateway_restart_handoff.py b/tests/hermes_cli/test_kanban_gateway_restart_handoff.pyindex 3c17fb3730b..25aecc32840 100644--- a/tests/hermes_cli/test_kanban_gateway_restart_handoff.py+++ b/tests/hermes_cli/test_kanban_gateway_restart_handoff.py@@ -194,6 +194,7 @@ def test_oneshot_unit_dispatcher_scope_wraps_or_warns_never_dooms_silently(@pytest.mark.platforms("linux")def test_real_user_systemd_scope_preserves_worker_context(+ request,worker_setup: tuple[Path, kb.Task], monkeypatch: pytest.MonkeyPatch) -> None:from tools import process_registry@@ -207,6 +208,8 @@ def test_real_user_systemd_scope_preserves_worker_context(# User-manager transient units outlive pytest's temporary directories.task = replace(task, id=f"t_candidate_{uuid4().hex}")unit = f"hermes-worker-kanban-{task.id}-run-{task.current_run_id}.scope"+ # Only this freshly named scope is test-owned; the live-system guard still refuses every other unit.+ request.node.live_system_guard_owned_units = {unit}receipt = workspace / "worker-receipt.json"script = ("import json, os, pathlib, sys, time; "diff --git a/tests/hermes_cli/test_update_stale_dashboard.py b/tests/hermes_cli/test_update_stale_dashboard.pyindex 0e9c510dccf..143f0221000 100644--- a/tests/hermes_cli/test_update_stale_dashboard.py+++ b/tests/hermes_cli/test_update_stale_dashboard.py@@ -125,7 +125,9 @@ def test_update_cleanup_spares_backend_owned_by_valid_ssh_lock(tmp_path, monkeypresult = _kill_stale_dashboard_processes(restart_managed=True)assert result == {"matched": [], "killed": [], "failed": []}- assert calls and all(call[:1] == ["systemctl"] and "list-unit-files" in call for call in calls)+ assert all(call[:1] == ["systemctl"] and "list-unit-files" in call for call in calls)+ # Windows has no systemd: the managed-unit probe returns before running anything.+ assert bool(calls) == (sys.platform != "win32")def test_explicit_stop_does_not_spare_backend_owned_by_valid_ssh_lock(diff --git a/tests/test_live_system_guard_self_test.py b/tests/test_live_system_guard_self_test.pyindex fcc1b638d63..24376180300 100644--- a/tests/test_live_system_guard_self_test.py+++ b/tests/test_live_system_guard_self_test.py@@ -189,6 +189,33 @@ def test_subprocess_run_systemctl_read_only_or_foreign_unit_passes_guard(cmd):subprocess.run(cmd, env={"PATH": "/nonexistent"}, check=False)+ "cmd",+ [+ ["bash", "-c", r"systemctl st\op hermes.service"],+ ["bash", "-c", r"systemctl --user rest\art hermes-dashboard"],+ r"systemctl --user re\start hermes-serve.service",+ ["bash", "-c", "sh -c 'systemctl --user restart hermes-dashboard'"],+ ],+)+def test_subprocess_run_shell_escaped_or_nested_verb_blocked(cmd):+ """The shell runs ``rest\\art`` as ``restart``; the guard must read it the same way."""+ with pytest.raises(RuntimeError, match="live-system guard"):+ subprocess.run(cmd, shell=isinstance(cmd, str), check=False)+++def test_a_test_owned_unit_can_be_cleaned_up_but_no_other(request):+ """A unit the test created under its own name may be stopped; every other Hermes unit stays refused."""+ owned = "hermes-worker-kanban-t_selftest-run-1.scope"+ request.node.live_system_guard_owned_units = {owned}+ with pytest.raises(FileNotFoundError):+ subprocess.run(["systemctl", "--user", "stop", owned], env={"PATH": "/nonexistent"}, check=False)+ with pytest.raises(RuntimeError, match="live-system guard"):+ subprocess.run(["systemctl", "--user", "stop", owned, "hermes-dashboard.service"], check=False)+ with pytest.raises(RuntimeError, match="live-system guard"):+ subprocess.run(["systemctl", "--user", "stop", "hermes-worker-kanban-other-run-1.scope"], check=False)++def test_subprocess_run_setsid_systemctl_blocked():with pytest.raises(RuntimeError, match="live-system guard"):subprocess.run(["setsid", "systemctl", "kill", "hermes-gateway"], check=False)