Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Validate browser navigation destinations (SKY-13070) (#8045)
Trevor Cheung11f7dfa3ad57
diff --git a/skyvern/core/script_generations/script_skyvern_page.py b/skyvern/core/script_generations/script_skyvern_page.pyindex cae32d741..593ceb99f 100644--- a/skyvern/core/script_generations/script_skyvern_page.py+++ b/skyvern/core/script_generations/script_skyvern_page.py@@ -47,7 +47,7 @@ from skyvern.forge.sdk.schemas.totp_codes import OTPTypefrom skyvern.forge.sdk.services.credentials import generate_totp_codefrom skyvern.schemas.steps import AgentStepOutputfrom skyvern.services.otp_service import poll_otp_value-from skyvern.utils.url_validators import prepend_scheme_and_validate_url+from skyvern.utils.url_validators import validate_fetch_urlfrom skyvern.webeye.actions.action_types import ActionTypefrom skyvern.webeye.actions.actions import (Action,@@ -1040,7 +1040,7 @@ class ScriptSkyvernPage(SkyvernPage):async def goto(self, url: str, **kwargs: Any) -> None:url = render_template(url)- url = prepend_scheme_and_validate_url(url)+ url = await asyncio.to_thread(validate_fetch_url, url)# Print navigation in script modecontext = skyvern_context.current()diff --git a/skyvern/core/script_generations/skyvern_page.py b/skyvern/core/script_generations/skyvern_page.pyindex 54c6b685f..c9d74d73f 100644--- a/skyvern/core/script_generations/skyvern_page.py+++ b/skyvern/core/script_generations/skyvern_page.py@@ -29,6 +29,7 @@ from skyvern.forge.sdk.event.factory import EventStrategyFactoryfrom skyvern.forge.sdk.services.credentials import is_unresolved_totp_valuefrom skyvern.library.ai_locator import AILocatorfrom skyvern.services.script_reviewer_v3.redaction import redact_sensitive_value+from skyvern.utils.url_validators import validate_fetch_urlfrom skyvern.webeye.actions import handler_utilsfrom skyvern.webeye.actions.action_types import ActionTypefrom skyvern.webeye.browser_engine import BrowserEngineSelection@@ -169,6 +170,7 @@ class SkyvernPage(Page):return decoratorasync def goto(self, url: str, **kwargs: Any) -> None:+ url = await asyncio.to_thread(validate_fetch_url, url)timeout = kwargs.pop("timeout", settings.BROWSER_LOADING_TIMEOUT_MS)await self.page.goto(url, timeout=timeout, **kwargs)diff --git a/skyvern/exceptions.py b/skyvern/exceptions.pyindex 9b87a9360..945c7c548 100644--- a/skyvern/exceptions.py+++ b/skyvern/exceptions.py@@ -1230,6 +1230,10 @@ class BlockedHost(SkyvernHTTPException):)+class UnresolvableHost(BlockedHost):+ pass++class InvalidWorkflowParameter(SkyvernHTTPException):def __init__(self, expected_parameter_type: str, value: str, workflow_permanent_id: str | None = None) -> None:message = f"Invalid workflow parameter. Expected parameter type: {expected_parameter_type}. Value: {value}."diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex 38e12b39a..e6f07dbf3 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -1004,7 +1004,7 @@ class ForgeAgent:page = await browser_state.must_get_working_page()current_url = page.urlif current_url.rstrip("/") != task.url.rstrip("/"):- await page.goto(task.url, timeout=settings.BROWSER_LOADING_TIMEOUT_MS)+ await browser_state.navigate_to_url(page=page, url=task.url)step = await self.update_step(step, status=StepStatus.completed, is_last=True, output=AgentStepOutput(action_results=[]))diff --git a/skyvern/services/script_service.py b/skyvern/services/script_service.pyindex 38f713a5b..e04702992 100644--- a/skyvern/services/script_service.py+++ b/skyvern/services/script_service.py@@ -107,6 +107,7 @@ from skyvern.schemas.steps import AgentStepOutputfrom skyvern.schemas.workflows import BlockResult, BlockStatus, BlockType, FileDownloadTarget, FileStorageType, FileTypefrom skyvern.utils.css_selector import build_action_summaries_with_timingfrom skyvern.utils.script_file_paths import SCRIPT_FILE_PATH_ERROR, normalize_script_file_path+from skyvern.utils.url_validators import validate_fetch_urlfrom skyvern.webeye.actions.action_types import ActionTypefrom skyvern.webeye.actions.actions import Action, DecisiveActionfrom skyvern.webeye.cdp_download_interceptor import download_filename_from_suffix@@ -3601,8 +3602,13 @@ async def goto(browser_session_id=block_validation_output.browser_session_id,)except Exception:+ try:+ candidate_url = _render_template_with_label(url, label)+ except Exception:+ candidate_url = url+ candidate_url = await asyncio.to_thread(validate_fetch_url, candidate_url)run_context = script_run_context_manager.ensure_run_context()- await run_context.page.goto(url)+ await run_context.page.goto(candidate_url)async def trigger_workflow(diff --git a/skyvern/utils/url_validators.py b/skyvern/utils/url_validators.pyindex eec4d1cb4..716a66002 100644--- a/skyvern/utils/url_validators.py+++ b/skyvern/utils/url_validators.py@@ -5,10 +5,10 @@ from typing import Anyfrom urllib.parse import quote, urljoin, urlparse, urlsplit, urlunsplitimport httpx-from pydantic import HttpUrl, ValidationError+from pydantic import AnyHttpUrl, HttpUrl, ValidationErrorfrom skyvern.config import settings-from skyvern.exceptions import BlockedHost, InvalidUrl, SkyvernHTTPException+from skyvern.exceptions import BlockedHost, InvalidUrl, SkyvernHTTPException, UnresolvableHostSAFE_REDIRECT_STATUS_CODES = {301, 302, 303, 307, 308}MAX_SAFE_REDIRECTS = 10@@ -69,7 +69,7 @@ def collapse_duplicate_www_prefix(url: str) -> str:return urlunsplit((parts.scheme, netloc, parts.path, parts.query, parts.fragment))-def prepend_scheme_and_validate_url(url: str) -> str:+def _prepend_scheme(url: str) -> str:if not url:return url@@ -87,7 +87,13 @@ def prepend_scheme_and_validate_url(url: str) -> str:if not parsed_url.scheme:url = f"https://{url}"- url = collapse_duplicate_www_prefix(url)+ return collapse_duplicate_www_prefix(url)+++def prepend_scheme_and_validate_url(url: str) -> str:+ url = _prepend_scheme(url)+ if not url:+ return urltry:HttpUrl(url)@@ -106,11 +112,15 @@ def canonical_navigation_host(url: str) -> str | None:``InvalidUrl`` for non-http(s) schemes and malformed URLs; returns ``None`` whenthere is no host."""- validated_url = prepend_scheme_and_validate_url(url)+ # _prepend_scheme (not prepend_scheme_and_validate_url) plus AnyHttpUrl: both parse with the+ # same WHATWG canonicalization, but HttpUrl's 2083-char ceiling makes a long, ordinary public+ # link fail to parse and so read as a blocked internal host. _prepend_scheme still rejects+ # non-http(s) schemes.+ validated_url = _prepend_scheme(url)if not validated_url:return Nonetry:- return HttpUrl(validated_url).host+ return AnyHttpUrl(validated_url).hostexcept ValidationError:return None@@ -207,6 +217,11 @@ def is_blocked_host(host: str, *, resolve_dns: bool = False) -> bool:try:resolve_fetch_host_ips(normalized)+ except UnresolvableHost:+ # UnresolvableHost subclasses BlockedHost, so it must be caught first. The browser resolves+ # through the run proxy and may reach hosts the worker cannot; worker resolution failure is+ # not a policy signal. Literal internal IPs and internal names are refused above, before DNS.+ return Falseexcept BlockedHost:return Truereturn False@@ -239,7 +254,7 @@ def resolve_fetch_host_ips(host: str) -> tuple[str, ...]:try:infos = socket.getaddrinfo(normalized, None, type=socket.SOCK_STREAM)except (OSError, UnicodeError):- raise BlockedHost(host=host)+ raise UnresolvableHost(host=host)resolved_ips: list[str] = []for info in infos:@@ -258,10 +273,36 @@ def resolve_fetch_host_ips(host: str) -> tuple[str, ...]:resolved_ips.append(resolved_ip_str)if not resolved_ips:- raise BlockedHost(host=host)+ raise UnresolvableHost(host=host)return tuple(resolved_ips)+def _raise_if_best_effort_fetch_host_is_blocked(url: str) -> None:+ # Browsers treat a backslash in the authority as a separator; urlsplit does not, which would+ # otherwise let "http://<blocked-ip>\.example.com" read as an unrelated host here while the+ # browser still navigates to the blocked one. Only ever used to block, never to permit.+ candidate = url.replace("\\", "/")+ try:+ parsed = urlsplit(candidate)+ if not parsed.scheme:+ parsed = urlsplit(f"https://{candidate}")+ host = parsed.hostname+ except (UnicodeError, ValueError):+ return++ if not host:+ return++ try:+ resolve_fetch_host_ips(host)+ except UnresolvableHost:+ return+ except BlockedHost:+ raise+ except Exception:+ return++def validate_url(url: str) -> str | None:try:url = prepend_scheme_and_validate_url(url=url)@@ -280,9 +321,10 @@ def validate_url(url: str) -> str | None:def validate_fetch_url_with_resolved_ips(url: str) -> tuple[str, tuple[str, ...]]:try:- url = prepend_scheme_and_validate_url(url=url)- v = HttpUrl(url=url)+ url = _prepend_scheme(url=url)+ v = AnyHttpUrl(url=url)except Exception as e:+ _raise_if_best_effort_fetch_host_is_blocked(url)raise SkyvernHTTPException(message=str(e), status_code=HTTPStatus.BAD_REQUEST)if not v.host:diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.pyindex ba402ef18..83000eade 100644--- a/skyvern/webeye/actions/handler.py+++ b/skyvern/webeye/actions/handler.py@@ -36,6 +36,7 @@ from skyvern.core.script_generations.fuzzy_matcher import match_option_exact_or_from skyvern.errors.errors import TOTPExpiredError, UserDefinedError, filter_to_user_defined_codesfrom skyvern.exceptions import (ActionExecutionTimeout,+ BlockedHost,CaptchaSolveError,CardNumberInputMismatch,EmptySelect,@@ -73,6 +74,7 @@ from skyvern.exceptions import (SecretInputMismatch,SkyvernException,SkyvernPageAnalysisTimeout,+ UnresolvableHost,)from skyvern.experimentation.wait_utils import get_or_create_wait_config, get_wait_timefrom skyvern.forge import app@@ -7035,6 +7037,8 @@ async def chain_click(action_results: list[ActionResult] = []try:if not await skyvern_element.navigate_to_a_href(page=page):+ if resolved_href := await skyvern_element.resolve_http_href(page):+ await asyncio.to_thread(validate_fetch_url, resolved_href)if click_count == 1:# Route through the active cursor strategy so alternate profiles can# dispatch their own click sequence (explicit mouse.down/up).@@ -7058,6 +7062,12 @@ async def chain_click(action_results = [ActionSuccess()]return action_results+ # The browser resolves through the run proxy and may reach hosts the worker cannot;+ # worker resolution failure is not a policy signal.+ if isinstance(e, BlockedHost) and not isinstance(e, UnresolvableHost):+ action_results = [ActionFailure(FailToClick(action.element_id, msg=str(e)))]+ return action_results+action_results = [ActionFailure(FailToClick(action.element_id, msg=str(e)))]if skyvern_element.get_tag_name() == "label":diff --git a/skyvern/webeye/navigation.py b/skyvern/webeye/navigation.pyindex 0657e996e..19fdd8125 100644--- a/skyvern/webeye/navigation.py+++ b/skyvern/webeye/navigation.py@@ -30,9 +30,9 @@ def validate_navigation_destination(url: str) -> None:"""Fail closed unless ``url`` targets a public http(s) destination.Rejects local-resource schemes (``file://`` and anything other than http/https) and- private, loopback, link-local, metadata, or otherwise-internal hosts. Mirrors the- boundary enforced on LLM-chosen GOTO_URL/NEW_TAB targets in parse_actions so every- navigation entry point that funnels through navigate_with_retry is guarded identically.+ private, loopback, link-local, metadata, or otherwise-internal hosts, including+ public-looking names that resolve to internal addresses. Every navigation entry point+ that funnels through navigate_with_retry is guarded identically.The host comes from the browser's WHATWG canonicalization, not stdlib urlparse, sonumeric-IP and backslash authority tricks that resolve to an internal host are caught."""@@ -44,7 +44,7 @@ def validate_navigation_destination(url: str) -> None:except InvalidUrl as error:raise BlockedNavigationDestination(url=url, reason="unsupported scheme or malformed url") from error- if not host or is_blocked_host(host, resolve_dns=False):+ if not host or is_blocked_host(host, resolve_dns=True):raise BlockedNavigationDestination(url=url, reason="internal, loopback, link-local, or metadata host")@@ -64,9 +64,9 @@ def _navigation_hop_urls(response: object) -> list[str]:return urls-def _revalidate_navigation_response(response: object) -> None:+async def _revalidate_navigation_response(response: object) -> None:for hop_url in _navigation_hop_urls(response):- validate_navigation_destination(hop_url)+ await asyncio.to_thread(validate_navigation_destination, hop_url)# Progressive wait_until degradation. Degrading to `domcontentloaded` and@@ -100,7 +100,7 @@ async def navigate_with_retry(degradation = _DEGRADATION_MAP.get(wait_until, [wait_until])# Fail closed before any request is dispatched so a blocked target never reaches the browser.- validate_navigation_destination(url)+ await asyncio.to_thread(validate_navigation_destination, url)for attempt in range(retry_times):strategy = degradation[min(attempt, len(degradation) - 1)]@@ -110,7 +110,7 @@ async def navigate_with_retry(response = await navigate(strategy)# Revalidate the followed redirect chain: page.goto follows redirects at the network# layer, so a public entry point can still land on an internal host (SKY-13112).- _revalidate_navigation_response(response)+ await _revalidate_navigation_response(response)elapsed = time.monotonic() - start_timeLOG.info("Page loading time", loading_time=elapsed, url=url, wait_until=strategy)await settle()diff --git a/skyvern/webeye/utils/dom.py b/skyvern/webeye/utils/dom.pyindex 24024f57b..590582c81 100644--- a/skyvern/webeye/utils/dom.py+++ b/skyvern/webeye/utils/dom.py@@ -39,6 +39,7 @@ from skyvern.exceptions import ()from skyvern.experimentation.wait_utils import get_or_create_wait_config, get_wait_time, scroll_into_view_waitfrom skyvern.forge.sdk.event.factory import EventStrategyFactory+from skyvern.utils.url_validators import validate_fetch_urlfrom skyvern.webeye.actions import handler_utilsfrom skyvern.webeye.browser_engine import BrowserEngineSelectionfrom skyvern.webeye.dom_inspection import (@@ -690,8 +691,8 @@ class SkyvernElement:coordinate click would dispatch overlay JS, which can navigate to anunintended URL. Following the href avoids that side effect entirely.- Returns the resolved URL on success, ``None`` when no safe URL can be- derived or when frame navigation raises an unrecoverable error.+ Returns the resolved URL on success or ``None`` when no HTTP(S) URL can be derived+ or frame navigation fails. Raises ``SkyvernHTTPException`` for a blocked URL."""# TODO: share a lower-level href-resolution + goto/download-success# helper with ``navigate_to_a_href``. Keep the entry points separate:@@ -705,6 +706,8 @@ class SkyvernElement:if target and target.strip().lower() != "_self":return None+ resolved = await asyncio.to_thread(validate_fetch_url, resolved)+try:frame = self.get_frame()except Exception:@@ -1463,6 +1466,8 @@ class SkyvernElement:if not href:return None+ href = await asyncio.to_thread(validate_fetch_url, href)+LOG.info("Trying to navigate to the <a> href link instead of clicking",href=href,diff --git a/tests/unit/test_browser_effect_sink_enumeration.py b/tests/unit/test_browser_effect_sink_enumeration.pyindex 9c045d3c4..324c8ee0e 100644--- a/tests/unit/test_browser_effect_sink_enumeration.py+++ b/tests/unit/test_browser_effect_sink_enumeration.py@@ -15,7 +15,7 @@ _CANDIDATE_METHODS = frozenset()_DISCOVERED_BROWSER_API_CALLS = {- "skyvern/forge/agent.py": Counter({"goto": 1, "new_page": 1}),+ "skyvern/forge/agent.py": Counter({"new_page": 1}),"skyvern/forge/agent_functions.py": Counter({"close": 1, "scroll_into_view_if_needed": 1}),"skyvern/webeye/actions/handler.py": Counter({@@ -199,14 +199,14 @@ def test_discovered_browser_api_lower_bound_is_stable() -> None:}assert observed == _DISCOVERED_BROWSER_API_CALLS- assert sum(sum(methods.values()) for methods in observed.values()) == 142+ assert sum(sum(methods.values()) for methods in observed.values()) == 141handler_candidates = _candidate_signatures("skyvern/webeye/actions/handler.py", _CANDIDATE_METHODS)classified_non_browser = Counter({signature: count for signature, count in handler_candidates.items() if signature in _NON_BROWSER_CANDIDATES})assert classified_non_browser == _NON_BROWSER_CANDIDATESassert sum(_NON_BROWSER_CANDIDATES.values()) == 5- assert sum(sum(methods.values()) for methods in observed.values()) - sum(_NON_BROWSER_CANDIDATES.values()) == 137+ assert sum(sum(methods.values()) for methods in observed.values()) - sum(_NON_BROWSER_CANDIDATES.values()) == 136def test_every_raw_evaluate_call_is_classified() -> None:diff --git a/tests/unit/test_chain_click_blocked_anchor_navigation.py b/tests/unit/test_chain_click_blocked_anchor_navigation.pyindex 1c57724ad..9f4d02a02 100644--- a/tests/unit/test_chain_click_blocked_anchor_navigation.py+++ b/tests/unit/test_chain_click_blocked_anchor_navigation.py@@ -15,6 +15,8 @@ import pytestfrom playwright.async_api import TimeoutError as PlaywrightTimeoutErrorfrom skyvern.config import settings+from skyvern.exceptions import BlockedHost, InvalidUrl, SkyvernHTTPException+from skyvern.utils.url_validators import validate_fetch_urlfrom skyvern.webeye.utils import dom as dom_modulefrom skyvern.webeye.utils.dom import InteractiveElement, SkyvernElement@@ -74,6 +76,21 @@ class TestTryNavigateViaHref:"evaluate",AsyncMock(return_value=None),)+ monkeypatch.setattr(dom_module, "validate_fetch_url", lambda url: url, raising=False)++ @pytest.mark.asyncio+ async def test_dom_try_navigate_via_href_rejects_loopback(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ elem = _make_anchor_element(href="http://127.0.0.1/internal")+ page = _make_page()+ monkeypatch.setattr(dom_module, "validate_fetch_url", validate_fetch_url)++ with pytest.raises(SkyvernHTTPException):+ await elem.try_navigate_via_href(page=page)++ elem.get_frame().goto.assert_not_awaited()@pytest.mark.asyncioasync def test_browser_normalized_href_is_preferred(self, monkeypatch: pytest.MonkeyPatch) -> None:@@ -287,6 +304,18 @@ class TestTryNavigateViaHref:page.goto.assert_not_called()+async def test_dom_navigate_to_a_href_rejects_loopback(monkeypatch: pytest.MonkeyPatch) -> None:+ elem = _make_anchor_element(href="http://127.0.0.1/internal", target="_blank")+ page = _make_page()+ monkeypatch.setattr(dom_module, "validate_fetch_url", validate_fetch_url, raising=False)++ with pytest.raises(SkyvernHTTPException):+ await elem.navigate_to_a_href(page=page)++ page.goto.assert_not_awaited()++class TestChainClickBlockedAnchorNavigation:"""Integration tests: chain_click must call the new helper only in the``blocking_element is None and blocked=True`` branch, and only for anchors@@ -717,6 +746,7 @@ def _make_ladder_element(*, tag: str = "button", **stubs: object) -> SkyvernElemelem.get_element_handler = AsyncMock(return_value=MagicMock()) # type: ignore[method-assign]elem.locator = MagicMock()elem.navigate_to_a_href = AsyncMock(return_value=None) # type: ignore[method-assign]+ elem.resolve_http_href = AsyncMock(return_value=None) # type: ignore[method-assign]elem.find_label_for = AsyncMock(return_value=None) # type: ignore[method-assign]elem.find_element_in_label_children = AsyncMock(return_value=None) # type: ignore[method-assign]elem.find_bound_label_by_attr_id = AsyncMock(return_value=None) # type: ignore[method-assign]@@ -768,6 +798,282 @@ async def _run_ladder()+class TestChainClickNavigationDestinationGuard:+ @staticmethod+ async def _run(+ monkeypatch: pytest.MonkeyPatch,+ *,+ navigation_result: str | None = None,+ navigation_error: Exception | None = None,+ locator_error: Exception | None = None,+ ) -> tuple[list, SkyvernElement, AsyncMock, AsyncMock]:+ from skyvern.webeye.actions import handler as handler_module+ from skyvern.webeye.actions.actions import ClickAction++ navigate = AsyncMock(side_effect=navigation_error, return_value=navigation_result)+ locator_click = AsyncMock(side_effect=locator_error)+ monkeypatch.setattr(handler_module.EventStrategyFactory, "click_element", locator_click)+ monkeypatch.setattr(handler_module.skyvern_context, "current", MagicMock(return_value=None))+ monkeypatch.setattr(handler_module, "resolve_engine_selection_for_task", MagicMock(return_value=None))++ elem = _make_ladder_element(tag=InteractiveElement.A, navigate_to_a_href=navigate)+ elem.locator.click = AsyncMock()+ page = MagicMock()+ page.url = "https://portal.example.com/dashboard"+ page.on = MagicMock()+ page.remove_listener = MagicMock()+ task = MagicMock()+ task.organization_id = "org_test"++ results = await handler_module.chain_click(+ task=task,+ scraped_page=MagicMock(),+ page=page,+ action=ClickAction(element_id="AAA3"),+ skyvern_element=elem,+ )+ return results, elem, navigate, locator_click++ @pytest.mark.asyncio+ async def test_unresolvable_host_reaches_coordinate_click(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.webeye.actions.responses import ActionSuccess++ def fails_dns(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:+ raise OSError("dns unavailable")++ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", fails_dns)+ with pytest.raises(BlockedHost) as exc_info:+ validate_fetch_url("https://unresolvable.example.test/target")++ results, elem, navigate, locator_click = await self._run(+ monkeypatch,+ navigation_error=exc_info.value,+ )++ assert isinstance(results[-1], ActionSuccess)+ navigate.assert_awaited_once()+ locator_click.assert_not_awaited()+ elem.coordinate_click.assert_awaited_once()+ elem.click_in_javascript.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_blocked_host_is_terminal_without_any_click(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.webeye.actions.responses import ActionFailure++ results, elem, navigate, locator_click = await self._run(+ monkeypatch,+ navigation_error=BlockedHost("127.0.0.1"),+ )++ assert len(results) == 1+ assert isinstance(results[0], ActionFailure)+ navigate.assert_awaited_once()+ locator_click.assert_not_awaited()+ elem.locator.click.assert_not_awaited()+ elem.coordinate_click.assert_not_awaited()+ elem.click_in_javascript.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_too_long_url_with_blocked_host_is_terminal_without_any_click(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from skyvern.webeye.actions.responses import ActionFailure++ url = "http://169.254.169.254/latest/meta-data/#" + "x" * 2100+ assert len(url) > 2083+ with pytest.raises(BlockedHost) as exc_info:+ validate_fetch_url(url)++ results, elem, navigate, locator_click = await self._run(+ monkeypatch,+ navigation_error=exc_info.value,+ )++ assert len(results) == 1+ assert isinstance(results[0], ActionFailure)+ navigate.assert_awaited_once()+ locator_click.assert_not_awaited()+ elem.locator.click.assert_not_awaited()+ elem.coordinate_click.assert_not_awaited()+ elem.click_in_javascript.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_permitted_href_navigation_still_succeeds_without_click(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ from skyvern.webeye.actions.responses import ActionSuccess++ results, elem, navigate, locator_click = await self._run(+ monkeypatch,+ navigation_result="https://other.example.net/target",+ )++ assert len(results) == 1+ assert isinstance(results[0], ActionSuccess)+ navigate.assert_awaited_once()+ locator_click.assert_not_awaited()+ elem.locator.click.assert_not_awaited()+ elem.coordinate_click.assert_not_awaited()+ elem.click_in_javascript.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_invalid_url_still_reaches_click_fallback(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.webeye.actions.responses import ActionSuccess++ results, elem, navigate, locator_click = await self._run(+ monkeypatch,+ navigation_error=InvalidUrl("not-a-url"),+ )++ assert isinstance(results[-1], ActionSuccess)+ navigate.assert_awaited_once()+ locator_click.assert_not_awaited()+ elem.coordinate_click.assert_awaited_once()+ elem.click_in_javascript.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_non_security_click_failure_still_reaches_fallback(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.webeye.actions.responses import ActionSuccess++ results, elem, navigate, locator_click = await self._run(+ monkeypatch,+ locator_error=RuntimeError("click failed"),+ )++ assert isinstance(results[-1], ActionSuccess)+ navigate.assert_awaited_once()+ locator_click.assert_awaited_once()+ elem.coordinate_click.assert_awaited_once()+ elem.click_in_javascript.assert_not_awaited()+++class TestChainClickPreDispatchAnchorGuard:+ @staticmethod+ async def _run(+ monkeypatch: pytest.MonkeyPatch,+ *,+ href: str,+ validator: MagicMock | None = None,+ ) -> tuple[list, SkyvernElement, AsyncMock, MagicMock]:+ from skyvern.webeye.actions import handler as handler_module+ from skyvern.webeye.actions.actions import ClickAction++ click_element = AsyncMock(return_value=None)+ monkeypatch.setattr(handler_module.EventStrategyFactory, "click_element", click_element)+ monkeypatch.setattr(handler_module.skyvern_context, "current", MagicMock(return_value=None))+ monkeypatch.setattr(handler_module, "resolve_engine_selection_for_task", MagicMock(return_value=None))+ if validator is not None:+ monkeypatch.setattr(handler_module, "validate_fetch_url", validator)++ elem = _make_ladder_element(tag=InteractiveElement.A)+ elem.locator.click = AsyncMock()+ del elem.resolve_http_href++ async def _get_attr(name: str, mode: str = "dynamic", **_: object) -> str | None:+ return href if name == "href" else None++ elem.get_attr = AsyncMock(side_effect=_get_attr) # type: ignore[method-assign]++ page = MagicMock()+ page.url = "https://portal.example.com/dashboard"+ page.on = MagicMock()+ page.remove_listener = MagicMock()++ frame = MagicMock()+ frame.url = page.url+ elem.get_frame = MagicMock(return_value=frame) # type: ignore[method-assign]+ monkeypatch.setattr(dom_module.SkyvernFrame, "evaluate", AsyncMock(return_value=href))++ task = MagicMock()+ task.organization_id = "org_test"++ results = await handler_module.chain_click(+ task=task,+ scraped_page=MagicMock(),+ page=page,+ action=ClickAction(element_id="AAA3"),+ skyvern_element=elem,+ )+ return results, elem, click_element, page++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "href",+ [+ "http://127.0.0.1/internal",+ "http://169.254.169.254/latest/meta-data/",+ ],+ )+ async def test_blocked_href_is_terminal_before_physical_click(+ self,+ monkeypatch: pytest.MonkeyPatch,+ href: str,+ ) -> None:+ from skyvern.webeye.actions.responses import ActionFailure++ results, elem, click_element, _ = await self._run(monkeypatch, href=href)++ assert len(results) == 1+ assert isinstance(results[0], ActionFailure)+ click_element.assert_not_awaited()+ elem.locator.click.assert_not_awaited()+ elem.coordinate_click.assert_not_awaited()+ elem.click_in_javascript.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_public_href_uses_physical_click_after_validation(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.webeye.actions.responses import ActionSuccess++ href = "https://example.com/target"+ validator = MagicMock(side_effect=lambda url: url)++ results, elem, click_element, page = await self._run(monkeypatch, href=href, validator=validator)++ assert len(results) == 1+ assert isinstance(results[0], ActionSuccess)+ validator.assert_called_once_with(href)+ click_element.assert_awaited_once_with(page, elem.locator, timeout=settings.BROWSER_ACTION_TIMEOUT_MS)+ elem.coordinate_click.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_unresolvable_href_reaches_coordinate_click(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.webeye.actions.responses import ActionSuccess++ def fails_dns(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:+ raise OSError("dns unavailable")++ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", fails_dns)+ href = "https://unresolvable.example.test/target"+ validator = MagicMock(wraps=validate_fetch_url)++ results, elem, click_element, _ = await self._run(monkeypatch, href=href, validator=validator)++ assert isinstance(results[-1], ActionSuccess)+ validator.assert_called_once_with(href)+ click_element.assert_not_awaited()+ elem.coordinate_click.assert_awaited_once()+ elem.click_in_javascript.assert_not_awaited()++ @pytest.mark.asyncio+ @pytest.mark.parametrize("href", ["javascript:void(0)", "#section"])+ async def test_non_http_href_clicks_without_validation(+ self,+ monkeypatch: pytest.MonkeyPatch,+ href: str,+ ) -> None:+ from skyvern.webeye.actions.responses import ActionSuccess++ validator = MagicMock(side_effect=AssertionError("validation must not run"))++ results, elem, click_element, page = await self._run(monkeypatch, href=href, validator=validator)++ assert len(results) == 1+ assert isinstance(results[0], ActionSuccess)+ validator.assert_not_called()+ click_element.assert_awaited_once_with(page, elem.locator, timeout=settings.BROWSER_ACTION_TIMEOUT_MS)+ elem.coordinate_click.assert_not_awaited()++class TestChainClickFallbackPostDispatchGuard:"""Each side-effecting fallback locator click in ``chain_click`` can itselfdispatch then time out on the post-click navigation wait. When classifieddiff --git a/tests/unit/test_real_browser_state_navigate.py b/tests/unit/test_real_browser_state_navigate.pyindex dd4add53a..7f27c76f4 100644--- a/tests/unit/test_real_browser_state_navigate.py+++ b/tests/unit/test_real_browser_state_navigate.py@@ -4,13 +4,19 @@ Covers SKY-8818: pages whose subresources never finish loading must stillsucceed if the DOM has parsed, via progressive wait_until degradation."""+import socket+import threadingfrom functools import partial+from types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMockimport pytestfrom playwright.async_api import TimeoutError as PlaywrightTimeoutError-from skyvern.exceptions import FailedToNavigateToUrl+from skyvern.config import settings+from skyvern.exceptions import BlockedNavigationDestination, FailedToNavigateToUrl+from skyvern.forge import agent as agent_module+from skyvern.forge.agent import ForgeAgentfrom skyvern.webeye import real_browser_statefrom skyvern.webeye.navigation import navigate_with_retryfrom skyvern.webeye.real_browser_state import RealBrowserState, _same_page_ignoring_fragment@@ -33,6 +39,11 @@ def _instant_sleep(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr("skyvern.webeye.navigation.asyncio.sleep", AsyncMock())monkeypatch.setattr("skyvern.webeye.real_browser_state.asyncio.sleep", AsyncMock())+ def resolves_public(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:+ return [(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("93.184.216.34", port or 0))]++ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", resolves_public)+def test_same_page_ignoring_fragment_matches_fragment_only_differences() -> None:assert _same_page_ignoring_fragment("https://example.test/results#section", "https://example.test/results") is True@@ -40,6 +51,218 @@ def test_same_page_ignoring_fragment_matches_fragment_only_differences() -> Noneassert _same_page_ignoring_fragment("https://example.test/results?page=2", "https://example.test/results") is False+ "url",+ [+ "http://169.254.169.254/latest/meta-data",+ "http://10.0.0.1/private",+ "http://169.254.1.1/link-local",+ "http://127.0.0.1/loopback",+ "file:///etc/passwd",+ ],+)+async def test_navigate_to_url_rejects_unsafe_caller_destination(+ browser_state: RealBrowserState,+ monkeypatch: pytest.MonkeyPatch,+ url: str,+) -> None:+ page = MagicMock()+ page.goto = AsyncMock()++ with pytest.raises(BlockedNavigationDestination):+ await browser_state.navigate_to_url(page=page, url=url)++ page.goto.assert_not_awaited()++[email protected]("url", ["", " ", "about:blank"])+async def test_navigate_to_url_treats_blank_targets_as_non_navigational(+ browser_state: RealBrowserState,+ url: str,+) -> None:+ # navigation._NON_NAVIGATIONAL_TARGETS: a blank target names no network destination, so the+ # destination guard deliberately lets it through rather than reporting a blocked host.+ page = MagicMock()+ page.goto = AsyncMock()++ await browser_state.navigate_to_url(page=page, url=url)++ page.goto.assert_awaited_once()+++async def test_navigation_accepts_public_caller_destination(+ browser_state: RealBrowserState,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ event_loop_thread = threading.get_ident()+ resolver_threads: list[int] = []++ def resolves_public(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:+ resolver_threads.append(threading.get_ident())+ return [(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("93.184.216.34", port or 0))]++ page = MagicMock()+ page.goto = AsyncMock()+ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", resolves_public)++ await browser_state.navigate_to_url(page=page, url="https://public.example.test/path")++ page.goto.assert_awaited_once()+ assert resolver_threads+ assert all(thread_id != event_loop_thread for thread_id in resolver_threads)+++async def test_navigate_to_url_accepts_allowed_loopback_destination(+ browser_state: RealBrowserState,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ page = MagicMock()+ page.goto = AsyncMock()+ monkeypatch.setattr(settings, "ALLOWED_HOSTS", ["127.0.0.1"])++ await browser_state.navigate_to_url(page=page, url="http://127.0.0.1/local")++ page.goto.assert_awaited_once()+++async def test_agent_navigation_rejects_hostname_resolving_to_internal_address(+ browser_state: RealBrowserState,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ event_loop_thread = threading.get_ident()+ resolver_threads: list[int] = []++ def resolves_internal(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:+ resolver_threads.append(threading.get_ident())+ return [(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("10.0.0.42", port or 0))]++ page = MagicMock()+ page.url = "https://93.184.216.34/current"+ page.goto = AsyncMock()+ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", resolves_internal)+ monkeypatch.setattr(browser_state, "must_get_working_page", AsyncMock(return_value=page))+ guarded_navigate = AsyncMock(wraps=browser_state.navigate_to_url)+ monkeypatch.setattr(browser_state, "navigate_to_url", guarded_navigate)++ step = SimpleNamespace(step_id="step-id", retry_index=0)+ task = SimpleNamespace(+ task_id="task-id",+ workflow_run_id=None,+ browser_session_id=None,+ browser_address=None,+ navigation_goal=None,+ navigation_payload=None,+ data_extraction_goal=None,+ complete_criterion=None,+ terminate_criterion=None,+ max_steps_per_run=settings.MAX_STEPS_PER_RUN,+ status="running",+ url="https://public-name.example.test/internal",+ )+ organization = SimpleNamespace(organization_id="organization-id", max_steps_per_run=None)+ agent = ForgeAgent.__new__(ForgeAgent)+ monkeypatch.setattr(+ agent,+ "initialize_execution_state",+ AsyncMock(return_value=(step, browser_state, MagicMock())),+ )+ fail_task = AsyncMock(return_value=False)+ monkeypatch.setattr(agent, "fail_task", fail_task)+ monkeypatch.setattr(+ agent_module.app,+ "DATABASE",+ SimpleNamespace(tasks=SimpleNamespace(get_task=AsyncMock(return_value=None))),+ )+ monkeypatch.setattr(+ agent_module.app,+ "AGENT_FUNCTION",+ SimpleNamespace(validate_step_execution=AsyncMock()),+ )++ with agent_module.skyvern_context.scoped(agent_module.skyvern_context.SkyvernContext()):+ await agent.execute_step(+ organization=organization,+ task=task,+ step=step,+ download_baseline_files=[],+ )++ guarded_navigate.assert_awaited_once_with(page=page, url=task.url)+ page.goto.assert_not_awaited()+ assert isinstance(fail_task.await_args.kwargs["exception"], BlockedNavigationDestination)+ assert resolver_threads+ assert all(thread_id != event_loop_thread for thread_id in resolver_threads)+++async def test_navigation_redirect_hop_rejects_hostname_resolving_to_internal_address(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ event_loop_thread = threading.get_ident()+ resolver_threads: list[int] = []++ def resolves_by_host(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:+ resolver_threads.append(threading.get_ident())+ ip = "10.0.0.42" if host == "redirect.example.test" else "93.184.216.34"+ return [(socket.AF_INET, socket.SOCK_STREAM, 0, "", (ip, port or 0))]++ initial_request = SimpleNamespace(url="https://entry.example.test/start", redirected_from=None)+ redirect_request = SimpleNamespace(url="https://redirect.example.test/final", redirected_from=initial_request)+ navigate = AsyncMock(return_value=SimpleNamespace(request=redirect_request))+ settle = AsyncMock()+ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", resolves_by_host)++ with pytest.raises(BlockedNavigationDestination):+ await navigate_with_retry(+ navigate=navigate,+ url="https://entry.example.test/start",+ retry_times=3,+ settle=settle,+ sleep=AsyncMock(),+ )++ navigate.assert_awaited_once()+ settle.assert_not_awaited()+ assert resolver_threads+ assert all(thread_id != event_loop_thread for thread_id in resolver_threads)+++async def test_navigation_redirect_hop_accepts_public_hostname(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ event_loop_thread = threading.get_ident()+ resolver_threads: list[int] = []++ def resolves_public(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:+ resolver_threads.append(threading.get_ident())+ return [(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("93.184.216.34", port or 0))]++ initial_request = SimpleNamespace(url="https://entry.example.test/start", redirected_from=None)+ redirect_request = SimpleNamespace(url="https://redirect.example.test/final", redirected_from=initial_request)+ navigate = AsyncMock(return_value=SimpleNamespace(request=redirect_request))+ settle = AsyncMock()+ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", resolves_public)++ await navigate_with_retry(+ navigate=navigate,+ url="https://entry.example.test/start",+ retry_times=3,+ settle=settle,+ sleep=AsyncMock(),+ )++ navigate.assert_awaited_once()+ settle.assert_awaited_once()+ assert resolver_threads+ assert all(thread_id != event_loop_thread for thread_id in resolver_threads)++@pytest.mark.asyncioasync def test_navigate_to_url_progresses_from_load_to_domcontentloaded(browser_state: RealBrowserState,diff --git a/tests/unit/test_script_skyvern_page.py b/tests/unit/test_script_skyvern_page.pyindex 96de26853..f260915ee 100644--- a/tests/unit/test_script_skyvern_page.py+++ b/tests/unit/test_script_skyvern_page.py@@ -26,7 +26,9 @@ from skyvern.exceptions import (NoTOTPSecretFound,ScriptTerminationException,SkyvernActionFailed,+ SkyvernHTTPException,)+from skyvern.services import script_serviceclass _KeyboardStub:@@ -90,6 +92,152 @@ def mock_ai():return _AiStub()+def _build_navigation_page(page_type, mock_scraped_page, mock_ai):+ raw_page = MagicMock(spec=["goto"])+ raw_page.goto = AsyncMock()+ with patch("skyvern.core.script_generations.skyvern_page.Page.__init__", return_value=None):+ if page_type is ScriptSkyvernPage:+ return page_type(scraped_page=mock_scraped_page, page=raw_page, ai=mock_ai), raw_page+ return page_type(page=raw_page, ai=mock_ai), raw_page++[email protected]("page_type", [SkyvernPage, ScriptSkyvernPage])+ "url",+ [+ "http://127.0.0.1/loopback",+ "http://169.254.169.254/latest/meta-data",+ ],+)+async def test_page_navigation_rejects_internal_destination(page_type, url, mock_scraped_page, mock_ai):+ page, raw_page = _build_navigation_page(page_type, mock_scraped_page, mock_ai)++ with pytest.raises(SkyvernHTTPException):+ await page.goto(url)++ raw_page.goto.assert_not_awaited()++[email protected]("page_type", [SkyvernPage, ScriptSkyvernPage])+async def test_page_navigation_accepts_public_destination(page_type, mock_scraped_page, mock_ai):+ page, raw_page = _build_navigation_page(page_type, mock_scraped_page, mock_ai)++ await page.goto("https://93.184.216.34/path")++ raw_page.goto.assert_awaited_once()+++async def test_script_service_goto_fallback_rejects_blocked_destination(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ url = "http://127.0.0.1/loopback"+ page = MagicMock()+ page.goto = AsyncMock()+ run_context = SimpleNamespace(page=page)+ monkeypatch.setattr(+ script_service,+ "_validate_and_get_output_parameter",+ AsyncMock(side_effect=RuntimeError("force fallback")),+ )+ monkeypatch.setattr(+ script_service.script_run_context_manager,+ "ensure_run_context",+ MagicMock(return_value=run_context),+ )++ with pytest.raises(SkyvernHTTPException):+ await script_service.goto(url)++ page.goto.assert_not_awaited()+++async def test_script_service_goto_fallback_accepts_permitted_destination(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ url = "https://93.184.216.34/path"+ page = MagicMock()+ page.goto = AsyncMock()+ run_context = SimpleNamespace(page=page)+ monkeypatch.setattr(+ script_service,+ "_validate_and_get_output_parameter",+ AsyncMock(side_effect=RuntimeError("force fallback")),+ )+ monkeypatch.setattr(+ script_service.script_run_context_manager,+ "ensure_run_context",+ MagicMock(return_value=run_context),+ )++ await script_service.goto(url)++ page.goto.assert_awaited_once_with(url)+++async def test_script_service_goto_fallback_rejects_rendered_blocked_destination(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ url = "{{ target }}"+ rendered_url = "http://127.0.0.1/loopback"+ page = MagicMock()+ page.goto = AsyncMock()+ run_context = SimpleNamespace(page=page)+ render_template = MagicMock(return_value=rendered_url)+ validate_fetch_url = MagicMock(wraps=script_service.validate_fetch_url)+ monkeypatch.setattr(+ script_service,+ "_validate_and_get_output_parameter",+ AsyncMock(side_effect=RuntimeError("force fallback")),+ )+ monkeypatch.setattr(script_service, "_render_template_with_label", render_template)+ monkeypatch.setattr(script_service, "validate_fetch_url", validate_fetch_url)+ monkeypatch.setattr(+ script_service.script_run_context_manager,+ "ensure_run_context",+ MagicMock(return_value=run_context),+ )++ with pytest.raises(SkyvernHTTPException):+ await script_service.goto(url)++ render_template.assert_called_once_with(url, None)+ validate_fetch_url.assert_called_once_with(rendered_url)+ page.goto.assert_not_awaited()+++async def test_script_service_goto_fallback_navigates_to_rendered_permitted_destination(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ url = "{{ target }}"+ rendered_url = "https://93.184.216.34/path"+ page = MagicMock()+ page.goto = AsyncMock()+ run_context = SimpleNamespace(page=page)+ render_template = MagicMock(return_value=rendered_url)+ monkeypatch.setattr(+ script_service,+ "_validate_and_get_output_parameter",+ AsyncMock(side_effect=RuntimeError("force fallback")),+ )+ monkeypatch.setattr(script_service, "_render_template_with_label", render_template)+ monkeypatch.setattr(+ script_service.script_run_context_manager,+ "ensure_run_context",+ MagicMock(return_value=run_context),+ )++ await script_service.goto(url)++ render_template.assert_called_once_with(url, None)+ page.goto.assert_awaited_once_with(rendered_url)++@pytest.mark.asyncioasync def test_wait_for_page_ready_before_action_calls_skyvern_frame(mock_scraped_page, mock_ai):"""diff --git a/tests/unit/test_url_validators.py b/tests/unit/test_url_validators.pyindex 5d675a0fe..bed6e7b6e 100644--- a/tests/unit/test_url_validators.py+++ b/tests/unit/test_url_validators.py@@ -3,7 +3,7 @@ import socketimport pytestfrom skyvern.config import settings-from skyvern.exceptions import BlockedHost+from skyvern.exceptions import BlockedHost, UnresolvableHostfrom skyvern.utils.url_validators import (encode_url,is_blocked_host,@@ -183,6 +183,29 @@ def test_is_blocked_host_allows_public_dns_answers(monkeypatch: pytest.MonkeyPatassert is_blocked_host("public.example.test", resolve_dns=True) is False+def test_is_blocked_host_does_not_treat_worker_dns_failure_as_a_policy_block(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def fails_dns(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:+ raise OSError("dns unavailable")++ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", fails_dns)++ assert is_blocked_host("public.example.test", resolve_dns=True) is False++[email protected]("host", ["10.0.0.5", "127.0.0.1", "169.254.169.254", "localhost"])+def test_is_blocked_host_still_refuses_internal_targets_without_resolving(+ monkeypatch: pytest.MonkeyPatch, host: str+) -> None:+ def unexpected_dns(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:+ raise AssertionError("internal targets must be refused before DNS is consulted")++ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", unexpected_dns)++ assert is_blocked_host(host, resolve_dns=True) is True++def test_validate_fetch_url_blocks_hostname_resolving_private_ip(monkeypatch: pytest.MonkeyPatch) -> None:def resolves_to_private(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:return [(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("10.0.0.42", port or 0))]@@ -193,13 +216,101 @@ def test_validate_fetch_url_blocks_hostname_resolving_private_ip(monkeypatch: pyvalidate_fetch_url("https://evil.example.test/file.pdf")[email protected]("blocked_host", ["127.0.0.1", "10.0.0.5", "169.254.169.254"])+def test_validate_fetch_url_checks_blocked_host_when_url_is_too_long(+ blocked_host: str,+) -> None:+ url = f"http://{blocked_host}/resource?payload=" + "x" * 2100+ assert len(url) > 2083++ with pytest.raises(BlockedHost) as exc_info:+ validate_fetch_url(url)++ assert type(exc_info.value) is BlockedHost++[email protected]("blocked_host", ["169.254.169.254", "127.0.0.1", "10.0.0.5"])+def test_validate_fetch_url_checks_blocked_host_behind_backslash_authority(+ blocked_host: str,+) -> None:+ # A browser reads the backslash as a separator and navigates to blocked_host, so the+ # over-length fallback must not be fooled into reading an unrelated host.+ url = f"http://{blocked_host}\\.example.com/latest/meta-data/#" + "x" * 2100+ assert len(url) > 2083++ with pytest.raises(BlockedHost) as exc_info:+ validate_fetch_url(url)++ assert type(exc_info.value) is BlockedHost+++def test_validate_fetch_url_allows_long_url_with_public_host(monkeypatch: pytest.MonkeyPatch) -> None:+ def resolves_to_public(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:+ return [(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("93.184.216.34", port or 0))]++ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", resolves_to_public)+ url = "https://public.example.test/callback?response=" + "x" * 2100+ assert len(url) > 2100++ assert validate_fetch_url(url) == url++[email protected]("url", ["http://localhost:8000/", "http://127.0.0.1:3000/"])+def test_validate_fetch_url_blocks_localhost_and_loopback_without_allowed_hosts(+ monkeypatch: pytest.MonkeyPatch, url: str+) -> None:+ monkeypatch.setattr(settings, "ALLOWED_HOSTS", [])++ with pytest.raises(BlockedHost):+ validate_fetch_url(url)+++def test_validate_fetch_url_allows_localhost_in_allowed_hosts(monkeypatch: pytest.MonkeyPatch) -> None:+ def resolves_to_loopback(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:+ return [(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("127.0.0.1", port or 0))]++ monkeypatch.setattr(settings, "ALLOWED_HOSTS", ["localhost"])+ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", resolves_to_loopback)+ url = "http://localhost:8000/"++ assert validate_fetch_url(url) == url++[email protected]("url", ["http://169.254.169.254/", "http://10.0.0.5/"])+def test_validate_fetch_url_blocks_metadata_and_private_hosts(url: str) -> None:+ with pytest.raises(BlockedHost):+ validate_fetch_url(url)+++def test_validate_fetch_url_blocks_localhost_resolving_to_private_host(monkeypatch: pytest.MonkeyPatch) -> None:+ def resolves_to_private(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:+ return [(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("10.0.0.5", port or 0))]++ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", resolves_to_private)++ with pytest.raises(BlockedHost):+ validate_fetch_url("http://localhost:8000/")++def test_validate_fetch_url_fails_closed_on_dns_error(monkeypatch: pytest.MonkeyPatch) -> None:def fails_dns(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:raise OSError("dns unavailable")monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", fails_dns)- with pytest.raises(BlockedHost):+ with pytest.raises(BlockedHost) as exc_info:+ validate_fetch_url("https://unresolvable.example.test/file.pdf")++ assert type(exc_info.value) is UnresolvableHost+++def test_validate_fetch_url_fails_closed_without_resolved_ips(monkeypatch: pytest.MonkeyPatch) -> None:+ def resolves_without_answers(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:+ return []++ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", resolves_without_answers)++ with pytest.raises(UnresolvableHost):validate_fetch_url("https://unresolvable.example.test/file.pdf")diff --git a/tests/unit_tests/webeye/test_navigation_retry.py b/tests/unit_tests/webeye/test_navigation_retry.pyindex 1014921a7..f591ee26f 100644--- a/tests/unit_tests/webeye/test_navigation_retry.py+++ b/tests/unit_tests/webeye/test_navigation_retry.py@@ -1,5 +1,6 @@from __future__ import annotations+import socketfrom unittest.mock import AsyncMockimport pytest@@ -8,6 +9,15 @@ from skyvern.exceptions import BlockedNavigationDestination, FailedToNavigateToUfrom skyvern.webeye.navigation import navigate_with_retry, validate_navigation_destinationfrom skyvern.webeye.real_browser_state import RealBrowserState+[email protected](autouse=True)+def _resolve_navigation_hosts_to_public_address(monkeypatch: pytest.MonkeyPatch) -> None:+ def resolves_public(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:+ return [(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("93.184.216.34", port or 0))]++ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", resolves_public)++# Internal, loopback, link-local, metadata, and local-file targets that must fail closed.BLOCKED_DESTINATIONS = [pytest.param("file:///etc/passwd", id="local-file"),@@ -227,6 +237,30 @@ def test_validate_navigation_destination_allows_public_targets(url: str) -> Nonevalidate_navigation_destination(url)+def test_validate_navigation_destination_allows_a_host_the_worker_cannot_resolve(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def fails_dns(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:+ raise OSError("dns unavailable")++ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", fails_dns)++ validate_navigation_destination("https://public.example.test/path")++[email protected]("url", BLOCKED_DESTINATIONS)+def test_validate_navigation_destination_still_refuses_internal_targets_when_dns_fails(+ monkeypatch: pytest.MonkeyPatch, url: str+) -> None:+ def fails_dns(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:+ raise OSError("dns unavailable")++ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", fails_dns)++ with pytest.raises(BlockedNavigationDestination):+ validate_navigation_destination(url)++@pytest.mark.parametrize("url", BLOCKED_DESTINATIONS)@pytest.mark.asyncioasync def test_navigate_with_retry_blocks_internal_and_local_before_dispatch(url: str) -> None: