The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): raw CDP blocklist, interception and cookie calls work on guarded backends
kshitijk4poor1c11a23f0f61
diff --git a/tests/tools/test_browser_eval_ssrf.py b/tests/tools/test_browser_eval_ssrf.pyindex 3ceb40922af..0b1f0368b89 100644--- a/tests/tools/test_browser_eval_ssrf.py+++ b/tests/tools/test_browser_eval_ssrf.py@@ -8,6 +8,7 @@ private-host literal is refused before anything reaches the browser.Sibling fix for the eval return-value path of issue #44731."""+import functoolsimport jsonimport pytest@@ -103,26 +104,46 @@ def test_raw_cdp_keeps_the_metadata_floor_when_the_private_guard_is_off(monkeypaassert guard(method="Runtime.evaluate", params=lan) is None[email protected]("local_backend", [False, True])-def test_raw_cdp_url_params_are_screened_even_when_the_open_page_is_public(monkeypatch, local_backend):- """A public page does not vouch for a call's own URLs: unlisted resource-loading methods keep the metadata- floor with the private guard on or off, and the private-address check whenever the guard is on."""- from tools import browser_cdp_tool, browser_session_cloud+def cdp_guard(monkeypatch, local_backend):+ """The raw CDP guard with a public page open: private guard on for a remote backend, off for a local one."""+ from tools import browser_cdp_toolmonkeypatch.setattr(browser_session_cloud, "is_local_backend", lambda: local_backend)monkeypatch.setattr(browser_session_cloud, "allow_private_urls", lambda: False)monkeypatch.setattr(browser_cdp_tool, "_current_page_private_url", lambda endpoint, target_id: None)- guard = browser_cdp_tool._browser_cdp_private_guard+ return functools.partial(browser_cdp_tool._browser_cdp_private_guard, endpoint="ws://x", target_id="T")++[email protected]("local_backend", [False, True])+def test_raw_cdp_url_params_are_screened_even_when_the_open_page_is_public(cdp_guard, local_backend):+ """A public page does not vouch for a call's own URLs: unlisted resource-loading methods keep the metadata+ floor with the private guard on or off, and the private-address check whenever the guard is on."""metadata = "http://metadata.google.internal/computeMetadata/v1/"calls = (("Network.loadNetworkResource", {"frameId": "F", "url": metadata, "options": {}}),("Runtime.callFunctionOn", {"functionDeclaration": f"() => fetch('{metadata}')"}),("Page.addScriptToEvaluateOnNewDocument", {"source": f"fetch(`{metadata}`)"}))for method, params in calls:- assert "cloud metadata" in guard(method=method, params=params, endpoint="ws://x", target_id="T")+ assert "cloud metadata" in cdp_guard(method=method, params=params)loopback = {"frameId": "F", "url": "http://127.0.0.1:8080/", "options": {}}- verdict = guard(method="Network.loadNetworkResource", params=loopback, endpoint="ws://x", target_id="T")- assert (verdict is None) == local_backend+ assert (cdp_guard(method="Network.loadNetworkResource", params=loopback) is None) == local_backendpublic = {"frameId": "F", "url": "https://93.184.216.34/", "options": {}}- assert guard(method="Network.loadNetworkResource", params=public, endpoint="ws://x", target_id="T") is None+ assert cdp_guard(method="Network.loadNetworkResource", params=public) is None# Typing a URL fetches nothing: text input stays allowed, metadata and LAN addresses alike.for typed in (metadata, "http://192.168.1.10/"):- assert guard(method="Input.insertText", params={"text": typed}, endpoint="ws://x", target_id="T") is None+ assert cdp_guard(method="Input.insertText", params={"text": typed}) is None++[email protected]("local_backend", [False, True])+def test_raw_cdp_params_the_call_never_fetches_are_not_screened(cdp_guard):+ """Blocklist and interception patterns, dialog text and cookie scope URLs name hosts without fetching+ them: wildcard and loopback patterns pass, and so does blocking the metadata address itself."""+ calls = (("Network.setBlockedURLs", {"urls": ["https://*.doubleclick.net/*", "http://127.0.0.1/*",+ "http://169.254.169.254/*"]}),+ ("Fetch.enable", {"patterns": [{"urlPattern": "https://*.example.invalid/*"}]}),+ ("Page.handleJavaScriptDialog", {"accept": True, "promptText": "http://127.0.0.1:8080/"}),+ ("Network.setCookie", {"name": "a", "value": "b", "url": "http://localhost:3000/"}))+ for method, params in calls:+ assert cdp_guard(method=method, params=params) is None, method+ # An attribute the page then loads is still a fetch.+ src = {"nodeId": 1, "name": "src", "value": "http://169.254.169.254/latest/meta-data/"}+ assert "cloud metadata" in cdp_guard(method="DOM.setAttributeValue", params=src)diff --git a/tools/browser_cdp_tool.py b/tools/browser_cdp_tool.pyindex c567153a869..e5b788c8dcf 100644--- a/tools/browser_cdp_tool.py+++ b/tools/browser_cdp_tool.py@@ -197,7 +197,15 @@ def _current_page_private_url(endpoint: str, target_id: Optional[str]) -> Optionreturn next((u for u in page_urls if u and not u.startswith(_ORIGINLESS_PAGE_PREFIXES) and url_blocked(u)), None)+# Input.* only types text or dispatches key/mouse events; a URL in its text is never fetched by the call._TEXT_INPUT_METHOD_PREFIX = "Input."+# Nor are these methods' URL params: blocklist / interception match patterns (wildcard hosts, often+# naming the very hosts being blocked), dialog answer text, cookie scope URLs.+_CDP_NON_FETCHING_METHODS = frozenset({+ "Network.setBlockedURLs", "Network.setRequestInterception", "Fetch.enable",+ "Page.handleJavaScriptDialog",+ "Network.setCookie", "Network.setCookies", "Network.deleteCookies", "Storage.setCookies",+})def _param_url_literals(value: Any, key: str = "") -> list[str]:@@ -214,6 +222,14 @@ def _param_url_literals(value: Any, key: str = "") -> list[str]:return []+def _fetched_param_urls(method: str, params: dict[str, Any]) -> list[str]:+ """The distinct URLs a call's params could make the browser fetch (none for text input or the+ non-fetching methods above)."""+ if method.startswith(_TEXT_INPUT_METHOD_PREFIX) or method in _CDP_NON_FETCHING_METHODS:+ return []+ return list(dict.fromkeys(_param_url_literals(params)))++def _browser_cdp_private_guard(*, method: str, params: dict[str, Any], endpoint: str = "",target_id: Optional[str] = None) -> Optional[str]:"""Apply the browser SSRF/private-page guard to raw CDP calls.@@ -230,10 +246,9 @@ def _browser_cdp_private_guard(*, method: str, params: dict[str, Any], endpoint:literal = probe(params or {}, url_blocked)if literal:return _blocked(template.format(literal), method)- # The cloud-metadata floor is unconditional for every method, as in browser_exec's _url_policy_error- # (#16234): with the private guard on or off, sidecar and local Chromium included.- # Input.* only types text or dispatches key/mouse events; a URL in its text is never fetched by the call.- literals = [] if method.startswith(_TEXT_INPUT_METHOD_PREFIX) else _param_url_literals(params or {})+ # The cloud-metadata floor applies with the private guard on or off, sidecar and local Chromium included,+ # as in browser_exec's _url_policy_error (#16234), to every URL the call could fetch.+ literals = _fetched_param_urls(method, params or {})metadata = next((u for u in literals if is_always_blocked_url(u)), None)if metadata:return _blocked(f"Blocked: CDP {method} targets a cloud metadata endpoint ({metadata}).", method)