fix(browser): a shared daemon is owned only by the Hermes whose command started it
Two same-user Hermes processes can reach one daemon. Both read bu-default.pid on the default Browser Use name, and every Hermes shares the real-profile attach session. The identity checks (uid, module, session leader, socket-dir binding) prove what the daemon is, not who started it, so both Hermes registered its group. Killing either one then killed the browser the other was still using. The real-profile attach's before/after pid-file diff had the same hole: two concurrent attaches both see the file change. Each agent-browser and browser-harness command now carries this process's spawn tag (spawn_env: pid plus create time). The daemon it forks inherits the tag, and _own_local_daemon / _own_harness_daemon register a daemon only when its tag names this process (process_identity.spawned_by_this_process; an unreadable environment fails closed). The pid-file diff is gone. Probed on macOS against agent-browser 0.26.0: the forked daemon carries the tag. New tests start a verified daemon tagged with another live process. Each fails with its check removed (the daemon gets registered) and passes with it. Reported by Greptile on #137057 (two threads).
This commit is contained in:
@@ -212,6 +212,25 @@ def parse_spawn_tag(raw: object) -> Optional[SpawnTag]:
|
||||
return SpawnTag(install, purpose, pid, create) if pid > 0 else None
|
||||
|
||||
|
||||
def spawned_by_this_process(pid: int) -> bool:
|
||||
"""True when ``pid`` carries a spawn tag naming THIS process (pid and create time).
|
||||
|
||||
A shared daemon (one session or pid file every Hermes of this user can reach) is owned only by
|
||||
the Hermes whose command actually started it: the CLI it ran was given ``spawn_env`` and the
|
||||
daemon inherited it. A pid file proves what a process is, not who started it. Fails closed:
|
||||
an unreadable environment (another user, a race) is not ours."""
|
||||
try:
|
||||
import psutil
|
||||
|
||||
tag = parse_spawn_tag(psutil.Process(int(pid)).environ().get(SPAWN_ENV_VAR))
|
||||
except Exception:
|
||||
return False
|
||||
if tag is None or tag.spawner_pid != os.getpid():
|
||||
return False
|
||||
mine = _process_create_time()
|
||||
return tag.spawner_create is None or mine is None or abs(tag.spawner_create - mine) < 2.0
|
||||
|
||||
|
||||
# Layer 2 — spawn ledger
|
||||
|
||||
|
||||
|
||||
@@ -40,7 +40,8 @@ def fake_daemon(tmp_path):
|
||||
(pkg / "__init__.py").write_text("", encoding="utf-8")
|
||||
(pkg / "daemon.py").write_text("import time\ntime.sleep(300)\n", encoding="utf-8")
|
||||
proc = subprocess.Popen([sys.executable, "-m", "browser_harness.daemon"], cwd=str(tmp_path / "pkgroot"),
|
||||
stdin=subprocess.DEVNULL, start_new_session=True)
|
||||
stdin=subprocess.DEVNULL, start_new_session=True,
|
||||
env={**os.environ, **process_identity.spawn_env("browser-harness-daemon")})
|
||||
runtime = tmp_path / "runtime"
|
||||
runtime.mkdir()
|
||||
yield proc, runtime
|
||||
@@ -123,7 +124,7 @@ def test_a_sigkilled_owner_takes_its_harness_daemon_with_it(tmp_path):
|
||||
"import json, os, subprocess, sys, time\n"
|
||||
"from tools import browser_use_cli\n"
|
||||
f"d = subprocess.Popen([sys.executable, '-m', 'browser_harness.daemon'], cwd={str(tmp_path / 'pkgroot')!r},"
|
||||
" stdin=subprocess.DEVNULL, start_new_session=True)\n"
|
||||
" stdin=subprocess.DEVNULL, start_new_session=True, env=browser_use_cli._base_subprocess_env())\n"
|
||||
f"open({str(runtime / 'bu.pid')!r}, 'w', encoding='utf-8').write(json.dumps({{'pid': d.pid}}))\n" # windows-footgun: ok — a write
|
||||
f"browser_use_cli._own_harness_daemon({{'BH_RUNTIME_DIR': {str(runtime)!r}}})\n"
|
||||
"print(d.pid, flush=True)\n"
|
||||
@@ -149,3 +150,30 @@ def test_a_sigkilled_owner_takes_its_harness_daemon_with_it(tmp_path):
|
||||
owner.kill()
|
||||
owner.wait(timeout=10)
|
||||
process_identity._supervised_pgids.clear()
|
||||
|
||||
|
||||
def test_a_daemon_another_live_hermes_started_on_the_same_name_is_never_registered(tmp_path, registered):
|
||||
"""Two Hermes processes on the default BU_NAME read the same bu-default.pid. The daemon belongs
|
||||
to the one whose CLI started it: the other must not hand it to its supervisor, or that Hermes
|
||||
dying would kill a browser session the first still uses."""
|
||||
pkg = tmp_path / "pkgroot" / "browser_harness"
|
||||
pkg.mkdir(parents=True)
|
||||
(pkg / "__init__.py").write_text("", encoding="utf-8")
|
||||
(pkg / "daemon.py").write_text("import time\ntime.sleep(300)\n", encoding="utf-8")
|
||||
runtime = tmp_path / "runtime"
|
||||
runtime.mkdir()
|
||||
other_hermes = subprocess.Popen([sys.executable, "-c", "import sys; sys.stdin.read()"], stdin=subprocess.PIPE)
|
||||
tag = process_identity.spawn_env("browser-harness-daemon")
|
||||
tag[process_identity.SPAWN_ENV_VAR] = tag[process_identity.SPAWN_ENV_VAR].replace(
|
||||
f":{os.getpid()}:", f":{other_hermes.pid}:")
|
||||
daemon = subprocess.Popen([sys.executable, "-m", "browser_harness.daemon"], cwd=str(tmp_path / "pkgroot"),
|
||||
stdin=subprocess.DEVNULL, start_new_session=True, env={**os.environ, **tag})
|
||||
try:
|
||||
_publish(runtime, "bu-default", daemon.pid)
|
||||
browser_use_cli._own_harness_daemon({"BH_HOME": str(runtime.parent)})
|
||||
assert registered == []
|
||||
finally:
|
||||
daemon.kill()
|
||||
daemon.wait(timeout=10)
|
||||
other_hermes.stdin.close()
|
||||
other_hermes.wait(timeout=10)
|
||||
|
||||
@@ -23,7 +23,8 @@ import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, List, NamedTuple, Optional
|
||||
|
||||
from hermes_cli.process_identity import own_process_groups, register_child, release_process_group_once_empty
|
||||
from hermes_cli.process_identity import (
|
||||
own_process_groups, register_child, release_process_group_once_empty, spawn_env, spawned_by_this_process)
|
||||
from hermes_constants import get_hermes_home, hermes_home_key
|
||||
from tools.browser_harness_dirs import (daemon_env, daemon_identity, fit_default_socket_dir,
|
||||
namespace_harness_dirs)
|
||||
@@ -196,6 +197,8 @@ def _base_subprocess_env() -> dict:
|
||||
env["PATH"] = _floor_subprocess_path(env.get("PATH", ""))
|
||||
env.setdefault("ANONYMIZED_TELEMETRY", "false")
|
||||
namespace_harness_dirs(env, _served_profile_tag()) # a served profile's own harness runtime/tmp dirs
|
||||
# A daemon the CLI starts inherits this tag; _own_harness_daemon owns only one that names us.
|
||||
env.update(spawn_env("browser-harness-daemon"))
|
||||
return env
|
||||
|
||||
|
||||
@@ -686,6 +689,8 @@ def _own_harness_daemon(env: dict) -> None:
|
||||
if (os.getsid(pid) != pid or proc.uids().real != os.getuid() # windows-footgun: ok — posix-only, returned above
|
||||
or argv[argv.index("-m") + 1] != "browser_harness.daemon"):
|
||||
return
|
||||
if not spawned_by_this_process(pid):
|
||||
return # another Hermes on the same BU_NAME started it: that Hermes owns it
|
||||
except (OSError, ValueError, KeyError, TypeError, IndexError, psutil.Error) as exc:
|
||||
logger.debug("browser_exec: no harness daemon to supervise for %s: %s", name, exc)
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user