Skip to content

Automate browser based workflows with AI

Give late-connecting CDP clients their own page sessions on a shared browser (#8055)

Aaron Perez5a2dc37d53b2
diff --git a/docs/cloud/building-agents/run-from-code.mdx b/docs/cloud/building-agents/run-from-code.mdx
index 6aae2f1db..6197ea00c 100644
--- a/docs/cloud/building-agents/run-from-code.mdx
+++ b/docs/cloud/building-agents/run-from-code.mdx
@@ -277,7 +277,7 @@ from skyvern import Skyvern
async def main():
client = Skyvern(api_key=os.getenv("SKYVERN_API_KEY"))
- result = await client.schedules.create(
+ result = await client.agent.create_workflow_schedule(
workflow_permanent_id="wpid_123456789",
cron_expression="0 9 * * 1-5",
timezone="America/New_York",
@@ -327,13 +327,13 @@ curl -X POST "https://api.skyvern.com/api/v1/workflows/wpid_123456789/schedules"
<CodeGroup>
```python Python
# Disable
-await client.schedules.disable(
+await client.agent.disable_workflow_schedule(
workflow_permanent_id="wpid_123456789",
workflow_schedule_id="wfs_abc123"
)
# Re-enable
-await client.schedules.enable(
+await client.agent.enable_workflow_schedule(
workflow_permanent_id="wpid_123456789",
workflow_schedule_id="wfs_abc123"
)
@@ -356,7 +356,7 @@ Permanently remove a schedule. This cannot be undone. Runs that were already tri
<CodeGroup>
```python Python
-await client.schedules.delete(
+await client.agent.delete_workflow_schedule_route(
workflow_permanent_id="wpid_123456789",
workflow_schedule_id="wfs_abc123"
)
diff --git a/docs/snippets/core-concepts-content.mdx b/docs/snippets/core-concepts-content.mdx
index 0dbf53020..abae38c7d 100644
--- a/docs/snippets/core-concepts-content.mdx
+++ b/docs/snippets/core-concepts-content.mdx
@@ -188,7 +188,7 @@ A Schedule runs an agent automatically on a recurring basis. You define a cron e
<CodeGroup>
```python Python
-result = await client.schedules.create(
+result = await client.agent.create_workflow_schedule(
workflow_permanent_id="wpid_abc123",
cron_expression="0 9 * * 1-5", # Weekdays at 9 AM
timezone="America/New_York",
diff --git a/skyvern/forge/sdk/db/repositories/tasks.py b/skyvern/forge/sdk/db/repositories/tasks.py
index 6db3823eb..048c434d9 100644
--- a/skyvern/forge/sdk/db/repositories/tasks.py
+++ b/skyvern/forge/sdk/db/repositories/tasks.py
@@ -6,7 +6,7 @@ from decimal import Decimal
from typing import Any, Sequence
import structlog
-from sqlalchemy import and_, delete, func, select, update
+from sqlalchemy import and_, delete, distinct, func, select, tuple_, update
from skyvern.forge.sdk.db._error_handling import db_operation
from skyvern.forge.sdk.db.base_alchemy_db import read_retry
@@ -306,14 +306,11 @@ class TasksRepository(BaseRepository):
where s.task_id in task_ids
"""
async with self.Session() as session:
- unique_step_orders = (
- select(StepModel.task_id, StepModel.order)
+ query = (
+ select(func.count(distinct(tuple_(StepModel.task_id, StepModel.order))))
.where(StepModel.task_id.in_(task_ids))
.where(StepModel.organization_id == organization_id)
- .distinct()
- .subquery()
)
- query = select(func.count()).select_from(unique_step_orders)
return (await session.execute(query)).scalar()
@db_operation("get_task_step_models")
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 81360eb5a..735bf48c8 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -5551,10 +5551,11 @@ async def wrapper({default_args}):
page = await browser_state.get_working_page()
if page is None:
- # A session can arrive holding a context with no tab, leaving nothing to adopt. Opening
- # one can raise even on a live context: when another Playwright client enabled autoAttach
- # first, it owns target announcements and this connection stays blind to pages
- # (SKY-13338) — no reconnect or retry from here can fix that.
+ # A session can arrive holding a context with no tab, leaving nothing to adopt.
+ # Opening one can still raise when the CDP path does not deliver this client the
+ # target announcement for the tab it creates (SKY-13338); the cloud CDP proxy
+ # fans announcements out to late autoAttach clients, so a failure here now
+ # points at a direct (non-proxied) multi-client connection.
try:
page = await browser_state.get_or_create_page()
except Exception as e:
diff --git a/skyvern/utils/url_validators.py b/skyvern/utils/url_validators.py
index fee4e1808..de2720283 100644
--- a/skyvern/utils/url_validators.py
+++ b/skyvern/utils/url_validators.py
@@ -297,6 +297,11 @@ def _raise_if_best_effort_fetch_host_is_blocked(url: str) -> None:
if not host:
return
+ # A non-http(s) scheme is refused on scheme alone, so resolving its host decides nothing and
+ # would emit a DNS query for an attacker-supplied name on every rejected URL.
+ if parsed.scheme not in ("http", "https"):
+ return
+
try:
resolve_fetch_host_ips(host)
except UnresolvableHost:
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index 83000eade..b8869da10 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -167,6 +167,7 @@ from skyvern.webeye.cdp_download_interceptor import (
settle_browser_downloads_for_context,
)
from skyvern.webeye.main_world_eval import evaluate_in_main_world
+from skyvern.webeye.navigation import revalidate_redirect_chain
from skyvern.webeye.scraper.scraped_page import (
CleanupElementTreeFunc,
ElementTreeBuilder,
@@ -5620,7 +5621,7 @@ async def handle_download_file_action(
# the URL is usally requiring login credentials/cookides, so we should use browser navigation to access the URL instead of downloading the file directly
validated_url = await asyncio.to_thread(validate_fetch_url, action.download_url)
try:
- await page.goto(validated_url, timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
+ response = await page.goto(validated_url, timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
except Exception as e:
error = str(e)
# some cases use this method to download a file. but it will be redirected away soon
@@ -5628,6 +5629,8 @@ async def handle_download_file_action(
# some cases playwright will raise error like "Page.goto: Download is starting"
if "net::ERR_ABORTED" not in error and "Page.goto: Download is starting" not in error:
raise e
+ else:
+ await revalidate_redirect_chain(response, validate_fetch_url, page.goto)
LOG.info(
"DownloadFileAction: Downloaded file from URL",
@@ -6658,7 +6661,8 @@ async def handle_goto_url_action(
step: Step,
) -> list[ActionResult]:
validated_url = await asyncio.to_thread(validate_fetch_url, action.url)
- await page.goto(validated_url, timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
+ response = await page.goto(validated_url, timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
+ await revalidate_redirect_chain(response, validate_fetch_url, page.goto)
# Navigation invalidates the current scraped page's element ids; stop the batch so the
# next step re-scrapes before any later actions run against the new DOM.
result = ActionSuccess()
@@ -6960,6 +6964,10 @@ def _get_click_count(action: ClickAction | UploadFileAction) -> int:
return 1
+def _is_policy_blocked_host(error: Exception) -> bool:
+ return isinstance(error, BlockedHost) and not isinstance(error, UnresolvableHost)
+
+
async def _locator_click(
locator: Locator,
click_count: int,
@@ -7064,7 +7072,7 @@ async def chain_click(
# 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):
+ if _is_policy_blocked_host(e):
action_results = [ActionFailure(FailToClick(action.element_id, msg=str(e)))]
return action_results
@@ -7217,16 +7225,22 @@ async def chain_click(
and action.y is None
and skyvern_element.get_tag_name() == InteractiveElement.A
):
- navigated_href = await skyvern_element.try_navigate_via_href(page=page)
- if navigated_href:
- LOG.info(
- "Chain click: bypassed coordinate fallback via direct href navigation",
- action=action,
- element=str(skyvern_element),
- href=navigated_href,
- )
- action_results.append(ActionSuccess())
- return action_results
+ try:
+ navigated_href = await skyvern_element.try_navigate_via_href(page=page)
+ except BlockedHost as e:
+ if _is_policy_blocked_host(e):
+ action_results = [ActionFailure(FailToClick(action.element_id, msg=str(e)))]
+ return action_results
+ else:
+ if navigated_href:
+ LOG.info(
+ "Chain click: bypassed coordinate fallback via direct href navigation",
+ action=action,
+ element=str(skyvern_element),
+ href=navigated_href,
+ )
+ action_results.append(ActionSuccess())
+ return action_results
else:
# Element is visible and elementFromPoint returns the target itself,
# but Playwright's click still failed (e.g. element transiently
diff --git a/skyvern/webeye/navigation.py b/skyvern/webeye/navigation.py
index 19fdd8125..bf90e7ddb 100644
--- a/skyvern/webeye/navigation.py
+++ b/skyvern/webeye/navigation.py
@@ -8,7 +8,7 @@ from typing import Literal
import structlog
from skyvern.constants import PERMANENT_NAV_ERRORS, SKIP_INNER_NAV_RETRY_ERRORS
-from skyvern.exceptions import BlockedNavigationDestination, FailedToNavigateToUrl, InvalidUrl
+from skyvern.exceptions import BlockedHost, BlockedNavigationDestination, FailedToNavigateToUrl, InvalidUrl
from skyvern.utils.url_validators import canonical_navigation_host, is_blocked_host
LOG = structlog.get_logger()
@@ -64,9 +64,32 @@ def _navigation_hop_urls(response: object) -> list[str]:
return urls
+async def revalidate_redirect_chain(
+ response: object,
+ validate: Callable[[str], object],
+ reset_page: NavigateFunc | None = None,
+) -> None:
+ """Re-check every hop the browser followed, plus the final destination.
+
+ ``validate`` must raise the exception family the call site already handles.
+ ``BlockedNavigationDestination`` is NOT a ``BlockedHost`` subclass, so passing the wrong
+ validator silently reroutes a blocked hop into the caller's success or fallback branch.
+ A provided ``reset_page`` is used to clear a refused destination without replacing its error.
+ """
+ try:
+ for hop_url in _navigation_hop_urls(response):
+ await asyncio.to_thread(validate, hop_url)
+ except BlockedHost:
+ if reset_page is not None:
+ try:
+ await reset_page("about:blank")
+ except Exception:
+ LOG.exception("Failed to reset page after redirect refusal")
+ raise
+
+
async def _revalidate_navigation_response(response: object) -> None:
- for hop_url in _navigation_hop_urls(response):
- await asyncio.to_thread(validate_navigation_destination, hop_url)
+ await revalidate_redirect_chain(response, validate_navigation_destination)
# Progressive wait_until degradation. Degrading to `domcontentloaded` and
diff --git a/skyvern/webeye/utils/dom.py b/skyvern/webeye/utils/dom.py
index 590582c81..dcaa04c43 100644
--- a/skyvern/webeye/utils/dom.py
+++ b/skyvern/webeye/utils/dom.py
@@ -47,6 +47,7 @@ from skyvern.webeye.dom_inspection import (
read_resolved_anchor_href,
read_whether_link_or_button,
)
+from skyvern.webeye.navigation import revalidate_redirect_chain
from skyvern.webeye.scraper.scraped_page import ScrapedPage, json_to_html
from skyvern.webeye.scraper.scraper import IncrementalScrapePage, trim_element
from skyvern.webeye.utils.page import SECRET_VISUAL_MASK_SCRIPT, SkyvernFrame
@@ -726,8 +727,7 @@ class SkyvernElement:
element_id=self.get_id(),
)
try:
- await frame.goto(resolved, timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
- return resolved
+ response = await frame.goto(resolved, timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
except Exception as e:
error = str(e)
# Same exceptions ``navigate_to_a_href`` treats as effective
@@ -744,6 +744,11 @@ class SkyvernElement:
)
return None
+ # Outside the except above on purpose: that handler swallows every failure into a
+ # coordinate-click fallback, which would turn a blocked redirect hop into a click.
+ await revalidate_redirect_chain(response, validate_fetch_url, page.goto)
+ return resolved
+
async def find_blocking_element(
self, dom: DomUtil, incremental_page: IncrementalScrapePage | None = None
) -> tuple[SkyvernElement | None, bool]:
@@ -1474,8 +1479,7 @@ class SkyvernElement:
current_url=page.url,
)
try:
- await page.goto(href, timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
- return href
+ response = await page.goto(href, timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
except Exception as e:
# some cases use this method to download a file. but it will be redirected away soon
# and agent will run into ABORTED error.
@@ -1490,6 +1494,9 @@ class SkyvernElement:
LOG.warning("Failed to navigate to the <a> href link", exc_info=True, href=href, current_url=page.url)
raise
+ await revalidate_redirect_chain(response, validate_fetch_url, page.goto)
+ return href
+
async def refresh_select_options(self) -> tuple[list, str] | None:
if self.get_tag_name() != InteractiveElement.SELECT:
return None
diff --git a/tests/unit/forge/sdk/db/test_tasks_repository.py b/tests/unit/forge/sdk/db/test_tasks_repository.py
deleted file mode 100644
index 05d8e2182..000000000
--- a/tests/unit/forge/sdk/db/test_tasks_repository.py
+++ /dev/null
@@ -1,43 +0,0 @@
-import pytest
-
-
-async def test_total_unique_step_order_count_deduplicates_retries_in_sqlite(agent_db) -> None:
- organization = await agent_db.organizations.create_organization(
- organization_name="Test organization",
- organization_id="o_test_task_step_count",
- )
- task = await agent_db.tasks.create_task(
- url="https://example.com",
- title="Count steps",
- navigation_goal=None,
- data_extraction_goal=None,
- navigation_payload=None,
- organization_id=organization.organization_id,
- )
- excluded_task = await agent_db.tasks.create_task(
- url="https://example.com",
- title="Excluded task",
- navigation_goal=None,
- data_extraction_goal=None,
- navigation_payload=None,
- organization_id=organization.organization_id,
- )
-
- await agent_db.tasks.create_step(task.task_id, order=0, retry_index=0, organization_id=organization.organization_id)
- await agent_db.tasks.create_step(task.task_id, order=0, retry_index=1, organization_id=organization.organization_id)
- await agent_db.tasks.create_step(task.task_id, order=1, retry_index=0, organization_id=organization.organization_id)
- await agent_db.tasks.create_step(
- excluded_task.task_id,
- order=0,
- retry_index=0,
- organization_id=organization.organization_id,
- )
-
- assert (
- await agent_db.tasks.get_total_unique_step_order_count_by_task_ids(
- task_ids=[task.task_id],
- organization_id=organization.organization_id,
- )
- == 2
- )
diff --git a/tests/unit/test_chain_click_blocked_anchor_navigation.py b/tests/unit/test_chain_click_blocked_anchor_navigation.py
index 9f4d02a02..fff3b0c56 100644
--- a/tests/unit/test_chain_click_blocked_anchor_navigation.py
+++ b/tests/unit/test_chain_click_blocked_anchor_navigation.py
@@ -9,13 +9,15 @@ fallback for the ``blocking_element is None and blocked is True`` branch only.
from __future__ import annotations
-from unittest.mock import AsyncMock, MagicMock
+import socket
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, call
import pytest
from playwright.async_api import TimeoutError as PlaywrightTimeoutError
from skyvern.config import settings
-from skyvern.exceptions import BlockedHost, InvalidUrl, SkyvernHTTPException
+from skyvern.exceptions import BlockedHost, BlockedNavigationDestination, InvalidUrl, SkyvernHTTPException
from skyvern.utils.url_validators import validate_fetch_url
from skyvern.webeye.utils import dom as dom_module
from skyvern.webeye.utils.dom import InteractiveElement, SkyvernElement
@@ -62,22 +64,19 @@ def _make_page(url: str = "https://portal.example.com/dashboard") -> MagicMock:
return page
[email protected](autouse=True)
+def _stub_skyvern_frame_evaluate(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ dom_module.SkyvernFrame,
+ "evaluate",
+ AsyncMock(return_value=None),
+ )
+ monkeypatch.setattr(dom_module, "validate_fetch_url", lambda url: url, raising=False)
+
+
class TestTryNavigateViaHref:
"""Unit tests for ``SkyvernElement.try_navigate_via_href``."""
- @pytest.fixture(autouse=True)
- def _stub_skyvern_frame_evaluate(self, monkeypatch: pytest.MonkeyPatch) -> None:
- # Default: normalized-href evaluate is unavailable, so the static
- # ``urljoin`` fallback path is exercised. Tests that specifically
- # need a normalized value (or an evaluate failure) re-patch this
- # attribute via their own ``monkeypatch`` fixture.
- monkeypatch.setattr(
- dom_module.SkyvernFrame,
- "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,
@@ -304,6 +303,100 @@ class TestTryNavigateViaHref:
page.goto.assert_not_called()
+def _public_resolver(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))]
+
+
+_UNRESOLVABLE_HOST = "unresolvable.example.test"
+
+
+def _resolver_with_unresolvable_host(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:
+ if host == _UNRESOLVABLE_HOST:
+ raise OSError("dns unavailable")
+ return _public_resolver(host, port, *args, **kwargs)
+
+
+def _redirect_chain(*urls: str) -> SimpleNamespace:
+ """page.goto-style response whose followed redirect chain visited ``urls`` in order."""
+ request: SimpleNamespace | None = None
+ for url in urls:
+ request = SimpleNamespace(url=url, redirected_from=request)
+ return SimpleNamespace(request=request)
+
+
+_METADATA_HOP = "http://169.254.169.254/latest/meta-data/"
+
+
+async def test_try_navigate_via_href_refuses_a_blocked_redirect_hop(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A public anchor that redirects to an internal host must not resolve as a success.
+
+ The generic ``except`` on this path swallows failures into a coordinate-click fallback, so a
+ swallowed guard would turn a blocked redirect into a physical click on the page.
+ """
+ elem = _make_anchor_element(href="/target")
+ page = _make_page()
+ monkeypatch.setattr(dom_module, "validate_fetch_url", validate_fetch_url, raising=False)
+ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", _public_resolver)
+ elem.get_frame().goto = AsyncMock(return_value=_redirect_chain("https://portal.example.com/target", _METADATA_HOP))
+
+ with pytest.raises(BlockedHost) as exc_info:
+ await elem.try_navigate_via_href(page=page)
+
+ # The click ladder branches on ``isinstance(e, BlockedHost)``; BlockedNavigationDestination is
+ # not in that hierarchy, so raising it here would ride the ladder into a coordinate click.
+ assert not isinstance(exc_info.value, BlockedNavigationDestination)
+ page.goto.assert_awaited_once_with("about:blank")
+
+
+async def test_try_navigate_via_href_allows_a_public_redirect_chain(monkeypatch: pytest.MonkeyPatch) -> None:
+ elem = _make_anchor_element(href="/target")
+ page = _make_page()
+ monkeypatch.setattr(dom_module, "validate_fetch_url", validate_fetch_url, raising=False)
+ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", _public_resolver)
+ elem.get_frame().goto = AsyncMock(
+ return_value=_redirect_chain("https://portal.example.com/target", "https://cdn.example.test/final")
+ )
+
+ assert await elem.try_navigate_via_href(page=page) == "https://portal.example.com/target"
+ page.goto.assert_not_awaited()
+
+
+async def test_navigate_to_a_href_refuses_a_blocked_redirect_hop(monkeypatch: pytest.MonkeyPatch) -> None:
+ elem = _make_anchor_element(href="https://external.example.test/target", target="_blank")
+ page = _make_page()
+ monkeypatch.setattr(dom_module, "validate_fetch_url", validate_fetch_url, raising=False)
+ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", _public_resolver)
+ page.goto = AsyncMock(return_value=_redirect_chain("https://external.example.test/target", _METADATA_HOP))
+
+ with pytest.raises(BlockedHost):
+ await elem.navigate_to_a_href(page=page)
+
+ assert page.goto.await_args_list == [
+ call("https://external.example.test/target", timeout=settings.BROWSER_LOADING_TIMEOUT_MS),
+ call("about:blank"),
+ ]
+
+
+async def test_navigate_to_a_href_allows_a_public_redirect_chain(monkeypatch: pytest.MonkeyPatch) -> None:
+ elem = _make_anchor_element(href="https://external.example.test/target", target="_blank")
+ page = _make_page()
+ monkeypatch.setattr(dom_module, "validate_fetch_url", validate_fetch_url, raising=False)
+ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", _public_resolver)
+ page.goto = AsyncMock(
+ return_value=_redirect_chain("https://external.example.test/target", "https://cdn.example.test/final")
+ )
+
+ assert await elem.navigate_to_a_href(page=page) == "https://external.example.test/target"
+ page.goto.assert_awaited_once_with(
+ "https://external.example.test/target",
+ timeout=settings.BROWSER_LOADING_TIMEOUT_MS,
+ )
+
+
@pytest.mark.asyncio
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")
@@ -341,6 +434,8 @@ class TestChainClickBlockedAnchorNavigation:
is_checked_mock: AsyncMock | None = None,
repeat: int = 1,
blocking_element: SkyvernElement | None = None,
+ real_href_navigation: bool = False,
+ navigation_response: object | None = None,
) -> tuple[list, AsyncMock, AsyncMock]:
"""Invoke chain_click through the ``blocking_element is None`` path
with tightly-scoped stubs. Returns (results, coordinate_click_mock,
@@ -375,25 +470,13 @@ class TestChainClickBlockedAnchorNavigation:
)
# Build a minimal element with the stubs chain_click reaches.
- elem = object.__new__(SkyvernElement)
+ elem = _make_anchor_element(href=href, tag=tag)
# chain_click's LOG.info calls invoke ``str(skyvern_element)`` which
# goes through ``SkyvernElement.__repr__``; that reads the private
# ``__static_element`` attribute set by ``__init__``. Since we bypass
# ``__init__`` here, seed the name-mangled attribute directly.
elem._SkyvernElement__static_element = {"id": "AAA3", "tagName": tag} # type: ignore[attr-defined]
- elem.get_tag_name = MagicMock(return_value=tag) # type: ignore[method-assign]
- elem.get_id = MagicMock(return_value="AAA3") # type: ignore[method-assign]
- elem.get_element_handler = AsyncMock(return_value=MagicMock()) # type: ignore[method-assign]
elem.locator = MagicMock()
-
- async def _get_attr(name: str, mode: str = "dynamic", **_: object) -> str | None:
- if name == "href":
- return href
- if name == "onclick":
- return None
- return None
-
- elem.get_attr = AsyncMock(side_effect=_get_attr) # type: ignore[method-assign]
elem.navigate_to_a_href = AsyncMock(return_value=None) # type: ignore[method-assign]
elem.find_bound_label_by_attr_id = AsyncMock(return_value=None) # type: ignore[method-assign]
elem.find_bound_label_by_direct_parent = AsyncMock(return_value=None) # type: ignore[method-assign]
@@ -411,12 +494,15 @@ class TestChainClickBlockedAnchorNavigation:
else:
elem.is_checked = AsyncMock(return_value=None) # type: ignore[method-assign]
- try_navigate = AsyncMock(return_value=navigate_result)
+ if real_href_navigation:
+ elem.get_frame().goto = AsyncMock(return_value=navigation_response)
+ elem.resolve_http_href = AsyncMock(side_effect=[None, href]) # type: ignore[method-assign]
+ try_navigate = AsyncMock(wraps=elem.try_navigate_via_href)
+ else:
+ try_navigate = AsyncMock(return_value=navigate_result)
elem.try_navigate_via_href = try_navigate # type: ignore[method-assign]
- page = MagicMock()
- page.url = "https://portal.example.com/dashboard"
- page.goto = AsyncMock(return_value=None)
+ page = _make_page()
page.on = MagicMock()
task = MagicMock()
@@ -562,6 +648,95 @@ class TestChainClickBlockedAnchorNavigation:
navigate.assert_awaited_once()
coord_click.assert_awaited_once()
+ @pytest.mark.asyncio
+ async def test_blocked_anchor_entry_url_is_terminal_without_coordinate_click(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ from skyvern.webeye.actions.responses import ActionFailure
+
+ monkeypatch.setattr(dom_module, "validate_fetch_url", validate_fetch_url)
+
+ results, coordinate_click, navigate = await self._run_chain_click(
+ monkeypatch,
+ blocked=True,
+ tag=InteractiveElement.A,
+ href=_METADATA_HOP,
+ real_href_navigation=True,
+ )
+
+ assert len(results) == 1
+ assert isinstance(results[0], ActionFailure)
+ navigate.assert_awaited_once()
+ coordinate_click.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_unresolvable_anchor_entry_url_continues_to_coordinate_click(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ from skyvern.webeye.actions.responses import ActionSuccess
+
+ monkeypatch.setattr(dom_module, "validate_fetch_url", validate_fetch_url)
+ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", _resolver_with_unresolvable_host)
+
+ results, coordinate_click, navigate = await self._run_chain_click(
+ monkeypatch,
+ blocked=True,
+ tag=InteractiveElement.A,
+ href=f"https://{_UNRESOLVABLE_HOST}/target",
+ real_href_navigation=True,
+ )
+
+ assert isinstance(results[-1], ActionSuccess)
+ navigate.assert_awaited_once()
+ coordinate_click.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_blocked_anchor_redirect_hop_is_terminal_without_coordinate_click(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ from skyvern.webeye.actions.responses import ActionFailure
+
+ href = "https://external.example.test/target"
+ monkeypatch.setattr(dom_module, "validate_fetch_url", validate_fetch_url)
+ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", _public_resolver)
+
+ results, coordinate_click, navigate = await self._run_chain_click(
+ monkeypatch,
+ blocked=True,
+ tag=InteractiveElement.A,
+ href=href,
+ real_href_navigation=True,
+ navigation_response=_redirect_chain(href, _METADATA_HOP),
+ )
+
+ assert len(results) == 1
+ assert isinstance(results[0], ActionFailure)
+ navigate.assert_awaited_once()
+ coordinate_click.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_unresolvable_anchor_redirect_hop_continues_to_coordinate_click(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ from skyvern.webeye.actions.responses import ActionSuccess
+
+ href = "https://external.example.test/target"
+ monkeypatch.setattr(dom_module, "validate_fetch_url", validate_fetch_url)
+ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", _resolver_with_unresolvable_host)
+
+ results, coordinate_click, navigate = await self._run_chain_click(
+ monkeypatch,
+ blocked=True,
+ tag=InteractiveElement.A,
+ href=href,
+ real_href_navigation=True,
+ navigation_response=_redirect_chain(href, f"https://{_UNRESOLVABLE_HOST}/final"),
+ )
+
+ assert isinstance(results[-1], ActionSuccess)
+ navigate.assert_awaited_once()
+ coordinate_click.assert_awaited_once()
+
def test_dom_module_exports_try_navigate_via_href() -> None:
"""Sanity check that the helper is a method on ``SkyvernElement``."""
diff --git a/tests/unit/test_download_file_action_handler.py b/tests/unit/test_download_file_action_handler.py
index b3c20c389..7bc11c349 100644
--- a/tests/unit/test_download_file_action_handler.py
+++ b/tests/unit/test_download_file_action_handler.py
@@ -5,13 +5,16 @@ import time
from collections.abc import Callable
from datetime import UTC, datetime
from pathlib import Path
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, call, patch
import pytest
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
+from skyvern.config import settings
from skyvern.constants import BROWSER_DOWNLOAD_TIMEOUT
from skyvern.errors.errors import UserDefinedError
+from skyvern.exceptions import BlockedHost
from skyvern.forge.sdk.models import StepStatus
from skyvern.webeye.actions.actions import ActionStatus, ClickAction, DownloadFileAction
from skyvern.webeye.actions.handler import (
@@ -1540,6 +1543,70 @@ async def test_handle_download_file_action_with_byte_data() -> None:
assert f.read() == test_bytes
+def _download_redirect_chain(*urls: str) -> SimpleNamespace:
+ """page.goto-style response whose followed redirect chain visited ``urls`` in order."""
+ request: SimpleNamespace | None = None
+ for url in urls:
+ request = SimpleNamespace(url=url, redirected_from=request)
+ return SimpleNamespace(request=request)
+
+
+def _refuse_metadata_hop(url: str) -> str:
+ if "169.254.169.254" in url:
+ raise BlockedHost(host=url)
+ return url
+
+
+async def test_handle_download_file_action_refuses_a_blocked_redirect_hop() -> None:
+ """A public download_url that redirects to the metadata endpoint must fail closed."""
+ now = datetime.now(UTC)
+ organization = make_organization(now)
+ task = make_task(now, organization)
+ step = make_step(now, task, step_id="step-1", status=StepStatus.created, order=0, output=None)
+
+ page = MagicMock()
+ page.goto = AsyncMock(
+ return_value=_download_redirect_chain(
+ "https://example.com/file.pdf", "http://169.254.169.254/latest/meta-data/"
+ )
+ )
+ browser_state = MagicMock()
+ scraped_page = ScrapedPage(
+ elements=[],
+ element_tree=[],
+ element_tree_trimmed=[],
+ _browser_state=browser_state,
+ _clean_up_func=AsyncMock(return_value=[]),
+ _scrape_exclude=None,
+ )
+
+ action = DownloadFileAction(
+ file_name="downloaded_file.pdf",
+ download_url="https://example.com/file.pdf",
+ organization_id=task.organization_id,
+ task_id=task.task_id,
+ step_id=step.step_id,
+ )
+
+ with (
+ patch("skyvern.webeye.actions.handler.initialize_download_dir", return_value="/tmp"),
+ patch("skyvern.webeye.actions.handler.validate_fetch_url", side_effect=_refuse_metadata_hop),
+ ):
+ result = await handle_download_file_action(action, page, scraped_page, task, step)
+
+ # This handler wraps its whole body in ``except Exception -> ActionFailure``, so a blocked hop
+ # surfaces as a failed action rather than propagating. The pre-existing entry-URL check on this
+ # path already behaves the same way; what matters is that it never reports success.
+ assert len(result) == 1
+ assert isinstance(result[0], ActionFailure)
+ assert result[0].exception_type == BlockedHost.__name__
+ assert page.goto.await_args_list == [
+ call("https://example.com/file.pdf", timeout=settings.BROWSER_LOADING_TIMEOUT_MS),
+ call("about:blank"),
+ ]
+
+
@pytest.mark.asyncio
async def test_handle_download_file_action_with_download_url() -> None:
"""Test that when download_url is provided, page.goto is called and returns ActionSuccess"""
diff --git a/tests/unit/test_navigation_action_handlers.py b/tests/unit/test_navigation_action_handlers.py
index 54d3e94d4..3db435bc0 100644
--- a/tests/unit/test_navigation_action_handlers.py
+++ b/tests/unit/test_navigation_action_handlers.py
@@ -1,9 +1,12 @@
"""Tests for the GOTO_URL / RELOAD_PAGE action handlers."""
-from unittest.mock import AsyncMock, MagicMock
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, call
import pytest
+from skyvern.config import settings
+from skyvern.exceptions import BlockedHost
from skyvern.webeye.actions import actions
from skyvern.webeye.actions.handler import handle_goto_url_action, handle_reload_page_action
from skyvern.webeye.actions.responses import ActionSuccess
@@ -46,3 +49,53 @@ async def test_reload_page_reloads_and_stops_batch() -> None:
assert isinstance(result[0], ActionSuccess)
assert result[0].skip_remaining_actions is True
page.reload.assert_awaited_once()
+
+
+_METADATA_HOP = "http://169.254.169.254/latest/meta-data/"
+
+
+def _redirect_chain(*urls: str) -> SimpleNamespace:
+ """page.goto-style response whose followed redirect chain visited ``urls`` in order."""
+ request: SimpleNamespace | None = None
+ for url in urls:
+ request = SimpleNamespace(url=url, redirected_from=request)
+ return SimpleNamespace(request=request)
+
+
+def _refuse_metadata(url: str) -> str:
+ if "169.254.169.254" in url:
+ raise BlockedHost(host=url)
+ return url
+
+
+async def test_goto_url_refuses_a_blocked_redirect_hop(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr("skyvern.webeye.actions.handler.validate_fetch_url", _refuse_metadata)
+ page = MagicMock()
+ page.goto = AsyncMock(return_value=_redirect_chain("https://example.test/page", _METADATA_HOP))
+
+ action = actions.GotoUrlAction(url="https://example.test/page")
+
+ with pytest.raises(BlockedHost):
+ await handle_goto_url_action(action, page, MagicMock(), _task(), MagicMock())
+
+ assert page.goto.await_args_list == [
+ call("https://example.test/page", timeout=settings.BROWSER_LOADING_TIMEOUT_MS),
+ call("about:blank"),
+ ]
+
+
+async def test_goto_url_allows_a_public_redirect_chain(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr("skyvern.webeye.actions.handler.validate_fetch_url", _refuse_metadata)
+ page = MagicMock()
+ page.goto = AsyncMock(return_value=_redirect_chain("https://example.test/page", "https://cdn.example.test/final"))
+
+ action = actions.GotoUrlAction(url="https://example.test/page")
+ result = await handle_goto_url_action(action, page, MagicMock(), _task(), MagicMock())
+
+ assert isinstance(result[0], ActionSuccess)
+ page.goto.assert_awaited_once_with(
+ "https://example.test/page",
+ timeout=settings.BROWSER_LOADING_TIMEOUT_MS,
+ )
diff --git a/tests/unit/test_url_validators.py b/tests/unit/test_url_validators.py
index c32aafb01..81fea3481 100644
--- a/tests/unit/test_url_validators.py
+++ b/tests/unit/test_url_validators.py
@@ -303,6 +303,49 @@ def test_validate_fetch_url_blocks_localhost_resolving_to_private_host(monkeypat
validate_fetch_url("http://localhost:8000/")
+ "url",
+ [
+ "ftp://public.example.test/file",
+ "chrome://settings",
+ "file:///etc/passwd",
+ "javascript:alert(1)",
+ ],
+)
+def test_validate_fetch_url_refuses_other_schemes_without_resolving(monkeypatch: pytest.MonkeyPatch, url: str) -> None:
+ """A scheme we refuse outright must not emit a DNS query for its host.
+
+ Resolving decides nothing for these, and it turns every rejected URL into a lookup of an
+ attacker-supplied name.
+ """
+ resolved: list[str] = []
+
+ def record(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:
+ resolved.append(host)
+ raise socket.gaierror("should not be called")
+
+ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", record)
+
+ with pytest.raises(SkyvernHTTPException):
+ validate_fetch_url(url)
+
+ assert resolved == []
+
+
+def test_validate_fetch_url_still_resolves_a_backslash_authority_host(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The http backslash-authority vector still resolves; only refused schemes skip DNS."""
+
+ def resolves_internal(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_internal)
+
+ with pytest.raises(BlockedHost):
+ validate_fetch_url("http://sneaky.example.test\\@public.example.test/")
+
+
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")
diff --git a/tests/unit_tests/webeye/test_navigation_retry.py b/tests/unit_tests/webeye/test_navigation_retry.py
index f591ee26f..5fe982a0d 100644
--- a/tests/unit_tests/webeye/test_navigation_retry.py
+++ b/tests/unit_tests/webeye/test_navigation_retry.py
@@ -1,12 +1,17 @@
from __future__ import annotations
import socket
-from unittest.mock import AsyncMock
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
import pytest
-from skyvern.exceptions import BlockedNavigationDestination, FailedToNavigateToUrl
-from skyvern.webeye.navigation import navigate_with_retry, validate_navigation_destination
+from skyvern.exceptions import BlockedHost, BlockedNavigationDestination, FailedToNavigateToUrl, UnresolvableHost
+from skyvern.webeye.navigation import (
+ navigate_with_retry,
+ revalidate_redirect_chain,
+ validate_navigation_destination,
+)
from skyvern.webeye.real_browser_state import RealBrowserState
@@ -401,3 +406,80 @@ async def test_navigate_with_retry_revalidates_every_redirect_hop() -> None:
)
settle.assert_not_awaited()
+
+
+async def test_revalidate_redirect_chain_checks_every_hop_and_the_final_destination() -> None:
+ response = _redirect_response(
+ "https://entry.example.test/a",
+ "https://mid.example.test/b",
+ "https://final.example.test/c",
+ )
+
+ seen: list[str] = []
+ reset_page = AsyncMock()
+ await revalidate_redirect_chain(response, seen.append, reset_page)
+
+ assert sorted(seen) == [
+ "https://entry.example.test/a",
+ "https://final.example.test/c",
+ "https://mid.example.test/b",
+ ]
+ reset_page.assert_not_awaited()
+
+
+async def test_revalidate_redirect_chain_propagates_the_validators_exception() -> None:
+ response = _redirect_response(
+ "https://entry.example.test/a",
+ "http://169.254.169.254/latest/meta-data/",
+ )
+
+ refusal = BlockedHost("169.254.169.254")
+ reset_page = AsyncMock()
+
+ def refuse_metadata(url: str) -> None:
+ if "169.254.169.254" in url:
+ raise refusal
+
+ with pytest.raises(BlockedHost) as exc_info:
+ await revalidate_redirect_chain(response, refuse_metadata, reset_page)
+
+ assert exc_info.value is refusal
+ reset_page.assert_awaited_once_with("about:blank")
+
+
[email protected]("refusal", [BlockedHost("blocked.test"), UnresolvableHost("unresolvable.test")])
+async def test_revalidate_redirect_chain_preserves_refusal_when_page_reset_fails(
+ monkeypatch: pytest.MonkeyPatch,
+ refusal: BlockedHost,
+) -> None:
+ response = _redirect_response(
+ "https://entry.example.test/a",
+ "http://169.254.169.254/latest/meta-data/",
+ )
+ reset_page = AsyncMock(side_effect=RuntimeError("reset failed"))
+ log_exception = MagicMock()
+ monkeypatch.setattr("skyvern.webeye.navigation.LOG.exception", log_exception)
+
+ def refuse_metadata(url: str) -> None:
+ if "169.254.169.254" in url:
+ raise refusal
+
+ with pytest.raises(type(refusal)) as exc_info:
+ await revalidate_redirect_chain(response, refuse_metadata, reset_page)
+
+ assert exc_info.value is refusal
+ reset_page.assert_awaited_once_with("about:blank")
+ log_exception.assert_called_once_with("Failed to reset page after redirect refusal")
+
+
+async def test_revalidate_redirect_chain_tolerates_a_response_without_a_request() -> None:
+ calls: list[str] = []
+
+ await revalidate_redirect_chain(None, calls.append)
+ await revalidate_redirect_chain(SimpleNamespace(request=None), calls.append)
+
+ assert calls == []