The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: compute each URL's routing verdict once, not once per decision
shadus5515e4172595
diff --git a/tests/tools/test_browser_use_cli.py b/tests/tools/test_browser_use_cli.pyindex 258e123ee9b..5fc53ec1180 100644--- a/tests/tools/test_browser_use_cli.py+++ b/tests/tools/test_browser_use_cli.py@@ -13,6 +13,7 @@ Covers the three seams the integration relies on:"""import jsonimport os+import socketimport statimport subprocessimport sys@@ -1258,28 +1259,28 @@ class TestExecHybridPrivateUrlRouting:# ---- the URL verdict -------------------------------------------------def test_lan_url_passes_preflight(self):- assert bu_cli._blocked_url_in_code(f'new_tab("{self.LAN}")') is None+ assert bu_cli._code_url_verdict(f'new_tab("{self.LAN}")').blocked is Nonedef test_loopback_url_passes_preflight(self):- assert bu_cli._blocked_url_in_code('new_tab("http://127.0.0.1:3000/")') is None+ assert bu_cli._code_url_verdict('new_tab("http://127.0.0.1:3000/")').blocked is Nonedef test_public_url_still_passes(self):- assert bu_cli._blocked_url_in_code('new_tab("https://example.com/x")') is None+ assert bu_cli._code_url_verdict('new_tab("https://example.com/x")').blocked is Nonedef 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/")')+ blocked = bu_cli._code_url_verdict('new_tab("http://169.254.169.254/latest/meta-data/")').blockedassert blocked and "cloud metadata" in blockeddef 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}")')+ blocked = bu_cli._code_url_verdict(f'new_tab("{self.LAN}")').blockedassert blocked and "private or internal" in blockeddef 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+ assert bu_cli._code_url_verdict(f'new_tab("{self.LAN}")').blocked is None# ---- the endpoint the verdict depends on -----------------------------@@ -1321,3 +1322,86 @@ class TestExecHybridPrivateUrlRouting:assert result["success"] is Trueassert seen == [], "a call touching a private URL must not reach the cloud provider"assert _fake_managed_chromium++ # ---- one evaluation per URL: the verdict and the route must share it ----++ @staticmethod+ def _rebinding_resolver(monkeypatch, first_ip, later_ip):+ """Answer ``first_ip`` to the first lookup of a host and ``later_ip`` to every one after it.++ The predicate under test (``_hybrid_routes_locally`` -> ``_url_is_private`` ->+ ``socket.getaddrinfo``) resolves DNS and does not memoise it, which is exactly what makes a+ split evaluation exploitable. Returns the list of lookups so a test can count them.+ """+ lookups = []++ def fake_getaddrinfo(host, *args, **kwargs):+ lookups.append(host)+ ip = first_ip if len(lookups) == 1 else later_ip+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, 0))]++ monkeypatch.setattr(socket, "getaddrinfo", fake_getaddrinfo)+ return lookups++ @staticmethod+ def _counting_routes_locally(monkeypatch):+ """Wrap the real ``_hybrid_routes_locally`` so a test can count how often the ROUTING verdict+ is evaluated. That is the predicate whose repeated evaluation is exploitable — it resolves+ DNS and is not memoised. (The cloud-metadata floor resolves the host separately and+ unconditionally: a different question, and a block rather than a routing decision.)+ """+ from tools import browser_tool as bt++ real = bt._hybrid_routes_locally+ evaluations = []++ def counting(url):+ evaluations.append(url)+ return real(url)++ monkeypatch.setattr(bt, "_hybrid_routes_locally", counting)+ return evaluations++ def test_rebinding_host_cannot_split_verdict_from_route(self, tmp_path, monkeypatch, _fake_managed_chromium):+ """A host that answers private then public must not clear the pre-flight and then go cloud.++ Evaluating the routing predicate once for the pre-flight and again for the backend choice+ lets a rebinding hostname through: the first lookup looks private so the private-address+ floor is relaxed, the second looks public so ``force_local_sidecar`` becomes False — and the+ call is executed against the CLOUD provider. That is the leak this whole change exists to+ prevent, so the verdict is computed ONCE per URL and reused by both decisions.+ """+ target = "http://rebind.example/login"+ self._rebinding_resolver(monkeypatch, "192.168.1.5", "93.184.216.34")+ evaluations = self._counting_routes_locally(monkeypatch)+ 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("{target}")'))++ assert result["success"] is True+ assert evaluations == [target], (+ f"the routing verdict was evaluated {len(evaluations)} times for one URL; the pre-flight "+ "and the backend choice must reuse ONE evaluation or a rebinding host splits them"+ )+ assert seen == [], "the pre-flight relaxed this URL, so it must not reach the cloud provider"+ assert _fake_managed_chromium, "the call should have been routed to the local engine"++ def test_public_then_private_answer_is_refused_not_leaked(self, tmp_path, monkeypatch, _fake_managed_chromium):+ """The other direction over-blocks, and over-blocking is the safe side: if the safety check+ ever sees a private answer the URL is refused, never allowed and then handed to the cloud.+ """+ self._rebinding_resolver(monkeypatch, "93.184.216.34", "192.168.1.5")+ 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("http://flip.example/x")'))++ assert "private or internal" in result.get("error", ""), result+ assert seen == [] and not _fake_managed_chromium, "a refused URL must not reach any backend"diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.pyindex 62eb8214fc8..2d3a95924a4 100644--- a/tools/browser_use_cli.py+++ b/tools/browser_use_cli.py@@ -17,7 +17,7 @@ import sysimport threadingimport timefrom pathlib import Path-from typing import Any, Callable, Dict, List, Optional+from typing import Any, Callable, Dict, List, NamedTuple, Optionalfrom hermes_constants import get_hermes_homefrom utils import is_truthy_value@@ -135,27 +135,43 @@ def _export_session_cdp(env: dict, get_session_info: Callable[[str], Any], cachereturn None-def _blocked_url_in_code(code: str) -> Optional[str]:- """Return an error if a URL literal fails the URL checks.+class _CodeUrlVerdict(NamedTuple):+ """What one pass over a code blob's URL literals decided (see ``_code_url_verdict``)."""++ blocked: Optional[str]+ local_sidecar: bool+++def _code_url_verdict(code: str) -> _CodeUrlVerdict:+ """One pass over the code's URL literals: the blocking error, if any, and whether the call must+ be served by the LOCAL hybrid sidecar.++ Both answers come from a SINGLE evaluation per URL, deliberately. The routing predicate resolves+ DNS (``_hybrid_routes_locally`` -> ``_url_is_private`` -> ``socket.getaddrinfo``) and is not+ memoised, so evaluating it separately per decision lets a host whose answer changes between the+ two lookups split them: the first lookup looks private, which relaxes the private-address floor,+ and the second looks public, which clears the local route — and the call then executes against+ the CLOUD provider with that private URL in it. That is the leak this check exists to prevent.+ Carry the verdict; never re-derive it.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.+ ``_navigation_session_key``, which likewise derives its relaxation from the session key+ (``_is_local_sidecar_key``) rather than re-running the predicate. ``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,- )+ local_sidecar = False+ for url in _URL_RE.findall(code or ""):+ routes_local = _hybrid_routes_locally(url) # evaluated exactly once per URL...+ if routes_local:+ local_sidecar = True+ err = evaluate_url_safety(url, auto_local=routes_local) # ...and reused here+ if err:+ return _CodeUrlVerdict(err.get("error", "Blocked: unsafe URL"), local_sidecar)+ return _CodeUrlVerdict(None, local_sidecar)def _base_subprocess_env() -> dict:@@ -660,17 +676,22 @@ def browser_exec(code: str, session: str = "", timeout_s: int = _DEFAULT_TIMEOUTif not code or not code.strip():return tool_error("No code provided. Pass Python that uses the pre-imported helpers, e.g. new_tab(\"https://example.com\") then print(page_info()).")- blocked = _blocked_url_in_code(code)- if blocked:- return tool_error(blocked)+ # ONE pass answers both questions below, and the answer is carried, not re-derived. The routing+ # predicate resolves DNS and is not memoised, so recomputing it here could disagree with the+ # pre-flight for a host whose answer changes between lookups (private, then public): the floor+ # would be relaxed and the call would still be handed to the CLOUD provider with the private URL+ # in it. `_code_url_verdict` computes each URL's verdict once and returns both decisions,+ # mirroring how browser_navigate derives its relaxation from the session key+ # (_is_local_sidecar_key) instead of re-running the predicate.+ verdict = _code_url_verdict(code)+ if verdict.blocked:+ return tool_error(verdict.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))+ # check above exists to prevent. Verdict and route move together.+ local_sidecar = verdict.local_sidecarcmd = _find_cli()if not cmd: