The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: browser_exec honours hybrid routing for private/LAN URLs
shadus7dc0df1be865
diff --git a/tests/tools/test_browser_use_cli.py b/tests/tools/test_browser_use_cli.pyindex 113f8d4e3bc..258e123ee9b 100644--- a/tests/tools/test_browser_use_cli.py+++ b/tests/tools/test_browser_use_cli.py@@ -1227,3 +1227,97 @@ class TestTimeoutProcessGroupKill:monkeypatch.setattr(bu_cli, "_kill_cli_process_group", lambda proc: None)with pytest.raises(subprocess.TimeoutExpired):bu_cli._run_cli_killing_process_group(["x"], "code", {}, 5)+++class TestExecHybridPrivateUrlRouting:+ """``browser_exec`` must reach the SAME verdict as ``browser_navigate`` for a private URL.++ Hybrid routing (``browser.auto_local_for_private_urls``, on by default) serves private/LAN+ URLs from a LOCAL Chromium sidecar so the cloud provider never sees them. ``browser_navigate``+ consults that decision via ``_navigation_session_key``; ``browser_exec``'s pre-flight URL scan+ did not, so every LAN URL was refused with "Blocked: URL targets a private or internal address"+ even though the navigate path would have routed and fetched it.++ Relaxing the pre-flight alone would be WRONG: the exec call resolves ONE endpoint for the whole+ code blob (``_resolve_backend_cdp``), so an allowed private URL would then be executed against+ the configured cloud browser — the exact leak the guard exists to prevent. The verdict and the+ endpoint must move together.+ """++ LAN = "http://192.168.0.1:9120/login"++ @pytest.fixture(autouse=True)+ def _cloud_with_hybrid(self, monkeypatch):+ """Cloud provider configured + hybrid routing on — the shipped default combination."""+ monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")+ # _hybrid_routes_locally reads the RAW override (a CDP override owns the whole session).+ monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override_raw", lambda: "")+ monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: object())+ monkeypatch.setattr(bt_cloud, "_auto_local_for_private_urls", lambda: True)++ # ---- the URL verdict -------------------------------------------------++ def test_lan_url_passes_preflight(self):+ assert bu_cli._blocked_url_in_code(f'new_tab("{self.LAN}")') is None++ def test_loopback_url_passes_preflight(self):+ assert bu_cli._blocked_url_in_code('new_tab("http://127.0.0.1:3000/")') is None++ def test_public_url_still_passes(self):+ assert bu_cli._blocked_url_in_code('new_tab("https://example.com/x")') is None++ def test_imds_still_blocked(self):+ """The cloud-metadata floor is unconditional — hybrid routing must not open it."""+ blocked = bu_cli._blocked_url_in_code('new_tab("http://169.254.169.254/latest/meta-data/")')+ assert blocked and "cloud metadata" in blocked++ def test_lan_url_blocked_when_hybrid_disabled(self, monkeypatch):+ monkeypatch.setattr(bt_cloud, "_auto_local_for_private_urls", lambda: False)+ blocked = bu_cli._blocked_url_in_code(f'new_tab("{self.LAN}")')+ assert blocked and "private or internal" in blocked++ def test_lan_url_blocked_without_a_cloud_provider(self, monkeypatch):+ """No provider ⇒ pure local mode ⇒ the private-address floor never applied anyway."""+ monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: None)+ assert bu_cli._blocked_url_in_code(f'new_tab("{self.LAN}")') is None++ # ---- the endpoint the verdict depends on -----------------------------++ def test_lan_url_routes_the_call_to_the_local_engine(self, tmp_path, monkeypatch, _fake_managed_chromium):+ """The cloud provider must never be asked for a session for a LAN-only call."""+ seen = []+ monkeypatch.setattr(bt_session, "_get_session_info", lambda key: seen.append(key) or {"cdp_url": "wss://cloud.example/x"})+ cli = _fake_cli(tmp_path, "cat\n")+ monkeypatch.setattr(bu_cli, "_find_cli", lambda: [cli])++ result = json.loads(bu_cli.browser_exec(f'new_tab("{self.LAN}")\nprint("ok")'))++ assert result["success"] is True+ assert seen == [], "the cloud provider was consulted for a LAN-only call"+ assert _fake_managed_chromium, "the local engine was never asked for a CDP endpoint"+ assert _fake_managed_chromium[0][1:] == ("get", ("cdp-url",))++ def test_public_only_call_still_uses_the_cloud_provider(self, tmp_path, monkeypatch, _fake_managed_chromium):+ seen = []+ monkeypatch.setattr(bt_session, "_get_session_info", lambda key: seen.append(key) or {"cdp_url": "wss://cloud.example/x"})+ cli = _fake_cli(tmp_path, "cat\n")+ monkeypatch.setattr(bu_cli, "_find_cli", lambda: [cli])++ result = json.loads(bu_cli.browser_exec('new_tab("https://example.com/x")'))++ assert result["success"] is True+ assert seen, "a public-only call should still go to the cloud provider"+ assert not _fake_managed_chromium, "a public-only call should not spawn the local engine"++ def test_mixed_call_goes_local_so_the_private_url_cannot_leak(self, tmp_path, monkeypatch, _fake_managed_chromium):+ """One endpoint per call: if any URL is private, the whole call runs locally."""+ seen = []+ monkeypatch.setattr(bt_session, "_get_session_info", lambda key: seen.append(key) or {"cdp_url": "wss://cloud.example/x"})+ cli = _fake_cli(tmp_path, "cat\n")+ monkeypatch.setattr(bu_cli, "_find_cli", lambda: [cli])++ result = json.loads(bu_cli.browser_exec(f'new_tab("https://example.com/x")\nnew_tab("{self.LAN}")'))++ assert result["success"] is True+ assert seen == [], "a call touching a private URL must not reach the cloud provider"+ assert _fake_managed_chromiumdiff --git a/tools/browser_tool.py b/tools/browser_tool.pyindex 6aa4bd0dcb8..920a4353dee 100644--- a/tools/browser_tool.py+++ b/tools/browser_tool.py@@ -314,21 +314,31 @@ def _url_is_private(url: str) -> bool:return False-def _navigation_session_key(task_id: str, url: str) -> str:- """Session key that should handle ``url`` for ``task_id``: ``f"{task_id}::local"`` (hybrid- local sidecar while the cloud session keeps serving public URLs) only when ALL hold —- cloud provider configured, ``browser.auto_local_for_private_urls`` on, private URL, no- CDP override (it owns the whole session), Camofox off (already local-only)."""- if task_id is None:- task_id = "default"- hybrid = (+def _hybrid_routes_locally(url: str) -> bool:+ """True when ``url`` must be served by the hybrid LOCAL sidecar rather than the configured+ cloud provider. The single source of truth for that predicate — ``_navigation_session_key``+ (the navigate path) and the ``browser_exec`` pre-flight + backend routing both read it, so+ the two verdicts cannot drift apart.++ Hybrid routing needs ALL of: a cloud provider configured,+ ``browser.auto_local_for_private_urls`` on, a private URL, no CDP override (it owns the whole+ session), Camofox off (already local-only)."""+ return (not _cdp._get_cdp_override_raw()and not _is_camofox_mode()and _cloud._get_cloud_provider() is not Noneand _cloud._auto_local_for_private_urls()and _url_is_private(url))- return f"{task_id}{_LOCAL_SUFFIX}" if hybrid else task_id+++def _navigation_session_key(task_id: str, url: str) -> str:+ """Session key that should handle ``url`` for ``task_id``: ``f"{task_id}::local"`` (hybrid+ local sidecar while the cloud session keeps serving public URLs) when+ ``_hybrid_routes_locally`` holds for ``url``."""+ if task_id is None:+ task_id = "default"+ return f"{task_id}{_LOCAL_SUFFIX}" if _hybrid_routes_locally(url) else task_iddef _is_local_sidecar_key(session_key: str) -> bool:@@ -675,10 +685,14 @@ def _secret_url_error_normalized(url: str) -> tuple[str, Optional[dict]]:return url, err-def evaluate_url_safety(url: str) -> Optional[dict]:- """Run URL safety checks; None if safe, else an error dict"""+def evaluate_url_safety(url: str, *, auto_local: bool = False) -> Optional[dict]:+ """Run URL safety checks; None if safe, else an error dict.++ ``auto_local`` relaxes the private-address floor for a URL hybrid routing will serve from a+ LOCAL sidecar — the cloud provider never sees it, which is the verdict the navigation path+ reaches for itself. The cloud-metadata floor is never relaxable."""url, err = _secret_url_error_normalized(url)- return err or _url_policy_error(url)+ return err or _url_policy_error(url, auto_local=auto_local)_BOT_DETECTION_TITLE_PATTERNS = (diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.pyindex ef887907b63..62eb8214fc8 100644--- a/tools/browser_use_cli.py+++ b/tools/browser_use_cli.py@@ -136,9 +136,26 @@ def _export_session_cdp(env: dict, get_session_info: Callable[[str], Any], cachedef _blocked_url_in_code(code: str) -> Optional[str]:- """Return an error if a URL literal fails the built-in navigation checks."""- from tools.browser_tool import evaluate_url_safety- return next((err.get("error", "Blocked: unsafe URL") for err in map(evaluate_url_safety, _URL_RE.findall(code or "")) if err), None)+ """Return an error if a URL literal fails the URL checks.++ A private/LAN URL that hybrid routing will hand to a LOCAL Chromium sidecar is allowed here,+ because the cloud provider never sees it — the same verdict ``browser_navigate`` reaches via+ ``_navigation_session_key``. ``browser_exec`` must route the call to that sidecar to match+ (see ``_route_backend(force_local_sidecar=...)``): the endpoint is resolved once per call, so+ allowing the URL while still pointing at the cloud provider would leak the LAN address to it.+ """+ from tools.browser_tool import _hybrid_routes_locally, evaluate_url_safety+ return next(+ (+ err.get("error", "Blocked: unsafe URL")+ for err in (+ evaluate_url_safety(url, auto_local=_hybrid_routes_locally(url))+ for url in _URL_RE.findall(code or "")+ )+ if err+ ),+ None,+ )def _base_subprocess_env() -> dict:@@ -427,7 +444,8 @@ def _resolve_local_engine_cdp(env: dict, task_id: Optional[str], session_name: sreturn _resolve_managed_chromium_cdp(env, task_id, session_name)-def _resolve_backend_cdp(env: dict, task_id: Optional[str], session_name: str = "") -> Optional[str]:+def _resolve_backend_cdp(env: dict, task_id: Optional[str], session_name: str = "",+ force_local_sidecar: bool = False) -> Optional[str]:"""Point the harness at the configured backend's CDP endpoint; error string on failure.Precedence: (1) ``BU_CDP_WS``/``BU_CDP_URL`` already in env (operator override); (2) ``BROWSER_CDP_URL``@@ -437,7 +455,11 @@ def _resolve_backend_cdp(env: dict, task_id: Optional[str], session_name: str =(never the harness's own discovery of the user's installed Chrome); (5) BU direct-API configs → None:the CLI reaches BU cloud natively (BU_AUTOSPAWN). ``session_name`` (BU_NAME) keys the session cache soeach name gets its OWN browser — what makes named sessions concurrent-safe.- """++ ``force_local_sidecar`` skips step (3) so a call carrying a private/LAN URL runs on the local+ engine instead of the cloud provider (hybrid routing; see ``_hybrid_routes_locally``). It is+ deliberately BELOW the two operator overrides: an explicit ``BU_CDP_*``/cdp_url owns the session,+ and the local-sidecar decision already declines to fire when a CDP override is set."""if _has_cdp_env(env):return Nonetry:@@ -451,7 +473,7 @@ def _resolve_backend_cdp(env: dict, task_id: Optional[str], session_name: str =if override:_set_cdp_env(env, override)return None- provider = _quiet(_get_cloud_provider, None, "Cloud provider lookup failed")+ provider = None if force_local_sidecar else _quiet(_get_cloud_provider, None, "Cloud provider lookup failed")if provider is None:return _resolve_local_engine_cdp(env, task_id, session_name)@@ -526,11 +548,16 @@ def _attach_vault_supervisor(env: dict, task_id: Optional[str]) -> None:logger.debug("browser_exec: CDP supervisor attach failed (non-fatal): %s", exc)-def _route_backend(env: dict, session: str, task_id: Optional[str], local: bool) -> Optional[str]:+def _route_backend(env: dict, session: str, task_id: Optional[str], local: bool,+ force_local_sidecar: bool = False) -> Optional[str]:"""Resolve where the harness connects; returns an error string or None. Real-profile consent runsBEFORE provider resolution so a hit short-circuits the cloud path via the BU_CDP_* env contract. Namedsessions compose with the backend: BU_NAME namespaces the harness daemon (IPC socket, log, pid) and on- provider backends additionally keys its own cloud browser."""+ provider backends additionally keys its own cloud browser.++ ``force_local_sidecar`` (a call carrying a private/LAN URL) declines the cloud provider so the local+ engine serves the whole call. It is distinct from ``local``, which means "the user's real-profile+ browser" and is consent-gated."""rp_err = _resolve_real_profile_cdp(env, force_local=local)if rp_err:return rp_err@@ -538,7 +565,8 @@ def _route_backend(env: dict, session: str, task_id: Optional[str], local: bool)if local and not _has_cdp_env(env) and not _real_profile_consented():return ("local=true was requested but browser.use_real_profile is off. Enable it in config.yaml ""(browser.use_real_profile: true) or the desktop Settings → Browser section, then retry.")- return _resolve_backend_cdp(env, task_id, session_name=session)+ return _resolve_backend_cdp(env, task_id, session_name=session,+ force_local_sidecar=force_local_sidecar)def _group_popen_kwargs() -> dict:@@ -636,6 +664,14 @@ def browser_exec(code: str, session: str = "", timeout_s: int = _DEFAULT_TIMEOUTif blocked:return tool_error(blocked)+ # Hybrid routing: the CDP endpoint is resolved ONCE per call (below), so a private/LAN URL+ # anywhere in the code means the whole call must run on the local sidecar. Allowing the URL+ # while still pointing at the cloud provider would hand the LAN address to it — the leak the+ # check above exists to prevent. Verdict and route move together, mirroring the per-URL+ # decision browser_navigate makes via _navigation_session_key.+ from tools.browser_tool import _hybrid_routes_locally+ local_sidecar = any(_hybrid_routes_locally(url) for url in _URL_RE.findall(code))+cmd = _find_cli()if not cmd:return tool_error("browser-harness is missing from Hermes's Python environment. "@@ -647,7 +683,7 @@ def browser_exec(code: str, session: str = "", timeout_s: int = _DEFAULT_TIMEOUTreturn tool_error(f"Invalid session name {session!r}: use 1-64 letters, digits, ""dashes, or underscores (e.g. 'r7k2').")env["BU_NAME"] = session- route_err = _route_backend(env, session, task_id, bool(local))+ route_err = _route_backend(env, session, task_id, bool(local), force_local_sidecar=local_sidecar)if route_err:return tool_error(route_err)bot_desktop_browser = bool(env.pop(_BOT_DESKTOP_BROWSER_SENTINEL, None))