Skip to content

The agent that grows with you

fix(cron): derive the user bus env per probe and scoped spawn

ckommabe9c2bd19cb7
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 70c1a169eea..2126f728879 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -3166,7 +3166,10 @@ def _launch_external_cron_worker(job: dict) -> bool:
from agent.secret_scope import is_multiplex_active
from tools.environments.local import build_subprocess_env
- from tools.process_registry import restart_safe_gateway_child_argv
+ from tools.process_registry import (
+ restart_safe_gateway_child_argv,
+ systemd_user_bus_env,
+ )
multiplex_active = is_multiplex_active()
scoped_command = restart_safe_gateway_child_argv(
@@ -3208,6 +3211,7 @@ def _launch_external_cron_worker(job: dict) -> bool:
inherit_profile_home=True,
extra={"HERMES_HOME": str(_get_hermes_home().resolve())},
)
+ worker_env = systemd_user_bus_env(worker_env)
try:
process = subprocess.Popen(
scoped_command,
diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.py
index 8d63565b686..5b42a2df744 100644
--- a/hermes_cli/kanban_db_dispatch.py
+++ b/hermes_cli/kanban_db_dispatch.py
@@ -2257,7 +2257,11 @@ def _default_spawn(task: Task, workspace: str, *, board: Optional[str] = None) -
# A worker spawned by a managed systemd gateway must leave the gateway's
# cgroup before startup; otherwise restarting the service kills the worker
# that is performing the handoff.
- cmd = _restart_safe_worker_argv(task, cmd)
+ scoped_cmd = _restart_safe_worker_argv(task, cmd)
+ if scoped_cmd != cmd:
+ from tools.process_registry import systemd_user_bus_env
+ env = systemd_user_bus_env(env)
+ cmd = scoped_cmd
log_f = _open_worker_log(task, board)
try:
proc = subprocess.Popen( # noqa: S603 -- argv is a fixed list built above
diff --git a/tests/tools/test_process_registry.py b/tests/tools/test_process_registry.py
index 3ac709db9d6..62dd2f9496a 100644
--- a/tests/tools/test_process_registry.py
+++ b/tests/tools/test_process_registry.py
@@ -2375,6 +2375,55 @@ class TestSystemdCgroupIsolation:
value.startswith("OOMPolicy=") for value in probe_argv if isinstance(value, str)
), probe_argv
+ @pytest.mark.linux_only
+ def test_systemd_probe_derives_owned_user_bus_env_for_system_gateway(
+ self, registry, monkeypatch, request
+ ):
+ """A system service running as an unprivileged user has no login env,
+ but may still have a valid lingering user manager and D-Bus socket."""
+ import socket
+ import tempfile
+
+ import tools.process_registry as pr
+
+ # Short path: AF_UNIX socket paths are capped at ~104 bytes, longer than most tmp_path values.
+ runtime_dir = pr.Path(tempfile.mkdtemp(prefix="hbus-", dir="/tmp"))
+ runtime_dir.chmod(0o700)
+ bus_path = runtime_dir / "bus"
+ bus_socket = socket.socket(socket.AF_UNIX)
+ bus_socket.bind(str(bus_path))
+
+ def _cleanup():
+ bus_socket.close()
+ bus_path.unlink(missing_ok=True)
+ runtime_dir.rmdir()
+
+ request.addfinalizer(_cleanup)
+
+ monkeypatch.delenv("XDG_RUNTIME_DIR", raising=False)
+ monkeypatch.delenv("DBUS_SESSION_BUS_ADDRESS", raising=False)
+ monkeypatch.setattr(pr, "_SYSTEMD_SCOPE_AVAILABLE", None)
+ monkeypatch.setattr(pr, "_default_user_runtime_dir", lambda: runtime_dir)
+ monkeypatch.setattr("shutil.which", lambda name: "/usr/bin/systemd-run")
+ derived = pr.systemd_user_bus_env(
+ {"DBUS_SESSION_BUS_ADDRESS": "unix:path=/tmp/untrusted-bus"}
+ )
+ assert derived["DBUS_SESSION_BUS_ADDRESS"] == f"unix:path={bus_path}"
+ probe_kwargs = []
+
+ def fake_run(*args, **kwargs):
+ probe_kwargs.append(kwargs)
+ return subprocess.CompletedProcess(args=args[0], returncode=0)
+
+ monkeypatch.setattr("subprocess.run", fake_run)
+
+ assert pr._systemd_run_user_scope_available() is True
+ env = probe_kwargs[0]["env"]
+ assert env["XDG_RUNTIME_DIR"] == str(runtime_dir)
+ assert env["DBUS_SESSION_BUS_ADDRESS"] == f"unix:path={bus_path}"
+ assert "XDG_RUNTIME_DIR" not in os.environ
+ assert "DBUS_SESSION_BUS_ADDRESS" not in os.environ
+
def test_systemd_scope_first_probe_is_serialized(self, monkeypatch):
"""Concurrent first-use callers must wait for one definitive probe.
diff --git a/tools/process_registry.py b/tools/process_registry.py
index 362afc3acd5..4b03a1b8999 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -12,6 +12,7 @@ import os
import platform
import shlex
import signal
+import stat
import subprocess
import threading
import time
@@ -137,6 +138,61 @@ def _systemd_scope_argv(binary: str, unit_name: str, *argv: str) -> List[str]:
]
+def _default_user_runtime_dir() -> Path:
+ """``/run/user/<uid>``; a function so tests can point it at a temp dir with a real socket."""
+ return Path(f"/run/user/{os.getuid()}") # windows-footgun: ok — only reached behind the _IS_LINUX gate in systemd_user_bus_env
+
+
+def _secure_user_runtime_dir(path: Path) -> bool:
+ """Accept only an absolute, owned, non-writable real directory."""
+ try:
+ metadata = path.lstat()
+ return (
+ path.is_absolute()
+ and stat.S_ISDIR(metadata.st_mode)
+ and metadata.st_uid == os.getuid() # windows-footgun: ok — only reached behind the _IS_LINUX gate in systemd_user_bus_env
+ and metadata.st_mode & 0o022 == 0
+ )
+ except OSError:
+ return False
+
+
+def systemd_user_bus_env(base_env: Optional[Dict[str, str]] = None) -> Dict[str, str]:
+ """Build an environment that can reach this user's lingering systemd manager.
+
+ System-level gateway units run as an unprivileged ``User=`` but normally do
+ not inherit login-session variables. When the conventional runtime
+ directory is owned by this uid and its bus exists, derive the two standard
+ variables. Derived fresh on every call rather than adopted once at boot: a
+ system unit has no ordering against ``user@<uid>.service``, and linger may be
+ enabled after the gateway started, so the bus can appear later (#104893).
+ The returned copy is passed explicitly to the probe and every scoped spawn;
+ ``os.environ`` is left unchanged.
+ """
+ env = dict(os.environ if base_env is None else base_env)
+ if not _IS_LINUX:
+ return env
+ configured = env.get("XDG_RUNTIME_DIR")
+ if configured and _secure_user_runtime_dir(Path(configured)):
+ runtime_dir = Path(configured)
+ else:
+ runtime_dir = _default_user_runtime_dir()
+ if not _secure_user_runtime_dir(runtime_dir):
+ return env
+
+ bus_path = runtime_dir / "bus"
+ try:
+ bus_metadata = bus_path.lstat()
+ except OSError:
+ return env
+ if not stat.S_ISSOCK(bus_metadata.st_mode) or bus_metadata.st_uid != os.getuid(): # windows-footgun: ok — behind the _IS_LINUX gate above
+ return env
+
+ env["XDG_RUNTIME_DIR"] = str(runtime_dir)
+ env["DBUS_SESSION_BUS_ADDRESS"] = f"unix:path={bus_path}"
+ return env
+
+
def _systemd_scope_cached() -> Optional[bool]:
"""Cached probe verdict, or None when a (re)probe is due. True is permanent; False
expires after ``_SYSTEMD_SCOPE_FAILURE_TTL_SECONDS`` so a D-Bus blip isn't sticky."""
@@ -171,7 +227,10 @@ def _systemd_run_user_scope_available() -> bool:
# Unique unit avoids collisions; the timeout bounds D-Bus.
probe_unit = f"hermes-probe-scope-{os.getpid()}-{uuid.uuid4().hex[:8]}"
result = subprocess.run(
- _systemd_scope_argv(binary, probe_unit, "/bin/true"), capture_output=True, timeout=3,
+ _systemd_scope_argv(binary, probe_unit, "/bin/true"),
+ capture_output=True,
+ timeout=3,
+ env=systemd_user_bus_env(),
)
available = result.returncode == 0
if not available:
@@ -266,8 +325,13 @@ def _stop_systemd_unit(unit_name: str) -> bool:
if binary is None:
return False
try:
- result = subprocess.run([binary, "--user", "stop", unit_name], capture_output=True, timeout=15,
- stdin=subprocess.DEVNULL)
+ result = subprocess.run(
+ [binary, "--user", "stop", unit_name],
+ capture_output=True,
+ timeout=15,
+ stdin=subprocess.DEVNULL,
+ env=systemd_user_bus_env(),
+ )
if result.returncode != 0:
stderr = (result.stderr or b"").decode(errors="replace").strip()
if any(marker in stderr.lower() for marker in ("not loaded", "not found", "does not exist")):
@@ -815,12 +879,14 @@ class ProcessRegistry(ProcessCheckpointMixin):
from winpty import PtyProcess as _PtyProcessCls
else:
from ptyprocess import PtyProcess as _PtyProcessCls
+ pty_argv = self._scope_argv(session, safe_command, session.id, "PTY")
pty_env = self._spawn_env(env_vars)
+ if session.systemd_unit:
+ pty_env = systemd_user_bus_env(pty_env)
# A PTY is a real TTY, so pager-happy tools (git log/diff, man) WILL page and
# hang waiting for `q` — default them to cat, honoring any pager the user set.
pty_env.setdefault("GIT_PAGER", "cat")
pty_env.setdefault("PAGER", "cat")
- pty_argv = self._scope_argv(session, safe_command, session.id, "PTY")
pty_proc = _PtyProcessCls.spawn(pty_argv, cwd=session.cwd, env=pty_env, dimensions=(30, 120))
session.pid = pty_proc.pid
session.host_start_time = self._safe_host_start_time(session.pid)
@@ -862,13 +928,16 @@ class ProcessRegistry(ProcessCheckpointMixin):
_popen_kwargs = {"creationflags": windows_hide_flags()} if _IS_WINDOWS else {}
unit_suffix = f"{session.id}-pipe-fallback" if pty_scope_attempted else session.id
spawn_argv = self._scope_argv(session, safe_command, unit_suffix, "Local")
+ spawn_env = self._spawn_env(env_vars)
+ if session.systemd_unit:
+ spawn_env = systemd_user_bus_env(spawn_env)
# start_new_session is REQUIRED with systemd-run --scope too: the scope does not
# give the worker a new session, so from an interactive TUI the worker would
# share the foreground process group and background spawns would stop the whole
# session (observed as dead TUIs in state T). Cgroup isolation is unaffected —
# the scope attaches to the invoked process, not the spawning session.
proc = subprocess.Popen(
- spawn_argv, text=True, cwd=session.cwd, env=self._spawn_env(env_vars), encoding="utf-8",
+ spawn_argv, text=True, cwd=session.cwd, env=spawn_env, encoding="utf-8",
errors="replace", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
start_new_session=True, **_popen_kwargs)
session.process = proc