Skip to content

Automate browser based workflows with AI

Prefer the Playwright error name in tab-open failure reasons (SKY-13338 follow-up) (#8042)

Aaron Perezb337820cef7e
diff --git a/skyvern/cli/core/browser_ops.py b/skyvern/cli/core/browser_ops.py
index d4d37bde4..d267a6a82 100644
--- a/skyvern/cli/core/browser_ops.py
+++ b/skyvern/cli/core/browser_ops.py
@@ -18,13 +18,21 @@ from typing import Any, Callable, Literal
import structlog
+from skyvern.exceptions import BlockedHost, SkyvernHTTPException
from skyvern.forge.sdk.settings_manager import SettingsManager
+from skyvern.utils.url_validators import validate_fetch_url
from skyvern.webeye.utils.page import JS_FUNCTION_DEFS, SkyvernFrame
from .guards import GuardError
LOG = structlog.get_logger(__name__)
+LOCALHOST_RECOVERY_HINT = (
+ "Run `pip install skyvern && skyvern browser serve --tunnel` to bridge "
+ "your local dev server to a cloud browser via ngrok. "
+ "Or use `local=true` in skyvern_browser_session_create for a local browser."
+)
+
@dataclass
class NavigateResult:
@@ -67,8 +75,20 @@ async def do_navigate(
url: str,
timeout: int = 30000,
wait_until: str | None = None,
+ *,
+ can_access_localhost: bool = False,
+ is_localhost_destination: bool = False,
) -> NavigateResult:
- await page.goto(url, timeout=timeout, wait_until=wait_until)
+ try:
+ validated_url = await asyncio.to_thread(validate_fetch_url, url)
+ except BlockedHost as e:
+ if not (can_access_localhost and is_localhost_destination):
+ hint = LOCALHOST_RECOVERY_HINT if is_localhost_destination else "Use a public HTTP(S) URL"
+ raise GuardError(str(e), hint) from e
+ validated_url = url
+ except SkyvernHTTPException as e:
+ raise GuardError(str(e), "Use a valid public HTTP(S) URL") from e
+ await page.goto(validated_url, timeout=timeout, wait_until=wait_until)
return NavigateResult(url=page.url, title=await page.title())
diff --git a/skyvern/cli/mcp_tools/browser.py b/skyvern/cli/mcp_tools/browser.py
index eee462fca..3150bbcf9 100644
--- a/skyvern/cli/mcp_tools/browser.py
+++ b/skyvern/cli/mcp_tools/browser.py
@@ -21,6 +21,7 @@ from pydantic import Field
from skyvern.cli.core.action_log import enqueue_action_event
from skyvern.cli.core.browser_ops import (
_ALLOWED_EXECUTE_TOOLS,
+ LOCALHOST_RECOVERY_HINT,
MAX_EXECUTE_STEPS,
CustomSelectClassifyError,
CustomSelectMatchError,
@@ -61,11 +62,13 @@ from skyvern.cli.core.session_manager import is_stateless_http_mode
from skyvern.cli.core.trajectory_store import append_trajectory_entry
from skyvern.config import settings
from skyvern.core.script_generations.skyvern_page import SkyvernPage
+from skyvern.exceptions import BlockedHost, SkyvernHTTPException
from skyvern.forge.sdk.api.files import resolve_run_download_id
from skyvern.forge.sdk.copilot.typed_value_policy import typed_text_looks_secret
from skyvern.forge.sdk.core import skyvern_context
from skyvern.schemas.action_log import ActionLogOutcome, project_action_event
from skyvern.schemas.run_blocks import CredentialType
+from skyvern.utils.url_validators import validate_fetch_url
from ._common import (
AI_FALLBACK_DESCRIPTION,
@@ -456,18 +459,28 @@ async def skyvern_navigate(
action_result = _action_result_factory(ctx=ctx, page=page)
- if _must_reject_localhost_url(ctx, url):
+ can_access_localhost = ctx.can_access_localhost is True
+ is_localhost_destination = is_localhost_url(url)
+ allow_localhost = can_access_localhost and is_localhost_destination
+ try:
+ validated_url = await asyncio.to_thread(validate_fetch_url, url)
+ except BlockedHost as e:
+ if allow_localhost:
+ validated_url = url
+ else:
+ hint = LOCALHOST_RECOVERY_HINT if is_localhost_destination else "Use a public HTTP(S) URL"
+ return action_result(
+ "skyvern_navigate",
+ ok=False,
+ browser_context=ctx,
+ error=make_error(ErrorCode.INVALID_INPUT, str(e), hint),
+ )
+ except SkyvernHTTPException as e:
return action_result(
"skyvern_navigate",
ok=False,
browser_context=ctx,
- error=make_error(
- ErrorCode.INVALID_INPUT,
- "Cloud browsers cannot reach localhost URLs",
- "Run `pip install skyvern && skyvern browser serve --tunnel` to bridge "
- "your local dev server to a cloud browser via ngrok. "
- "Or use `local=true` in skyvern_browser_session_create for a local browser.",
- ),
+ error=make_error(ErrorCode.INVALID_INPUT, str(e), "Use a valid public HTTP(S) URL"),
)
# Any navigation attempt may destroy iframes — clear frame state upfront
@@ -478,7 +491,14 @@ async def skyvern_navigate(
with Timer() as timer:
try:
- result = await do_navigate(page, url, timeout=timeout, wait_until=wait_until)
+ result = await do_navigate(
+ page,
+ validated_url,
+ timeout=timeout,
+ wait_until=wait_until,
+ can_access_localhost=can_access_localhost,
+ is_localhost_destination=is_localhost_destination,
+ )
timer.mark("sdk")
except GuardError as e:
return action_result(
@@ -2623,9 +2643,7 @@ async def skyvern_run_task(
error=make_error(
ErrorCode.INVALID_INPUT,
"Cloud browsers cannot reach localhost URLs",
- "Run `pip install skyvern && skyvern browser serve --tunnel` to bridge "
- "your local dev server to a cloud browser via ngrok. "
- "Or use `local=true` in skyvern_browser_session_create for a local browser.",
+ LOCALHOST_RECOVERY_HINT,
),
)
diff --git a/skyvern/cli/mcp_tools/tabs.py b/skyvern/cli/mcp_tools/tabs.py
index 07b2fb3ef..a62db297a 100644
--- a/skyvern/cli/mcp_tools/tabs.py
+++ b/skyvern/cli/mcp_tools/tabs.py
@@ -16,8 +16,11 @@ from pydantic import BaseModel, Field
from skyvern.cli.core.browser_ops import do_screenshot
from skyvern.cli.core.guards import GuardError, validate_wait_until
+from skyvern.exceptions import BlockedHost, SkyvernHTTPException
+from skyvern.utils.url_validators import validate_fetch_url
from ._common import ErrorCode, Timer, make_error, make_result, save_artifact
+from ._localhost import is_localhost_url
from ._session import (
BrowserNotAvailableError,
clear_session_ref_map,
@@ -148,6 +151,26 @@ async def skyvern_tab_new(
if browser is None:
return make_result("skyvern_tab_new", ok=False, error=no_browser_error())
+ if url:
+ allow_localhost = ctx.can_access_localhost is True and is_localhost_url(url)
+ try:
+ url = await asyncio.to_thread(validate_fetch_url, url)
+ except BlockedHost as e:
+ if not allow_localhost:
+ return make_result(
+ "skyvern_tab_new",
+ ok=False,
+ browser_context=ctx,
+ error=make_error(ErrorCode.INVALID_INPUT, str(e), "Use a public HTTP(S) URL"),
+ )
+ except SkyvernHTTPException as e:
+ return make_result(
+ "skyvern_tab_new",
+ ok=False,
+ browser_context=ctx,
+ error=make_error(ErrorCode.INVALID_INPUT, str(e), "Use a valid public HTTP(S) URL"),
+ )
+
prev_active = state._active_page
new_page = None
with Timer() as timer:
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 0b8f4b25c..81360eb5a 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -3738,6 +3738,16 @@ class CodeBlockCaptchaError(Exception):
CODE_BLOCK_TAB_OPEN_FAILURE_REASON = "Code block could not open a tab in the browser session; the session's browser may be held by another Playwright client"
+
+def _page_open_error_label(error: BaseException) -> str:
+ # Playwright maps only TimeoutError/TargetClosedError to their own Python classes; every
+ # other driver failure is the base Error whose .name carries the real class (e.g. TypeError).
+ name = getattr(error, "name", None)
+ if isinstance(name, str) and name:
+ return name
+ return type(error).__name__
+
+
_CODE_BLOCK_CAPTCHA_CHECKBOX_SELECTOR = ", ".join(
(
'input[type="checkbox"][id*="captcha" i]',
@@ -5558,7 +5568,7 @@ async def wrapper({default_args}):
)
return await self.build_block_result(
success=False,
- failure_reason=f"{CODE_BLOCK_TAB_OPEN_FAILURE_REASON} ({type(e).__name__})",
+ failure_reason=f"{CODE_BLOCK_TAB_OPEN_FAILURE_REASON} ({_page_open_error_label(e)})",
output_parameter_value=None,
status=BlockStatus.failed,
workflow_run_block_id=workflow_run_block_id,
diff --git a/tests/unit/test_cli_shared_core.py b/tests/unit/test_cli_shared_core.py
index 9a0f3b5d2..0f599903a 100644
--- a/tests/unit/test_cli_shared_core.py
+++ b/tests/unit/test_cli_shared_core.py
@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
+from skyvern.cli.core import browser_ops
from skyvern.cli.core.browser_ops import do_act, do_extract, do_navigate, do_screenshot, parse_extract_schema
from skyvern.cli.core.guards import (
GuardError,
@@ -20,6 +21,11 @@ from skyvern.cli.core.session_ops import do_session_close, do_session_create, do
from skyvern.client.types.extensions import Extensions
CAPTCHA_SOLVER_EXTENSION: Extensions = "captcha-solver"
+LOCALHOST_RECOVERY_HINT = (
+ "Run `pip install skyvern && skyvern browser serve --tunnel` to bridge "
+ "your local dev server to a cloud browser via ngrok. "
+ "Or use `local=true` in skyvern_browser_session_create for a local browser."
+)
# ---------------------------------------------------------------------------
# guards.py
@@ -97,11 +103,12 @@ def test_resolve_ai_mode(selector: str | None, intent: str | None, expected: tup
@pytest.mark.asyncio
-async def test_do_navigate_success() -> None:
+async def test_do_navigate_success(monkeypatch: pytest.MonkeyPatch) -> None:
page = MagicMock()
page.goto = AsyncMock()
page.url = "https://example.com/final"
page.title = AsyncMock(return_value="Example")
+ monkeypatch.setattr(browser_ops, "validate_fetch_url", lambda url: url)
result = await do_navigate(page, "https://example.com")
assert result.url == "https://example.com/final"
@@ -109,17 +116,81 @@ async def test_do_navigate_success() -> None:
@pytest.mark.asyncio
-async def test_do_navigate_passes_wait_until_through() -> None:
+async def test_do_navigate_passes_wait_until_through(monkeypatch: pytest.MonkeyPatch) -> None:
page = MagicMock()
page.goto = AsyncMock()
page.url = "https://example.com/final"
page.title = AsyncMock(return_value="Example")
+ monkeypatch.setattr(browser_ops, "validate_fetch_url", lambda url: url)
result = await do_navigate(page, "https://example.com", wait_until="badvalue")
assert result.url == "https://example.com/final"
page.goto.assert_awaited_once_with("https://example.com", timeout=30000, wait_until="badvalue")
+ "url",
+ [
+ pytest.param("http://169.254.169.254/", id="metadata"),
+ pytest.param("http://10.20.30.40/", id="private"),
+ pytest.param("http://127.0.0.2/", id="alternate-loopback"),
+ pytest.param("http://2130706433/", id="integer-loopback"),
+ ],
+)
+async def test_do_navigate_rejects_unsafe_url(url: str) -> None:
+ page = MagicMock()
+ page.goto = AsyncMock()
+
+ with pytest.raises(GuardError):
+ await do_navigate(page, url)
+
+ page.goto.assert_not_awaited()
+
+
[email protected]("url", ["http://localhost:3000/", "http://127.0.0.1:8000/"])
+async def test_do_navigate_allows_local_url_when_context_permits(url: str) -> None:
+ page = MagicMock()
+ page.goto = AsyncMock()
+ page.url = url
+ page.title = AsyncMock(return_value="Local")
+
+ result = await do_navigate(
+ page,
+ url,
+ can_access_localhost=True,
+ is_localhost_destination=True,
+ )
+
+ assert result.url == url
+ page.goto.assert_awaited_once_with(url, timeout=30000, wait_until=None)
+
+
[email protected]("url", ["http://169.254.169.254/", "http://10.20.30.40/"])
+async def test_do_navigate_rejects_non_loopback_internal_url_when_context_permits(url: str) -> None:
+ page = MagicMock()
+ page.goto = AsyncMock()
+
+ with pytest.raises(GuardError):
+ await do_navigate(page, url, can_access_localhost=True)
+
+ page.goto.assert_not_awaited()
+
+
+async def test_do_navigate_rejects_local_url_when_context_does_not_permit() -> None:
+ page = MagicMock()
+ page.goto = AsyncMock()
+
+ with pytest.raises(GuardError) as exc_info:
+ await do_navigate(page, "http://127.0.0.1:8000/", is_localhost_destination=True)
+
+ assert exc_info.value.hint == LOCALHOST_RECOVERY_HINT
+ page.goto.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_do_screenshot_full_page() -> None:
page = MagicMock()
diff --git a/tests/unit/test_code_block_sandbox.py b/tests/unit/test_code_block_sandbox.py
index b53bb4d81..62ebd87d0 100644
--- a/tests/unit/test_code_block_sandbox.py
+++ b/tests/unit/test_code_block_sandbox.py
@@ -836,7 +836,10 @@ async def wrapper({default_args}):
assert result.output_parameter_value == {"value": "ok"}
async def _execute_against_tabless_session(
- self, monkeypatch: pytest.MonkeyPatch, open_page_raises: bool = False
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ open_page_raises: bool = False,
+ open_page_error: Exception | None = None,
) -> tuple[object, int, int]:
"""Run a block against a session whose context holds zero pages."""
@@ -846,16 +849,18 @@ async def wrapper({default_args}):
self.open_attempts = 0
self.created_pages = 0
- async def get_working_page(self) -> object | None:
- return None
-
async def get_or_create_page(self, *args: object, **kwargs: object) -> object:
self.open_attempts += 1
+ if open_page_error is not None:
+ raise open_page_error
if open_page_raises:
raise RuntimeError("browser is gone")
self.created_pages += 1
return object()
+ async def get_working_page(self) -> object | None:
+ return None
+
class FakeWorkflowRunContext:
values: dict[str, object] = {}
secrets: dict[str, object] = {}
@@ -930,6 +935,22 @@ async def wrapper({default_args}):
assert result.failure_reason == f"{CODE_BLOCK_TAB_OPEN_FAILURE_REASON} (RuntimeError)"
assert result.failure_reason != "No page found to run the code block"
+ @pytest.mark.asyncio
+ async def test_execute_reports_the_driver_error_name_when_the_tab_cannot_open(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """Playwright surfaces most driver failures as its base Error class, whose .name carries
+ the real error (parse_error sets it); the class name alone would render as just (Error)."""
+ from playwright.async_api import Error as PlaywrightError
+
+ driver_error = PlaywrightError("BrowserContext.new_page: Cannot read properties of undefined")
+ driver_error._name = "TypeError"
+
+ result, _, _ = await self._execute_against_tabless_session(monkeypatch, open_page_error=driver_error)
+
+ assert result.success is False
+ assert result.failure_reason == f"{CODE_BLOCK_TAB_OPEN_FAILURE_REASON} (TypeError)"
+
def test_poc_blocked_at_is_safe_code_gate(self) -> None:
"""The PoC payload is rejected before exec() is ever called."""
malicious_code = "proc = await asyncio.create_subprocess_shell('id')"
diff --git a/tests/unit/test_mcp_browser_tools.py b/tests/unit/test_mcp_browser_tools.py
index 499aac1c6..7bbcd3539 100644
--- a/tests/unit/test_mcp_browser_tools.py
+++ b/tests/unit/test_mcp_browser_tools.py
@@ -751,6 +751,7 @@ def _sdk_equivalent_page(monkeypatch: pytest.MonkeyPatch) -> None:
context = BrowserContext(mode="cloud_session", session_id="pbs_test")
monkeypatch.setenv("SKYVERN_DISABLE_CUSTOM_SELECT", "1")
monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, context)))
+ monkeypatch.setattr(mcp_browser, "validate_fetch_url", lambda url: url)
monkeypatch.setattr(mcp_browser, "get_current_session", lambda: SimpleNamespace(_working_frame=None))
monkeypatch.setattr(mcp_browser, "clear_session_ref_map", Mock())
monkeypatch.setattr(
diff --git a/tests/unit/test_mcp_localhost_guard.py b/tests/unit/test_mcp_localhost_guard.py
index 3b8ca234e..04c370d56 100644
--- a/tests/unit/test_mcp_localhost_guard.py
+++ b/tests/unit/test_mcp_localhost_guard.py
@@ -10,6 +10,12 @@ from skyvern.cli.core.result import BrowserContext
from skyvern.cli.mcp_tools import browser as mcp_browser
from skyvern.cli.mcp_tools._localhost import is_localhost_url
+LOCALHOST_RECOVERY_HINT = (
+ "Run `pip install skyvern && skyvern browser serve --tunnel` to bridge "
+ "your local dev server to a cloud browser via ngrok. "
+ "Or use `local=true` in skyvern_browser_session_create for a local browser."
+)
+
# ---------------------------------------------------------------------------
# is_localhost_url unit tests
# ---------------------------------------------------------------------------
@@ -78,7 +84,7 @@ async def test_navigate_rejects_localhost_on_cloud_session(
assert result["ok"] is False
assert result["error"]["code"] == mcp_browser.ErrorCode.INVALID_INPUT
assert "localhost" in result["error"]["message"].lower()
- assert "skyvern browser serve --tunnel" in result["error"]["hint"]
+ assert result["error"]["hint"] == LOCALHOST_RECOVERY_HINT
@pytest.mark.asyncio
@@ -91,13 +97,14 @@ async def test_navigate_rejects_127_0_0_1_on_cloud_session(monkeypatch: pytest.M
assert result["ok"] is False
assert result["error"]["code"] == mcp_browser.ErrorCode.INVALID_INPUT
- assert "localhost" in result["error"]["message"].lower()
+ assert "127.0.0.1" in result["error"]["message"]
+ assert result["error"]["hint"] == LOCALHOST_RECOVERY_HINT
@pytest.mark.asyncio
async def test_navigate_allows_localhost_on_local_session(monkeypatch: pytest.MonkeyPatch) -> None:
page = AsyncMock()
- ctx = BrowserContext(mode="local")
+ ctx = BrowserContext(mode="local", can_access_localhost=True)
monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, ctx)))
monkeypatch.setattr(
mcp_browser,
@@ -111,19 +118,20 @@ async def test_navigate_allows_localhost_on_local_session(monkeypatch: pytest.Mo
@pytest.mark.asyncio
-async def test_navigate_allows_localhost_on_cdp_session(monkeypatch: pytest.MonkeyPatch) -> None:
+async def test_navigate_rejects_localhost_when_context_permission_is_unknown(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
page = AsyncMock()
ctx = BrowserContext(mode="cdp", cdp_url="ws://localhost:9222")
monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, ctx)))
- monkeypatch.setattr(
- mcp_browser,
- "do_navigate",
- AsyncMock(return_value=AsyncMock(url="http://localhost:3000", title="App")),
- )
+ do_navigate = AsyncMock()
+ monkeypatch.setattr(mcp_browser, "do_navigate", do_navigate)
result = await mcp_browser.skyvern_navigate(url="http://localhost:3000")
- assert result["ok"] is True
+ assert result["ok"] is False
+ assert result["error"]["code"] == mcp_browser.ErrorCode.INVALID_INPUT
+ do_navigate.assert_not_awaited()
@pytest.mark.asyncio
@@ -143,27 +151,61 @@ async def test_navigate_attempts_localhost_when_cloud_session_can_access_localho
@pytest.mark.asyncio
-async def test_navigate_unknown_localhost_reachability_reports_real_navigation_error(
[email protected]("url", ["http://localhost:3000/", "http://127.0.0.1:8000/"])
+async def test_navigate_allows_local_url_when_context_permits(
monkeypatch: pytest.MonkeyPatch,
+ url: str,
) -> None:
page = AsyncMock()
- ctx = BrowserContext(mode="cloud_session", session_id="pbs_test")
+ ctx = BrowserContext(mode="cloud_session", session_id="pbs_test", can_access_localhost=True)
+ do_navigate = AsyncMock(return_value=AsyncMock(url=url, title="App"))
monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, ctx)))
- monkeypatch.setattr(mcp_browser, "do_navigate", AsyncMock(side_effect=RuntimeError("connection refused")))
+ monkeypatch.setattr(mcp_browser, "do_navigate", do_navigate)
- result = await mcp_browser.skyvern_navigate(url="http://localhost:3000")
+ result = await mcp_browser.skyvern_navigate(url=url)
+
+ assert result["ok"] is True
+ do_navigate.assert_awaited_once()
+
+
+ ("url", "can_access_localhost"),
+ [
+ pytest.param("http://169.254.169.254/", False, id="metadata"),
+ pytest.param("http://10.20.30.40/", False, id="private"),
+ pytest.param("http://127.0.0.2/", False, id="alternate-loopback"),
+ pytest.param("http://2130706433/", False, id="integer-loopback"),
+ pytest.param("http://169.254.169.254/", True, id="metadata-local-context"),
+ pytest.param("http://10.20.30.40/", True, id="private-local-context"),
+ ],
+)
+async def test_navigate_rejects_unsafe_url_before_delegate(
+ monkeypatch: pytest.MonkeyPatch, url: str, can_access_localhost: bool
+) -> None:
+ page = AsyncMock()
+ ctx = BrowserContext(
+ mode="local" if can_access_localhost else "cloud_session",
+ session_id=None if can_access_localhost else "pbs_test",
+ can_access_localhost=can_access_localhost,
+ )
+ do_navigate = AsyncMock()
+ monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, ctx)))
+ monkeypatch.setattr(mcp_browser, "do_navigate", do_navigate)
+
+ result = await mcp_browser.skyvern_navigate(url=url)
assert result["ok"] is False
- assert result["error"]["code"] == mcp_browser.ErrorCode.ACTION_FAILED
- assert result["error"]["message"] == "connection refused"
- assert result["error"]["message"] != "Cloud browsers cannot reach localhost URLs"
+ assert result["error"]["code"] == mcp_browser.ErrorCode.INVALID_INPUT
+ do_navigate.assert_not_awaited()
@pytest.mark.asyncio
async def test_navigate_allows_public_url_on_cloud_session(monkeypatch: pytest.MonkeyPatch) -> None:
page = AsyncMock()
- ctx = BrowserContext(mode="cloud_session", session_id="pbs_test")
+ ctx = BrowserContext(mode="cloud_session", session_id="pbs_test", can_access_localhost=False)
monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, ctx)))
+ monkeypatch.setattr(mcp_browser, "validate_fetch_url", lambda url: url)
monkeypatch.setattr(
mcp_browser,
"do_navigate",
@@ -194,7 +236,7 @@ async def test_run_task_rejects_localhost_on_cloud_session(monkeypatch: pytest.M
assert result["ok"] is False
assert result["error"]["code"] == mcp_browser.ErrorCode.INVALID_INPUT
assert "localhost" in result["error"]["message"].lower()
- assert "skyvern browser serve --tunnel" in result["error"]["hint"]
+ assert result["error"]["hint"] == LOCALHOST_RECOVERY_HINT
@pytest.mark.asyncio
diff --git a/tests/unit/test_mcp_response_size_cap.py b/tests/unit/test_mcp_response_size_cap.py
index 5662532ce..6e92a5b5e 100644
--- a/tests/unit/test_mcp_response_size_cap.py
+++ b/tests/unit/test_mcp_response_size_cap.py
@@ -237,6 +237,7 @@ async def test_every_registered_extract_tool_caps_an_oversize_extraction(
ctx = BrowserContext(mode="cloud_session", session_id="pbs_test")
page = SimpleNamespace(page=SimpleNamespace())
monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, ctx)))
+ monkeypatch.setattr(mcp_browser, "validate_fetch_url", lambda url: url)
monkeypatch.setattr(mcp_browser, "get_current_session", lambda: SimpleNamespace(_working_frame=None))
monkeypatch.setattr(mcp_browser, "clear_session_ref_map", Mock())
monkeypatch.setattr(mcp_browser, "do_extract", AsyncMock(return_value=SimpleNamespace(extracted=oversize)))
@@ -268,6 +269,7 @@ def _stub_browser(monkeypatch: pytest.MonkeyPatch) -> None:
evaluate=AsyncMock(return_value=None),
)
monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, ctx)))
+ monkeypatch.setattr(mcp_browser, "validate_fetch_url", lambda url: url)
monkeypatch.setattr(mcp_browser, "get_current_session", lambda: SimpleNamespace(_working_frame=None))
monkeypatch.setattr(mcp_browser, "clear_session_ref_map", Mock())
monkeypatch.setattr(
diff --git a/tests/unit/test_mcp_tab_tools.py b/tests/unit/test_mcp_tab_tools.py
index d8b5b2555..46f2f09b2 100644
--- a/tests/unit/test_mcp_tab_tools.py
+++ b/tests/unit/test_mcp_tab_tools.py
@@ -135,7 +135,7 @@ async def test_tab_new_with_url(monkeypatch: pytest.MonkeyPatch) -> None:
browser._browser_context.new_page = AsyncMock(return_value=new_page)
browser._browser_context.pages = [existing_page, new_page]
- ctx = BrowserContext(mode="local")
+ ctx = BrowserContext(mode="cloud_session", session_id="pbs_test", can_access_localhost=False)
monkeypatch.setattr(mcp_tabs, "get_page", AsyncMock(return_value=(SimpleNamespace(page=existing_page), ctx)))
state = _make_session_state(browser)
@@ -144,7 +144,62 @@ async def test_tab_new_with_url(monkeypatch: pytest.MonkeyPatch) -> None:
result = await mcp_tabs.skyvern_tab_new(url="https://target.com")
assert result["ok"] is True
- new_page.goto.assert_awaited_once_with("https://target.com", wait_until="domcontentloaded", timeout=30000)
+ new_page.goto.assert_awaited_once_with("https://target.com/", wait_until="domcontentloaded", timeout=30000)
+
+
+ ("url", "can_access_localhost"),
+ [
+ pytest.param("file:///etc/passwd", False, id="file"),
+ pytest.param("http://169.254.169.254/", False, id="metadata"),
+ pytest.param("http://10.20.30.40/", False, id="private"),
+ pytest.param("http://127.0.0.1:8000/", False, id="loopback"),
+ pytest.param("http://127.0.0.2/", False, id="alternate-loopback"),
+ pytest.param("http://2130706433/", False, id="integer-loopback"),
+ pytest.param("http://169.254.169.254/", True, id="metadata-local-context"),
+ pytest.param("http://10.20.30.40/", True, id="private-local-context"),
+ ],
+)
+async def test_tab_new_rejects_unsafe_url_before_opening(
+ monkeypatch: pytest.MonkeyPatch, url: str, can_access_localhost: bool
+) -> None:
+ existing_page = _make_mock_page()
+ new_page = _make_mock_page()
+ browser = _make_mock_browser(existing_page)
+ browser._browser_context.new_page = AsyncMock(return_value=new_page)
+ ctx = BrowserContext(
+ mode="local" if can_access_localhost else "cloud_session",
+ session_id=None if can_access_localhost else "pbs_test",
+ can_access_localhost=can_access_localhost,
+ )
+ _patch_get_page(monkeypatch, existing_page, ctx)
+ _patch_session(monkeypatch, _make_session_state(browser))
+
+ result = await mcp_tabs.skyvern_tab_new(url=url)
+
+ assert result["ok"] is False
+ assert result["error"]["code"] == "INVALID_INPUT"
+ browser._browser_context.new_page.assert_not_awaited()
+ new_page.goto.assert_not_awaited()
+
+
[email protected]("url", ["http://localhost:3000/", "http://127.0.0.1:8000/"])
+async def test_tab_new_allows_local_url_when_context_permits(monkeypatch: pytest.MonkeyPatch, url: str) -> None:
+ existing_page = _make_mock_page()
+ new_page = _make_mock_page(url, "Local")
+ browser = _make_mock_browser(existing_page)
+ browser._browser_context.new_page = AsyncMock(return_value=new_page)
+ browser._browser_context.pages = [existing_page, new_page]
+ ctx = BrowserContext(mode="local", can_access_localhost=True)
+ _patch_get_page(monkeypatch, existing_page, ctx)
+ _patch_session(monkeypatch, _make_session_state(browser))
+
+ result = await mcp_tabs.skyvern_tab_new(url=url)
+
+ assert result["ok"] is True
+ new_page.goto.assert_awaited_once_with(url, wait_until="domcontentloaded", timeout=30000)
@pytest.mark.asyncio
@@ -166,7 +221,7 @@ async def test_tab_new_navigation_failure_restores_previous_active(monkeypatch:
state._active_page = existing_page
_patch_session(monkeypatch, state)
- result = await mcp_tabs.skyvern_tab_new(url="https://bad-url.com")
+ result = await mcp_tabs.skyvern_tab_new(url="https://example.com")
assert result["ok"] is False
# Previous active page should be restored, not reset to None