Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Validate shared browser navigation destinations and revalidate redirect hops (SKY-13112) (#7962)
Aaron Perez8621363c6ac5
diff --git a/skyvern/exceptions.py b/skyvern/exceptions.pyindex 3174ca3a6..6bbc0a5ff 100644--- a/skyvern/exceptions.py+++ b/skyvern/exceptions.py@@ -550,6 +550,16 @@ class FailedToNavigateToUrl(SkyvernException):super().__init__(f"Failed to navigate to url {url}. Error message: {error_message}")+class BlockedNavigationDestination(FailedToNavigateToUrl):+ """A navigation target (or one of its redirect hops) resolves to a private, link-local,+ loopback, metadata, or local-resource destination. A subclass of FailedToNavigateToUrl so+ existing navigation error handling treats it as a permanent failure and never retries it."""++ def __init__(self, url: str, reason: str) -> None:+ self.reason = reason+ super().__init__(url=url, error_message=f"blocked navigation destination: {reason}")++class FailedToReloadPage(SkyvernException):def __init__(self, url: str, error_message: str) -> None:self.url = urldiff --git a/skyvern/utils/url_validators.py b/skyvern/utils/url_validators.pyindex 3d92ad240..0769916dc 100644--- a/skyvern/utils/url_validators.py+++ b/skyvern/utils/url_validators.py@@ -72,7 +72,13 @@ def prepend_scheme_and_validate_url(url: str) -> str:if not url:return url- parsed_url = urlparse(url=url)+ try:+ parsed_url = urlparse(url=url)+ except ValueError as error:+ # Malformed authorities (e.g. an unterminated IPv6 literal like ``http://[``) make+ # stdlib urlparse raise a raw ValueError; surface it as the typed InvalidUrl so+ # callers get one contract instead of a leaking parser error.+ raise InvalidUrl(url=url) from errorif parsed_url.scheme and parsed_url.scheme not in ["http", "https"]:raise InvalidUrl(url=url)@@ -90,6 +96,24 @@ def prepend_scheme_and_validate_url(url: str) -> str:return url+def canonical_navigation_host(url: str) -> str | None:+ """Host a browser resolves ``url`` against, via pydantic's WHATWG URL model.++ The WHATWG parser (what the browser uses) canonicalizes numeric IPv4 literals+ (decimal/octal/hex/shortened) and backslash authority tricks to the host the+ browser truly connects to, unlike stdlib ``urlparse`` which can diverge. Raises+ ``InvalidUrl`` for non-http(s) schemes and malformed URLs; returns ``None`` when+ there is no host.+ """+ validated_url = prepend_scheme_and_validate_url(url)+ if not validated_url:+ return None+ try:+ return HttpUrl(validated_url).host+ except ValidationError:+ return None++def _normalize_host(host: str) -> str:# RFC 3986 wraps IPv6 literals in [...]; ip_address() only accepts the bare form.return (host[1:-1] if host.startswith("[") and host.endswith("]") else host).strip().lower().rstrip(".")diff --git a/skyvern/webeye/navigation.py b/skyvern/webeye/navigation.pyindex 3b98cb566..0657e996e 100644--- a/skyvern/webeye/navigation.py+++ b/skyvern/webeye/navigation.py@@ -8,7 +8,8 @@ from typing import Literalimport structlogfrom skyvern.constants import PERMANENT_NAV_ERRORS, SKIP_INNER_NAV_RETRY_ERRORS-from skyvern.exceptions import FailedToNavigateToUrl+from skyvern.exceptions import BlockedNavigationDestination, FailedToNavigateToUrl, InvalidUrl+from skyvern.utils.url_validators import canonical_navigation_host, is_blocked_hostLOG = structlog.get_logger()@@ -16,6 +17,58 @@ NavigateFunc = Callable[[str], Awaitable[object]]SettleFunc = Callable[[], Awaitable[None]]SleepFunc = Callable[[float], Awaitable[None]]+# Targets that never egress: an empty URL (browser_session continuation) and about:blank+# (reconnect to a fresh page). Blocking these would break those flows; pass them through.+_NON_NAVIGATIONAL_TARGETS = frozenset({"", "about:blank"})++# Defensive bound on the redirect walk. Browsers cap redirect chains well below this, so it+# only guards against a pathological/cyclic ``redirected_from`` link, not real navigation.+_MAX_REDIRECT_HOPS = 100+++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.+ The host comes from the browser's WHATWG canonicalization, not stdlib urlparse, so+ numeric-IP and backslash authority tricks that resolve to an internal host are caught.+ """+ if url.strip().lower() in _NON_NAVIGATIONAL_TARGETS:+ return++ try:+ host = canonical_navigation_host(url)+ 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):+ raise BlockedNavigationDestination(url=url, reason="internal, loopback, link-local, or metadata host")+++def _navigation_hop_urls(response: object) -> list[str]:+ # ``navigate`` returns the page.goto result as an opaque object; a real Playwright Response+ # exposes the followed redirect chain via ``request.redirected_from``. Duck-type it so the+ # shared helper stays decoupled from playwright and testable with plain fakes.+ urls: list[str] = []+ request = getattr(response, "request", None)+ for _ in range(_MAX_REDIRECT_HOPS):+ if request is None:+ break+ hop_url = getattr(request, "url", None)+ if isinstance(hop_url, str) and hop_url:+ urls.append(hop_url)+ request = getattr(request, "redirected_from", None)+ return urls+++def _revalidate_navigation_response(response: object) -> None:+ for hop_url in _navigation_hop_urls(response):+ validate_navigation_destination(hop_url)++# Progressive wait_until degradation. Degrading to `domcontentloaded` and# then `commit` lets navigation succeed once the DOM or response is ready._DEGRADATION_MAP: dict[str, list[str]] = {@@ -46,20 +99,27 @@ async def navigate_with_retry(sleep = asyncio.sleepdegradation = _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)+for attempt in range(retry_times):strategy = degradation[min(attempt, len(degradation) - 1)]LOG.info("Trying to navigate to url", url=url, retry_time=attempt, wait_until=strategy)try:start_time = time.monotonic()- # SECURITY RESIDUAL (SKY-12525): redirects happen below this call; Route.fetch- # bypasses vendor networking. SKY-8484 tracks egress policy and future CDP interception.- await navigate(strategy)+ 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)elapsed = time.monotonic() - start_timeLOG.info("Page loading time", loading_time=elapsed, url=url, wait_until=strategy)await settle()LOG.info("Successfully navigated to url", url=url, retry_time=attempt, wait_until=strategy)return+ except BlockedNavigationDestination:+ # Blocked destinations are permanent; retrying re-issues the same request.+ raiseexcept Exception as error:error_str = str(error)diff --git a/tests/unit_tests/test_url_validators_extended.py b/tests/unit_tests/test_url_validators_extended.pyindex 2e50f5b56..77e867ef6 100644--- a/tests/unit_tests/test_url_validators_extended.py+++ b/tests/unit_tests/test_url_validators_extended.py@@ -141,6 +141,12 @@ class TestPrependSchemeAndValidateUrl:with pytest.raises(InvalidUrl):prepend_scheme_and_validate_url("not a valid url at all!!!")+ @pytest.mark.parametrize("url", ["http://[", "http://[::1", "https://]"])+ def test_malformed_ipv6_raises_invalid_url_not_value_error(self, url):+ """Unterminated IPv6 literals make stdlib urlparse raise ValueError; it must surface as InvalidUrl."""+ with pytest.raises(InvalidUrl):+ prepend_scheme_and_validate_url(url)+class TestEncodeUrlEdgeCases:"""Edge case tests for encode_url."""diff --git a/tests/unit_tests/webeye/test_navigation_retry.py b/tests/unit_tests/webeye/test_navigation_retry.pyindex 2e9641b51..1014921a7 100644--- a/tests/unit_tests/webeye/test_navigation_retry.py+++ b/tests/unit_tests/webeye/test_navigation_retry.py@@ -4,10 +4,55 @@ from unittest.mock import AsyncMockimport pytest-from skyvern.exceptions import FailedToNavigateToUrl-from skyvern.webeye.navigation import navigate_with_retry+from skyvern.exceptions import BlockedNavigationDestination, FailedToNavigateToUrl+from skyvern.webeye.navigation import navigate_with_retry, validate_navigation_destinationfrom skyvern.webeye.real_browser_state import RealBrowserState+# Internal, loopback, link-local, metadata, and local-file targets that must fail closed.+BLOCKED_DESTINATIONS = [+ pytest.param("file:///etc/passwd", id="local-file"),+ pytest.param("file://localhost/etc/shadow", id="local-file-host"),+ pytest.param("http://169.254.169.254/latest/meta-data/", id="cloud-metadata-ip"),+ pytest.param("http://169.254.1.1/", id="link-local"),+ pytest.param("http://192.168.0.10/admin", id="private-192"),+ pytest.param("http://10.0.0.5/", id="private-10"),+ pytest.param("http://127.0.0.1:9000/", id="loopback-ip"),+ pytest.param("http://localhost:8000/admin", id="localhost"),+ pytest.param("http://metadata.google.internal/computeMetadata/v1/", id="metadata-hostname"),+ pytest.param("http://kubernetes.default.svc/api", id="cluster-internal-svc"),+ # Numeric-IP and backslash-authority forms the browser normalizes to an internal host+ # even though stdlib urlparse / ipaddress do not (WHATWG canonicalization catches them).+ pytest.param("http://2130706433/", id="decimal-ip-loopback"),+ pytest.param("http://0177.0.0.1/", id="octal-ip-loopback"),+ pytest.param("http://0x7f.0.0.1/", id="hex-ip-loopback"),+ pytest.param("http://0xa9fea9fe/", id="hex-ip-metadata"),+ pytest.param("http://169.254.43518/", id="shortened-ip-metadata"),+ pytest.param(r"http://169.254.169.254\@example.com/", id="backslash-authority-metadata"),+ pytest.param(r"http:\\169.254.169.254/", id="all-backslash-authority"),+]+++class _FakeRequest:+ """Duck-types the slice of playwright.async_api.Request that redirect revalidation reads."""++ def __init__(self, url: str, redirected_from: _FakeRequest | None = None) -> None:+ self.url = url+ self.redirected_from = redirected_from+++class _FakeResponse:+ def __init__(self, request: _FakeRequest) -> None:+ self.request = request+++def _redirect_response(*urls: str) -> _FakeResponse:+ """Build a page.goto-style response whose redirect chain visited ``urls`` in order."""+ request: _FakeRequest | None = None+ for url in urls:+ request = _FakeRequest(url, redirected_from=request)+ assert request is not None+ return _FakeResponse(request)+@pytest.mark.parametrize("error_message",@@ -161,3 +206,164 @@ async def test_get_or_create_page_retries_retriable_failed_navigation() -> None:assert browser_state.check_and_fix_state.await_count == 2browser_state.close_current_open_page.assert_awaited_once()browser_state.validate_browser_context.assert_awaited_once_with(page)++[email protected]("url", BLOCKED_DESTINATIONS)+def test_validate_navigation_destination_rejects_internal_and_local_targets(url: str) -> None:+ with pytest.raises(BlockedNavigationDestination):+ validate_navigation_destination(url)+++ "url",+ [+ "https://example.com/path",+ "http://example.com/",+ "https://sub.example.co.uk/a?b=c",+ "example.com", # scheme-less public hosts are still allowed (https is prepended)+ ],+)+def test_validate_navigation_destination_allows_public_targets(url: str) -> None:+ validate_navigation_destination(url)++[email protected]("url", BLOCKED_DESTINATIONS)+async def test_navigate_with_retry_blocks_internal_and_local_before_dispatch(url: str) -> None:+ navigate = AsyncMock()+ settle = AsyncMock()+ sleep = AsyncMock()++ with pytest.raises(BlockedNavigationDestination):+ await navigate_with_retry(navigate=navigate, url=url, retry_times=3, settle=settle, sleep=sleep)++ navigate.assert_not_awaited() # rejected before any request is dispatched+ settle.assert_not_awaited()+ sleep.assert_not_awaited()+++# Malformed authorities (unterminated IPv6 literals) that make stdlib urlparse raise a raw+# ValueError; the guard must convert that to BlockedNavigationDestination before dispatch.+MALFORMED_DESTINATIONS = [+ pytest.param("http://[", id="unterminated-ipv6-bracket"),+ pytest.param("http://[::1", id="unclosed-ipv6-literal"),+ pytest.param("https://]", id="stray-ipv6-close-bracket"),+]++[email protected]("url", MALFORMED_DESTINATIONS)+def test_validate_navigation_destination_rejects_malformed_urls(url: str) -> None:+ with pytest.raises(BlockedNavigationDestination):+ validate_navigation_destination(url)++[email protected]("url", MALFORMED_DESTINATIONS)+async def test_navigate_with_retry_blocks_malformed_url_before_dispatch(url: str) -> None:+ navigate = AsyncMock()+ settle = AsyncMock()+ sleep = AsyncMock()++ with pytest.raises(BlockedNavigationDestination):+ await navigate_with_retry(navigate=navigate, url=url, retry_times=3, settle=settle, sleep=sleep)++ navigate.assert_not_awaited() # a parser error must not leak past the guard as a raw ValueError+ settle.assert_not_awaited()+ sleep.assert_not_awaited()+++async def test_navigate_with_retry_blocked_destination_is_a_navigation_failure() -> None:+ # Subclass of FailedToNavigateToUrl so existing navigation error handling catches it.+ navigate = AsyncMock()+ with pytest.raises(FailedToNavigateToUrl):+ await navigate_with_retry(+ navigate=navigate, url="http://169.254.169.254/", retry_times=3, settle=AsyncMock(), sleep=AsyncMock()+ )+++async def test_navigate_with_retry_revalidates_redirect_hops_and_fails_closed() -> None:+ navigate = AsyncMock(+ return_value=_redirect_response("https://example.com/start", "http://169.254.169.254/latest/meta-data/")+ )+ settle = AsyncMock()+ sleep = AsyncMock()++ with pytest.raises(BlockedNavigationDestination):+ await navigate_with_retry(+ navigate=navigate, url="https://example.com/start", retry_times=3, settle=settle, sleep=sleep+ )++ assert navigate.await_count == 1 # a blocked redirect is not retried+ settle.assert_not_awaited() # never settle a page that landed on an internal host+ sleep.assert_not_awaited()+++async def test_navigate_with_retry_allows_public_redirect_chain() -> None:+ navigate = AsyncMock(return_value=_redirect_response("http://example.com/start", "https://example.com/final"))+ settle = AsyncMock()++ await navigate_with_retry(+ navigate=navigate, url="http://example.com/start", retry_times=3, settle=settle, sleep=AsyncMock()+ )++ navigate.assert_awaited_once()+ settle.assert_awaited_once()+++async def test_navigate_with_retry_allows_public_navigation_without_response() -> None:+ navigate = AsyncMock(return_value=None)+ settle = AsyncMock()++ await navigate_with_retry(+ navigate=navigate, url="https://example.com/", retry_times=3, settle=settle, sleep=AsyncMock()+ )++ navigate.assert_awaited_once()+ settle.assert_awaited_once()+++# Empty and about:blank targets are non-egressing continuation/reconnect URLs that reach+# navigate_with_retry (e.g. task.url="" browser_session continuation, `url or "about:blank"`+# on reconnect); the fail-closed guard must let them through rather than reject them.+ "url",+ [pytest.param("", id="empty-string"), pytest.param("about:blank", id="about-blank")],+)+def test_validate_navigation_destination_allows_non_navigational_targets(url: str) -> None:+ validate_navigation_destination(url)+++ "url",+ [pytest.param("", id="empty-string"), pytest.param("about:blank", id="about-blank")],+)+async def test_navigate_with_retry_allows_non_navigational_targets(url: str) -> None:+ navigate = AsyncMock(return_value=None)+ settle = AsyncMock()++ await navigate_with_retry(navigate=navigate, url=url, retry_times=3, settle=settle, sleep=AsyncMock())++ navigate.assert_awaited_once()+ settle.assert_awaited_once()+++async def test_navigate_with_retry_revalidates_every_redirect_hop() -> None:+ # An internal earliest hop followed by a long public tail: the whole chain must be+ # validated, not just the hops nearest the final URL.+ internal_first = "http://169.254.169.254/"+ public_tail = [f"https://hop{index}.example.com/" for index in range(14)]+ navigate = AsyncMock(return_value=_redirect_response(internal_first, *public_tail))+ settle = AsyncMock()++ with pytest.raises(BlockedNavigationDestination):+ await navigate_with_retry(+ navigate=navigate, url="https://start.example.com/", retry_times=3, settle=settle, sleep=AsyncMock()+ )++ settle.assert_not_awaited()