The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): a shared browser another environment holds is attached through its endpoint, or refused
Teknium0083c92f3820
diff --git a/tests/tools/test_browser_launcher_foreign_attach.py b/tests/tools/test_browser_launcher_foreign_attach.pynew file mode 100644index 00000000000..34537059a0a--- /dev/null+++ b/tests/tools/test_browser_launcher_foreign_attach.py@@ -0,0 +1,139 @@+"""A shared-profile Chromium held from an environment this process cannot verify (a container gateway's browser+seen from the host CLI, or the other way round) is never launched over, deleted or reaped from here.++Its ``SingletonLock`` names a pid of ANOTHER PID namespace (written under another hostname, or by a launch record+from another namespace), so the number proves nothing here. When its DevTools endpoint answers, Hermes attaches+and leases it as usual; when it does not, the launch fails with an error naming the profile instead of starting a+second Chromium on the same user-data-dir (which would wipe the running browser's ``DevToolsActivePort`` and fight+it for the profile).+"""++from __future__ import annotations++import json+import os+import socket+import subprocess+import sys++import pytest++from tests.tools.browser_launcher_fakes import kill_fake, pids, write_fake_chromium+from tests.waiting import wait_until+from tools import browser_launcher as launcher++pytestmark = pytest.mark.platforms("linux")++_FOREIGN_NS = "4026531836:00000000-0000-0000-0000-000000000000"+_OTHER_HOST = "container-3f9c2a"+++def _dead_pid() -> int:+ proc = subprocess.Popen([sys.executable, "-c", "pass"])+ proc.wait()+ return proc.pid+++def _relock(udd, host: str, pid: int) -> None:+ """Point the profile's SingletonLock at ``<host>-<pid>``: how Chromium in another environment wrote it."""+ lock = udd / "SingletonLock"+ lock.unlink(missing_ok=True)+ os.symlink(f"{host}-{pid}", lock)+++def _foreign_launch_record(udd, pid: int) -> None:+ """The launch record a Hermes in another PID namespace wrote for ``pid`` (its own number for the browser)."""+ state = launcher._shared_state_dir(str(udd))+ name = f"{launcher._profile_digest(str(udd))[:16]}-{pid}-nffffffffffff.json"+ (state / name).write_text(json.dumps({+ "owner_pid": pid + 1, "owner_start_time": 1, "pid": pid, "start_time": 7, "user_data_dir": str(udd),+ "home_key": "elsewhere", "ephemeral": False, "ns": _FOREIGN_NS}))+++def _start_fake(script, udd) -> subprocess.Popen:+ proc = subprocess.Popen([str(script), "--remote-debugging-port=0", f"--user-data-dir={udd}"],+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ assert wait_until(lambda: (udd / "DevToolsActivePort").exists(), timeout=15, what="the fake to come up")+ return proc++[email protected]_system_guard_bypass # the fake browser is ours to stop if a leg failed+def test_a_reachable_browser_from_another_environment_is_attached_and_never_stopped(tmp_path):+ script = write_fake_chromium(tmp_path / "chromium")+ udd, key = tmp_path / "pinned-profile", f"profile:{tmp_path / 'pinned-profile'}"+ theirs = _start_fake(script, udd)+ try:+ _relock(udd, _OTHER_HOST, _dead_pid()) # its pid in the container names nobody here+ port_file = (udd / "DevToolsActivePort").read_text()++ browser, err = launcher.launch_chromium(key, executable=str(script), user_data_dir=str(udd),+ ephemeral=False, headed=False, env=dict(os.environ), timeout=30)++ assert err is None and browser is not None and not browser.owned+ port, path = port_file.split()+ assert browser.cdp_url == f"ws://127.0.0.1:{port}{path}"+ assert pids(udd, "spawns") == [theirs.pid], "a second Chromium was started on the held profile"+ assert (udd / "DevToolsActivePort").read_text() == port_file+ state = launcher._shared_state_dir(str(udd))+ assert list(state.glob("*.lease")), "attached without a lease"+ assert launcher.get_browser(key) is browser++ launcher.stop_browser(key)+ assert launcher.reap_orphaned_browsers() == 0+ assert theirs.poll() is None, "stopped a browser another environment holds"+ assert not list(state.glob("*.lease"))+ assert (udd / "DevToolsActivePort").read_text() == port_file+ finally:+ kill_fake(theirs.pid, script)+ theirs.wait(timeout=10)++[email protected]_system_guard_bypass # the fake browser is ours to stop if a leg failed+def test_an_attached_browser_from_another_environment_is_dropped_once_its_endpoint_is_gone(tmp_path):+ script = write_fake_chromium(tmp_path / "chromium")+ udd, key = tmp_path / "pinned-profile", f"profile:{tmp_path / 'pinned-profile'}"+ theirs = _start_fake(script, udd)+ try:+ _relock(udd, _OTHER_HOST, _dead_pid())+ browser, err = launcher.launch_chromium(key, executable=str(script), user_data_dir=str(udd),+ ephemeral=False, headed=False, env=dict(os.environ), timeout=30)+ assert err is None and browser is not None+ kill_fake(theirs.pid, script)+ theirs.wait(timeout=10)+ assert launcher.get_browser(key) is None+ finally:+ kill_fake(theirs.pid, script)+ launcher.stop_browser(key)++[email protected]_system_guard_bypass # a wrongly started second browser is ours to stop[email protected]("evidence", ["other-hostname", "other-namespace-record"])+def test_an_unreachable_browser_from_another_environment_is_an_error_not_a_second_launch(tmp_path, evidence):+ script = write_fake_chromium(tmp_path / "chromium")+ udd, key = tmp_path / "pinned-profile", f"profile:{tmp_path / 'pinned-profile'}"+ udd.mkdir()+ pid = _dead_pid()+ closed = socket.socket()+ closed.bind(("127.0.0.1", 0))+ port_file = f"{closed.getsockname()[1]}\n/devtools/browser/elsewhere\n"+ closed.close() # its DevTools port is the container's loopback: nothing answers here+ (udd / "DevToolsActivePort").write_text(port_file)+ if evidence == "other-hostname":+ _relock(udd, _OTHER_HOST, pid)+ else:+ _relock(udd, socket.gethostname(), pid) # same hostname (--uts=host), another pid namespace+ _foreign_launch_record(udd, pid)++ try:+ browser, err = launcher.launch_chromium(key, executable=str(script), user_data_dir=str(udd),+ ephemeral=False, headed=False, env=dict(os.environ), timeout=30)++ assert browser is None+ assert str(udd) in err and "another environment" in err+ assert pids(udd, "spawns") == [], "a second Chromium was started on a profile another environment holds"+ assert (udd / "DevToolsActivePort").read_text() == port_file+ assert os.readlink(udd / "SingletonLock").endswith(f"-{pid}")+ finally:+ launcher.stop_browser(key)+ for spawned in pids(udd, "spawns"):+ kill_fake(spawned, script)diff --git a/tests/tools/test_browser_real_profile.py b/tests/tools/test_browser_real_profile.pyindex 5105e238cce..9376b20b39f 100644--- a/tests/tools/test_browser_real_profile.py+++ b/tests/tools/test_browser_real_profile.py@@ -318,22 +318,30 @@ class TestRealProfileCdpLaunch:owned, so never killed), never re-run the snapshot over its open databases. A DevToolsActivePort leftby a crash whose port was recycled by ANOTHER CDP server (browser id mismatch) must not be attachedto; the normal launch path runs."""+ import socket+ import subprocess+(tmp_path / "DevToolsActivePort").write_text("41000\n/devtools/browser/x\n", encoding="utf-8")- os.symlink(f"host-{os.getpid()}", tmp_path / "SingletonLock")+ chrome = subprocess.Popen([*_SLEEPER, f"--user-data-dir={tmp_path}"]) # the survivor holding the dir+ os.symlink(f"{socket.gethostname()}-{chrome.pid}", tmp_path / "SingletonLock")version = Mock()version.json.return_value = {"webSocketDebuggerUrl": f"ws://127.0.0.1:41000{live_browser_id}"}- with patch.object(bs_cloud, "use_real_profile", return_value=True), \- patch("hermes_cli.browser_connect.detect_default_chromium", return_value="chrome"), \- patch("hermes_cli.browser_connect.real_profile_copy_dir", return_value=str(tmp_path)), \- patch("hermes_cli.browser_connect.chromium_executable", return_value="/usr/bin/chrome"), \- patch("hermes_cli.browser_connect.snapshot_real_profile", return_value=(None, "boom")) as snapshot, \- patch("requests.get", return_value=version):- cdp, err = rp.real_profile_cdp()+ try:+ with patch.object(bs_cloud, "use_real_profile", return_value=True), \+ patch("hermes_cli.browser_connect.detect_default_chromium", return_value="chrome"), \+ patch("hermes_cli.browser_connect.real_profile_copy_dir", return_value=str(tmp_path)), \+ patch("hermes_cli.browser_connect.chromium_executable", return_value="/usr/bin/chrome"), \+ patch("hermes_cli.browser_connect.snapshot_real_profile", return_value=(None, "boom")) as snapshot, \+ patch("requests.get", return_value=version):+ cdp, err = rp.real_profile_cdp()+ attached = launcher.get_browser(rp.real_profile_key()) # while the stand-in still runs+ finally:+ chrome.kill()+ chrome.wait(timeout=30)if live_browser_id == "/devtools/browser/x":assert (cdp, err) == ("ws://127.0.0.1:41000/devtools/browser/x", None)snapshot.assert_not_called()- attached = launcher.get_browser(rp.real_profile_key())- assert attached is not None and attached.owned is False+ assert attached is not None and attached.owned is False and attached.pid == chrome.pidelse:snapshot.assert_called_once()assert cdp is None and "boom" in errdiff --git a/tools/browser_launcher.py b/tools/browser_launcher.pyindex 8f9cbcede7f..b34b7f18fb0 100644--- a/tools/browser_launcher.py+++ b/tools/browser_launcher.py@@ -23,6 +23,7 @@ import loggingimport osimport reimport shutil+import socketimport statimport subprocessimport sys@@ -79,6 +80,10 @@ class LaunchedBrowser:# File name of the launch record its leases are keyed by, when that is not this process's own name for# it: an attached browser keeps its launcher's record, whichever PID namespace wrote it.record_name: Optional[str] = None+ # Held from an environment this process cannot verify (another PID namespace: a container's browser seen+ # from the host, or the reverse): ``pid`` is that namespace's number, names nobody here and is never+ # signalled; liveness is its DevTools endpoint.+ foreign: bool = False_browsers: dict[str, LaunchedBrowser] = {}@@ -290,12 +295,58 @@ def _wait_for_devtools(proc: subprocess.Popen, user_data_dir: str, deadline: flodef _singleton_pid(user_data_dir: str) -> Optional[int]:"""Pid of the Chromium holding ``user_data_dir``: the ``SingletonLock`` symlink (POSIX), else (Windowshas no symlink, only a locked ``lockfile``) the browser process whose argv names the dir."""+ owner = _singleton_owner(user_data_dir)+ if owner is None:+ return _pid_naming_dir(user_data_dir) if os.name == "nt" else None+ return owner[1]+++def _singleton_owner(user_data_dir: str) -> Optional[tuple[str, int]]:+ """``(hostname, pid)`` Chromium wrote into ``user_data_dir``'s ``SingletonLock`` symlink (POSIX), else None."""try:target = os.readlink(os.path.join(user_data_dir, "SingletonLock"))except OSError:- return _pid_naming_dir(user_data_dir) if os.name == "nt" else None- pid_text = target.rpartition("-")[2]- return int(pid_text) if pid_text.isdigit() else None+ return None+ host, _, pid_text = target.rpartition("-")+ return (host, int(pid_text)) if pid_text.isdigit() else None+++def _foreign_holder(user_data_dir: str) -> Optional[int]:+ """The ``SingletonLock`` pid of a Chromium on ``user_data_dir`` that runs in an environment this process cannot+ verify, else None. Foreign: the lock is not a live process here whose argv names the dir, and it was written+ under another hostname (another host or container; Chromium too refuses such a lock) or names the browser+ of a launch record from another PID namespace. A lock of this hostname with no such record is stale (this+ environment's crashed browser): Chromium itself takes it over, and so does a launch."""+ owner = _singleton_owner(user_data_dir)+ if owner is None:+ return None+ host, pid = owner+ if _pid_alive(pid) and _cmdline_names_dir(pid, user_data_dir):+ return None+ if host != socket.gethostname() or _foreign_record_names(user_data_dir, pid):+ return pid+ return None+++def _foreign_record_names(user_data_dir: str, pid: int) -> bool:+ """A launch record from another PID namespace names ``pid`` as shared profile ``user_data_dir``'s browser."""+ from tools.browser_launcher_holders import same_namespace+ state = _shared_state_dir(user_data_dir)+ if state is None:+ return False+ for name in _record_names(state, user_data_dir, pid):+ record = _load_record(state / name)+ if record is not None and record.get("pid") == pid and not same_namespace(record):+ return True+ return False+++def _record_names(records: Path, user_data_dir: str, pid) -> list[str]:+ """Names of the launch records in ``records`` for profile ``user_data_dir``'s browser ``pid``, whichever PID+ namespace wrote them (each carries its writer's ``ns_tag``), sorted."""+ stem = f"{_profile_digest(user_data_dir)[:16]}-{pid}"+ pattern = re.compile(rf"^{re.escape(stem)}(-n[0-9a-f]{{12}})?\.json$")+ return sorted(p.name for p in records.glob(f"{stem}*.json") if pattern.match(p.name))def _pid_naming_dir(user_data_dir: str) -> Optional[int]:@@ -400,24 +451,57 @@ def _launch_record_name(records: Path, browser: LaunchedBrowser) -> Optional[strhost CLI attached to) would miss the lease and stop the browser under it. This namespace's record winsover another's on the same pid number; None when there is no record (a browser a human started)."""from tools.browser_launcher_holders import ns_tag- stem = f"{_profile_digest(browser.user_data_dir)[:16]}-{browser.pid}"- pattern = re.compile(rf"^{re.escape(stem)}(-n[0-9a-f]{{12}})?\.json$")- names = sorted(p.name for p in records.glob(f"{stem}*.json") if pattern.match(p.name))- own = f"{stem}{ns_tag()}.json"+ names = _record_names(records, browser.user_data_dir, browser.pid)+ own = f"{_profile_digest(browser.user_data_dir)[:16]}-{browser.pid}{ns_tag()}.json"+ if browser.foreign: # its pid number is another namespace's: a record of ours on that number is another browser+ return next((name for name in names if name != own), None)return own if own in names else next(iter(names), None)+def _attach_foreign(key: str, user_data_dir: str, home_key: str, pid: int) -> Optional[LaunchedBrowser]:+ """The Chromium another environment holds on ``user_data_dir``, leased, when its DevTools endpoint answers here+ (caller holds the profile's lock); None when it does not. Never adopted: its record is not ours to take."""+ found = _read_devtools_file(user_data_dir)+ if found is None or not _devtools_endpoint_live(*found):+ return None+ logger.info("browser: attaching to the Chromium another environment runs on %s (its pid %s there)",+ user_data_dir, pid)+ browser = _make_browser(key, found[0], found[1], pid=pid, start_time=None, user_data_dir=user_data_dir,+ owned=False, ephemeral=False, home_key=home_key)+ browser.foreign = True+ records = _state_dir(browser)+ if records is not None:+ from tools import browser_launcher_holders as holders+ browser.record_name = _launch_record_name(records, browser)+ holders.write_lease(_record_path(browser), browser) # its launcher's exit must not stop it under us+ return browser+++def _foreign_unreachable(user_data_dir: str) -> str:+ return (f"The browser profile {user_data_dir} is in use by a Chromium in another environment (a container or "+ "the host) that this process can neither reach nor verify, so Hermes will not start a second browser "+ "on it. Stop that browser, or set browser.user_data_dir to another directory for this environment; if "+ f"no browser runs there any more, delete {os.path.join(user_data_dir, 'SingletonLock')}.")++def _start_shared(key: str, executable: str, udd: str, home_key: str, prepare,**launch) -> tuple[Optional[LaunchedBrowser], Optional[str]]:"""Attach to, or launch, shared profile ``udd``'s one Chromium as ONE step under the profile's cross-processlock: of two processes starting it at once the later waits, then attaches (a second launch would wipe thefirst's DevToolsActivePort and lose Chromium's singleton), and an owner's stop cannot fall between the liveprobe and the lease. A first launch holds the lock for its whole readiness wait; the reaper skips a busy- profile instead of waiting (:func:`_reap_shared_profiles`)."""+ profile instead of waiting (:func:`_reap_shared_profiles`). A browser another environment holds is attached+ through its endpoint, or refused; never launched over."""from tools import browser_launcher_holders as holdersstate = _shared_state_dir(udd)with holders.records_lock(state) if state is not None else contextlib.nullcontext():- attached = _attach_running(key, udd, home_key)+ foreign = _foreign_holder(udd)+ if foreign is not None:+ attached = _attach_foreign(key, udd, home_key, foreign)+ if attached is None:+ return None, _foreign_unreachable(udd)+ else:+ attached = _attach_running(key, udd, home_key)if attached is None:failure = prepare() if prepare is not None else Noneif failure:@@ -546,13 +630,28 @@ def get_browser(key: str) -> Optional[LaunchedBrowser]:browser = _browsers.get(key)if browser is None:return None- if _alive(browser):- return browser- logger.info("browser: Chromium for %s (pid %s) is gone", key, browser.pid)- _forget(key, browser)+ if not browser.foreign:+ if _alive(browser):+ return browser+ logger.info("browser: Chromium for %s (pid %s) is gone", key, browser.pid)+ _forget(key, browser)+ return None+ if _foreign_alive(browser): # an HTTP probe: never under the process-wide lock+ return browser+ with _lock:+ if _browsers.get(key) is browser:+ logger.info("browser: the Chromium another environment ran for %s is gone", key)+ _forget(key, browser)return None+def _foreign_alive(browser: LaunchedBrowser) -> bool:+ """A browser another environment holds is alive while its profile still names this endpoint and it answers."""+ found = _read_devtools_file(browser.user_data_dir)+ return (found is not None and browser.cdp_url == f"ws://127.0.0.1:{found[0]}{found[1]}"+ and _devtools_endpoint_live(*found))++def _heir_key(browser: LaunchedBrowser) -> Optional[str]:"""Another key of this process on the same shared-profile Chromium (one dir reached by two paths, e.g. asymlink): it inherits this process's hold, so dropping ``browser``'s key must neither drop the lease nor@@ -561,7 +660,8 @@ def _heir_key(browser: LaunchedBrowser) -> Optional[str]:return Nonewith _lock:return next((k for k, b in _browsers.items() if b is not browser and not b.ephemeral- and b.pid == browser.pid and b.start_time == browser.start_time), None)+ and b.foreign == browser.foreign and b.pid == browser.pid+ and b.start_time == browser.start_time), None)def _forget(key: str, browser: LaunchedBrowser, *, drop_record: bool = True) -> None:@@ -642,6 +742,8 @@ def _last_holder_out(record: Path, browser: LaunchedBrowser) -> bool:it). Otherwise a record this process holds, or whose owner is gone, goes to a live holder."""from tools import browser_launcher_holders as holdersholders.drop_lease(record)+ if browser.foreign: # its pid names nobody here: stopped (or reaped) only from its own environment+ return Falseothers = holders.other_live_holders(record, browser.start_time)data = _load_record(record) if record.exists() else Noneif data is not None and data.get("start_time") != browser.start_time:@@ -812,8 +914,9 @@ def _is_recorded_browser(record: dict, home: Optional[str]) -> bool:def _tracked_browser(record: dict) -> Optional[LaunchedBrowser]:- with _lock:- return next((b for b in (*_browsers.values(), *_launching.values()) if b.pid == record.get("pid")), None)+ with _lock: # a browser another environment holds has a pid of THAT namespace: it tracks no record here+ return next((b for b in (*_browsers.values(), *_launching.values())+ if not b.foreign and b.pid == record.get("pid")), None)def _adopt_record(browser: LaunchedBrowser) -> None: