Skip to content

Automate browser based workflows with AI

Serve the saved clear-browsing-data page on the secure code-block runner (SKY-16259) (#8556)

Andrew Neilson5c0a1048196d
diff --git a/skyvern/forge/sdk/copilot/tools/banned_blocks.py b/skyvern/forge/sdk/copilot/tools/banned_blocks.py
index 829a7078e..c1eab8fa8 100644
--- a/skyvern/forge/sdk/copilot/tools/banned_blocks.py
+++ b/skyvern/forge/sdk/copilot/tools/banned_blocks.py
@@ -331,7 +331,7 @@ def _code_only_browser_schema_guidance() -> list[str]:
_saved_credential_guidance(),
_secret_credential_guidance(),
"The Code runtime provides await solve_captcha(page) for a platform-managed verification challenge observed while scouting; this is an available capability, not a required step for every login.",
- "The Code runtime provides await clear_browser_data(page) when a site needs a clean session before it will sign in: it drops every cookie in the run's browser and all stored data for the page's current origin, and returns nothing. Read page.url first and navigate back to it afterwards. Browser settings pages (chrome://...) cannot be navigated to; this helper is the way to clear state. A workflow parameter named clear_browser_data shadows the helper in both executors. Before calling the helper in that case, rename the parameter to an unused name, preserve its value/default, and update its block bindings, code/template references, and caller-supplied run input keys.",
+ "The Code runtime provides await clear_browser_data(page) when a site needs a clean session before it will sign in: it drops every cookie in the run's browser and all stored data for every origin it has a page or frame open on, and returns nothing. Read page.url first and navigate back to it afterwards. Browser settings pages (chrome://...) cannot be navigated to; this helper is the way to clear state. A workflow parameter named clear_browser_data shadows the helper in both executors. Before calling the helper in that case, rename the parameter to an unused name, preserve its value/default, and update its block bindings, code/template references, and caller-supplied run input keys.",
"For file attachment: bind the file as a workflow parameter with workflow_parameter_type file_url, then call await attach_authorized_file(page, <file_parameter>, <observed_selector>). The parameter is a handle, not a path: pass it only to that helper. Attaching puts the file's contents in the page, where page scripts and page.evaluate can read them, so attach it only to the page that should receive it. It accepts only that run's materialized file, uploads at most 10 MB, and returns filename and size.",
]
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 35908cc82..990b01f23 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -62,7 +62,7 @@ from jinja2.sandbox import SandboxedEnvironment
from jsonschema import Draft202012Validator
from jsonschema.exceptions import ValidationError
from opentelemetry import trace as otel_trace
-from playwright.async_api import BrowserContext, Page
+from playwright.async_api import BrowserContext, CDPSession, Frame, Page
from playwright.async_api import TimeoutError as PlaywrightTimeoutError
from pydantic import BaseModel, Field, PrivateAttr, field_validator, model_validator
from sqlalchemy.exc import InterfaceError, OperationalError, SQLAlchemyError
@@ -302,6 +302,7 @@ from skyvern.webeye.actions.action_types import ActionType
from skyvern.webeye.actions.actions import Action, ActionStatus
from skyvern.webeye.browser_artifacts import DownloadBinding
from skyvern.webeye.browser_driver_errors import is_driver_error
+from skyvern.webeye.browser_engine import is_any_engine_error
from skyvern.webeye.browser_factory import rebind_download_dir
from skyvern.webeye.browser_object_predicates import is_page_like
from skyvern.webeye.browser_state import BrowserState, get_browser_state_diagnostic
@@ -5233,24 +5234,214 @@ def _bind_code_block_download_claim(
return click_and_claim_download
+def _page_origin(url: str) -> str:
+ """The page's origin as CDP's ``securityOrigin`` spells it: never the userinfo a URL can carry."""
+ parsed = urlsplit(url)
+ if parsed.scheme == "blob":
+ # A blob: document reaches the storage of the origin that minted it, and carries that origin
+ # inside its own URL rather than as a host of its own; an opaque one spells `null` and falls
+ # through to the empty answer below.
+ return _page_origin(parsed.path)
+ if parsed.scheme not in ("http", "https") or not parsed.hostname:
+ return ""
+ host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
+ return f"{parsed.scheme}://{host}:{parsed.port}" if parsed.port else f"{parsed.scheme}://{host}"
+
+
+def _frames_by_origin(open_page: Page) -> dict[str, list[Frame]]:
+ """Every frame this tab holds, grouped by origin, its own document and each nested one.
+
+ Keyed by origin because sessionStorage is per tab and origin, and carrying the frames because
+ `DOMStorage` is answered by the renderer: a cross-site frame runs out-of-process under the site
+ isolation production has on, and is reachable only from a session attached to that frame. All of
+ them are kept rather than the first, because a sandboxed frame spells the same origin as an
+ ordinary one while reaching no storage at all, and clearing has to find the one that does.
+ """
+ frames: dict[str, list[Frame]] = {}
+ for frame in open_page.frames:
+ origin = _page_origin(frame.url)
+ if origin:
+ frames.setdefault(origin, []).append(frame)
+ return frames
+
+
+def _context_origins(context: BrowserContext) -> list[str]:
+ """Every origin the run's context currently holds a document for, across all its tabs.
+
+ `Storage.clearDataForOrigin` takes one serialized origin and has no wildcard: an origin it cannot
+ parse clears the whole partition only because the filter fails open, which is not something to
+ aim a destructive call at. An origin whose document has already been closed is not reachable this
+ way and keeps its stored data.
+ """
+ origins: dict[str, None] = {}
+ for open_page in context.pages:
+ for origin in _frames_by_origin(open_page):
+ origins[origin] = None
+ return list(origins)
+
+
+def _is_browser_refusal(exc: BaseException) -> bool:
+ """Whether the browser refused this command, on any engine a run can select.
+
+ The clear is handed a page rather than the run's `BrowserEngineSelection`, so it cannot ask the
+ pinned engine the way `skyvern/webeye/utils/page.py` does; the registry answers for every engine
+ instead. `is_driver_error` covers the two Playwright-family packages a single image can install,
+ which the registry's stock spec names as one.
+ """
+ return is_any_engine_error(exc) or is_driver_error(exc)
+
+
+async def _dom_storage_session(context: BrowserContext, open_page: Page, frame: Frame) -> tuple[CDPSession, bool]:
+ """A CDP session that can answer `DOMStorage` for this frame, and whether it is the frame's own.
+
+ `DOMStorage` is served by the renderer holding the document, so a cross-site frame — out-of-process
+ under the site isolation a headful browser has on — answers only on a session of its own, and a
+ frame sharing its parent's renderer has no such session and answers on the page's. The flag
+ matters because anything else asked of the page's session answers for the page, not the frame.
+ """
+ try:
+ return await context.new_cdp_session(frame), True
+ except Exception as exc:
+ # Both driver packages are live in the production image and a persistent session's pages raise
+ # the one the source rewrite did not repoint, so the refusal is recognised by driver family.
+ if not _is_browser_refusal(exc):
+ raise
+ return await context.new_cdp_session(open_page), False
+
+
+_FRAME_STORAGE_REACHABLE_PROBE = (
+ "(() => { try { sessionStorage.length; return 'reachable'; } catch (error) { return 'unreachable'; } })()"
+)
+
+
+async def _frame_storage_is_unreachable(session: CDPSession) -> bool:
+ """Whether the frame behind this session can reach web storage at all.
+
+ A sandboxed or otherwise opaque frame has no storage area to address and nothing that outlives its
+ document, so a clear that cannot find one has found nothing to clear. Asked only after the clear
+ has already failed: a page can make this probe throw, but it cannot make the browser lose a frame
+ it can address, so a real addressing failure still surfaces.
+ """
+ try:
+ answer = await session.send(
+ "Runtime.evaluate", {"expression": _FRAME_STORAGE_REACHABLE_PROBE, "returnByValue": True}
+ )
+ except Exception as exc:
+ if not _is_browser_refusal(exc):
+ raise
+ return False
+ return answer.get("result", {}).get("value") == "unreachable"
+
+
+async def _cleared_session_storage(context: BrowserContext, open_page: Page, frame: Frame, origin: str) -> bool:
+ """Clear one frame's sessionStorage, reporting whether this frame turned out to hold any.
+
+ A frame that cannot reach storage has none to clear and is passed over, so another frame at the
+ same origin still gets its turn: a sandboxed frame spells the origin the same way an ordinary one
+ does, and going only by the first would leave the ordinary frame's storage behind.
+ """
+ frame_session, is_own_session = await _dom_storage_session(context, open_page, frame)
+ try:
+ await frame_session.send("DOMStorage.clear", {"storageId": {"securityOrigin": origin, "isLocalStorage": False}})
+ return True
+ except Exception as exc:
+ # Only a frame holding a session of its own can be asked about its own storage, and a frame
+ # with nothing to clear is exactly that kind: it is opaque, so it has a target.
+ if not _is_browser_refusal(exc) or not (is_own_session and await _frame_storage_is_unreachable(frame_session)):
+ raise
+ return False
+ finally:
+ await frame_session.detach()
+
+
+async def _cleared_inherited_session_storage(context: BrowserContext, open_page: Page) -> str:
+ """Clear the sessionStorage of a tab whose URL names no origin, returning the origin it inherited.
+
+ A window opened on `about:blank` inherits its opener's origin and takes a copy of its sessionStorage
+ into a tab area of its own, which `Storage.clearDataForOrigin` does not reach and the opener's own
+ `DOMStorage.clear` does not address. The browser is asked which storage key the frame uses rather
+ than the document, which can redefine `window.origin`; the frame tree cannot answer, reporting an
+ inherited origin as `://` exactly as it does for a tab that has none.
+ """
+ session = await context.new_cdp_session(open_page)
+ try:
+ frame_tree = await session.send("Page.getFrameTree")
+ try:
+ frame_id = frame_tree["frameTree"]["frame"]["id"]
+ answer = await session.send("Storage.getStorageKeyForFrame", {"frameId": frame_id})
+ except Exception as exc:
+ # A frame with no storage key is one on an opaque origin, which has no storage area to
+ # clear -- and which answers the probe as such. Any other refusal, a timeout among them,
+ # would otherwise pass for a tab with nothing to clear and leave its session behind.
+ if not _is_browser_refusal(exc) or not await _frame_storage_is_unreachable(session):
+ raise
+ return ""
+ storage_key = answer.get("storageKey")
+ if not storage_key:
+ return ""
+ await session.send("DOMStorage.clear", {"storageId": {"storageKey": storage_key, "isLocalStorage": False}})
+ return _page_origin(storage_key)
+ finally:
+ await session.detach()
+
+
async def _code_block_clear_browser_data_builtin(page: Page | RecordingPage) -> None:
- """Drop every cookie in the run's browser context and all stored data for the current page's
- origin, the way a block navigating to the browser's clear-browsing-data page meant to; the author
- is choosing to lose the session, so nothing is restored afterwards."""
+ """Drop every cookie in the run's browser context and all stored data for the origins it holds, the
+ way a block navigating to the browser's clear-browsing-data page meant to; the author is choosing
+ to lose the session, so nothing is restored afterwards.
+
+ This is the signature authored code is given, in both executors: a block names the page it is
+ clearing and nothing else. Naming origins is a worker-side concern, below.
+ """
+ await _clear_browser_data_in_context(page)
+
+
+async def _clear_browser_data_in_context(page: Page | RecordingPage, replaced_origins: Sequence[str] = ()) -> None:
+ """``replaced_origins`` are origins a worker destroyed on the way here, whose stored data is still
+ clearable by origin even though no frame is left to name it. Their sessionStorage is not: that
+ needs a live frame, and it went with the document.
+ """
real_page = page._underlying_page if isinstance(page, RecordingPage) else page
context = real_page.context
- origin = _page_origin(real_page.url)
- LOG.info("Code block clearing browser data", origin=origin)
+ # Taken before the pass below awaits anything: a frame the page navigates or removes while that
+ # runs is gone by the time it could be enumerated, and its stored data outlives it.
+ opened_origins = _context_origins(context)
+ # sessionStorage first: it is the only part addressed per frame, so it is the part that can fail,
+ # and failing here leaves the session intact for a retry rather than half-cleared.
+ # `Storage.clearDataForOrigin` has no sessionStorage storage type, so this pass is what covers it.
+ inherited_origins: list[str] = []
+ session_storage_cleared: set[str] = set()
+ for open_page in context.pages:
+ if not _page_origin(open_page.url):
+ inherited = await _cleared_inherited_session_storage(context, open_page)
+ inherited_origins.append(inherited)
+ session_storage_cleared.add(inherited)
+ for origin, frames in _frames_by_origin(open_page).items():
+ for frame in frames:
+ if await _cleared_session_storage(context, open_page, frame, origin):
+ session_storage_cleared.add(origin)
+ break
+ origins = list(
+ dict.fromkeys(
+ [*opened_origins, *_context_origins(context), *filter(None, inherited_origins), *replaced_origins]
+ )
+ )
+ # sessionStorage is reachable only through a live frame at that origin, so an origin no frame
+ # answered for keeps it. Named here because the caller is told the clear succeeded, which it did:
+ # everything addressable went. Nothing outside this list is a claim about what survived.
+ LOG.info(
+ "Code block clearing browser data",
+ origins=len(origins),
+ session_storage_unreached=[origin for origin in origins if origin not in session_storage_cleared],
+ )
await context.clear_cookies()
- if not origin:
- return
- cdp_session = await context.new_cdp_session(real_page)
- try:
- await cdp_session.send("Storage.clearDataForOrigin", {"origin": origin, "storageTypes": "all"})
- # Storage.clearDataForOrigin leaves the open tab's sessionStorage in place.
- await cdp_session.send("DOMStorage.clear", {"storageId": {"securityOrigin": origin, "isLocalStorage": False}})
- finally:
- await cdp_session.detach()
+ if origins:
+ cdp_session = await context.new_cdp_session(real_page)
+ try:
+ for origin in origins:
+ await cdp_session.send("Storage.clearDataForOrigin", {"origin": origin, "storageTypes": "all"})
+ finally:
+ await cdp_session.detach()
CLEAR_BROWSER_DATA_HELPER_CONTRACT: dict[str, Any] = {
@@ -5265,7 +5456,8 @@ CLEAR_BROWSER_DATA_HELPER_CONTRACT: dict[str, Any] = {
"returns": {"type": "null"},
"effect": (
"Every cookie in the run's browser context is dropped, and all stored data (local and session "
- "storage, IndexedDB, caches) for the page's current origin. Nothing is restored afterwards."
+ "storage, IndexedDB, caches) for every origin the context has a page or frame open on. Nothing is "
+ "restored afterwards."
),
"usage": (
"For a site that requires a clean session before sign-in: read page.url, await the helper, then "
@@ -5274,15 +5466,6 @@ CLEAR_BROWSER_DATA_HELPER_CONTRACT: dict[str, Any] = {
}
-def _page_origin(url: str) -> str:
- """The page's origin as CDP's ``securityOrigin`` spells it: never the userinfo a URL can carry."""
- parsed = urlsplit(url)
- if parsed.scheme not in ("http", "https") or not parsed.hostname:
- return ""
- host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
- return f"{parsed.scheme}://{host}:{parsed.port}" if parsed.port else f"{parsed.scheme}://{host}"
-
-
def _bind_code_block_search_web(
page: Page | RecordingPage | None,
) -> Callable[[str, int], Awaitable[web_search.WebSearchObservation]]:
diff --git a/skyvern/webeye/browser_engine.py b/skyvern/webeye/browser_engine.py
index 66d1e9e27..1ddaf70fb 100644
--- a/skyvern/webeye/browser_engine.py
+++ b/skyvern/webeye/browser_engine.py
@@ -470,6 +470,25 @@ REGISTRY.register(RUSTWRIGHT_SPEC)
REGISTRY.register(SKYCDP_SPEC)
+def is_any_engine_error(exc: BaseException) -> bool:
+ """Whether ``exc`` is the driver-error family of any engine this image could select.
+
+ For a caller that holds a page but not the run's ``BrowserEngineSelection`` and so cannot ask
+ ``is_engine_error``; going through the registry keeps the engine packages named here rather than
+ at the call site. Wider than the pinned check by construction, so it answers yes to a refusal the
+ selected engine would also own, and an engine whose package is absent contributes nothing.
+ """
+ for name in REGISTRY.names():
+ spec = REGISTRY.get(name)
+ try:
+ error_type, _ = spec._load_error_types()
+ except ImportError:
+ continue
+ if isinstance(exc, error_type):
+ return True
+ return False
+
+
@dataclass(frozen=True)
class BrowserEngineContext:
"""Per-run inputs a resolver may use to pick and validate an engine. Available at the browser
diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py
index 4bec5abce..b9db14f01 100644
--- a/tests/unit/conftest.py
+++ b/tests/unit/conftest.py
@@ -23,6 +23,7 @@ from opentelemetry import trace as otel_trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
+from playwright.async_api import Error as PlaywrightError
from sqlalchemy import create_engine
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
@@ -559,12 +560,43 @@ class FakeSearchBrowserContext:
class FakeCdpSession:
- def __init__(self) -> None:
+ def __init__(
+ self,
+ storage_reachable: bool = True,
+ origins_refusing_clear: tuple[str, ...] = (),
+ origins_failing_unexpectedly: tuple[str, ...] = (),
+ refuses_clear: bool = False,
+ refusal_error: type[BaseException] = PlaywrightError,
+ storage_key: str | None = None,
+ ) -> None:
self.sent: list[tuple[str, dict | None]] = []
self.detached = False
+ self.storage_key = storage_key
+ self.storage_reachable = storage_reachable
+ self.origins_refusing_clear = origins_refusing_clear
+ self.origins_failing_unexpectedly = origins_failing_unexpectedly
+ self.refuses_clear = refuses_clear
+ self.refusal_error = refusal_error
async def send(self, method: str, params: dict | None = None) -> dict:
self.sent.append((method, params))
+ if method == "Runtime.evaluate":
+ # Answers for whatever document this session is attached to, as the real one does.
+ return {"result": {"value": "reachable" if self.storage_reachable else "unreachable"}}
+ if method == "Page.getFrameTree":
+ return {"frameTree": {"frame": {"id": "frame-of-this-session"}}}
+ if method == "Storage.getStorageKeyForFrame":
+ if self.storage_key is None:
+ raise self.refusal_error(
+ "Protocol error (Storage.getStorageKeyForFrame): Frame corresponds to an opaque origin"
+ )
+ return {"storageKey": self.storage_key}
+ if method == "DOMStorage.clear":
+ origin = (params or {}).get("storageId", {}).get("securityOrigin")
+ if origin in self.origins_failing_unexpectedly:
+ raise ValueError("not a browser-driver error")
+ if self.refuses_clear or origin in self.origins_refusing_clear:
+ raise self.refusal_error("Protocol error (DOMStorage.clear): Frame not found for the given storage id")
return {}
async def detach(self) -> None:
@@ -572,17 +604,50 @@ class FakeCdpSession:
class FakeClearingBrowserContext:
- """Browser context a `clear_browser_data` call clears: records the cookie wipe and every CDP session it hands out."""
+ """Browser context a `clear_browser_data` call clears: records the cookie wipe and every CDP session it hands out.
- def __init__(self) -> None:
+ `pages` is what the clear enumerates origins from, so a test that expects storage to be cleared has
+ to put its page in it, the way a live context holds its open tabs.
+ """
+
+ def __init__(self, clear_cookies_error: Exception | None = None) -> None:
self.clear_cookies_calls = 0
+ self.clear_cookies_error = clear_cookies_error
self.cdp_sessions: list[tuple[object, FakeCdpSession]] = []
+ self.pages: list[object] = []
+ # Documents whose session reports no reachable storage, the way a sandboxed frame's does.
+ self.frames_without_storage: list[object] = []
+ # Origins whose DOMStorage.clear fails, whichever session carries it.
+ self.origins_refusing_clear: list[str] = []
+ # Frames sharing their parent's renderer: Playwright refuses them a session of their own.
+ self.frames_without_own_session: list[object] = []
+ # Origins whose clear fails with something that is not a browser-driver error at all.
+ self.origins_failing_unexpectedly: list[str] = []
+ # Frames whose own clear fails, however the origin is spelled -- a sandboxed frame does this
+ # while an ordinary frame at the same origin clears fine.
+ self.frames_refusing_clear: list[object] = []
+ # Raise this engine's refusal instead of the Playwright family's, as a raw-CDP run would.
+ self.refusal_error: type[BaseException] = PlaywrightError
+ # Storage key the browser reports for a tab whose URL names no origin, as it does for a
+ # window opened on about:blank. A tab absent from this list has an opaque origin and none.
+ self.inherited_storage_keys: list[tuple[object, str]] = []
async def clear_cookies(self) -> None:
self.clear_cookies_calls += 1
+ if self.clear_cookies_error is not None:
+ raise self.clear_cookies_error
async def new_cdp_session(self, page: object) -> FakeCdpSession:
- session = FakeCdpSession()
+ if page in self.frames_without_own_session:
+ raise PlaywrightError("This frame does not have a separate CDP session")
+ session = FakeCdpSession(
+ storage_reachable=page not in self.frames_without_storage,
+ origins_refusing_clear=tuple(self.origins_refusing_clear),
+ origins_failing_unexpectedly=tuple(self.origins_failing_unexpectedly),
+ refuses_clear=page in self.frames_refusing_clear,
+ refusal_error=self.refusal_error,
+ storage_key=next((key for held, key in self.inherited_storage_keys if held is page), None),
+ )
self.cdp_sessions.append((page, session))
return session
diff --git a/tests/unit/test_code_block_sandbox.py b/tests/unit/test_code_block_sandbox.py
index d946a92d1..449cb8b56 100644
--- a/tests/unit/test_code_block_sandbox.py
+++ b/tests/unit/test_code_block_sandbox.py
@@ -7,15 +7,17 @@ Verifies that the CodeBlock safety layer:
"""
import asyncio
+import inspect
import json
import re
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from datetime import UTC, datetime, timezone
from types import SimpleNamespace
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import ANY, AsyncMock, MagicMock
import pytest
+from playwright.async_api import Error as PlaywrightError
from playwright.async_api import Page
from playwright.async_api import TimeoutError as PlaywrightTimeoutError
@@ -53,6 +55,7 @@ from skyvern.forge.sdk.workflow.models.parameter import (
from skyvern.schemas.workflows import BlockStatus
from skyvern.webeye import dialog_handler
from skyvern.webeye.browser_artifacts import BrowserArtifacts
+from skyvern.webeye.skycdp.errors import CdpError
from tests.unit.conftest import FakeClearingBrowserContext, FakeSearchBrowserContext
from tests.unit.fake_workflow_run_context import FakeWorkflowRunContext
@@ -3024,6 +3027,14 @@ class TestClearBrowserDataHelperBinding:
def test_clear_browser_data_is_reserved_in_safe_vars(self) -> None:
assert "clear_browser_data" in CodeBlock.build_safe_vars()
+ def test_the_helper_authored_code_gets_takes_only_the_page(self) -> None:
+ # The secure runner's wrapper accepts the page and nothing else, so a block that named
+ # origins here would run in one executor and be rejected by the other. Worker-side callers
+ # that do have origins to name use the private function instead.
+ bound = CodeBlock.build_safe_vars()["clear_browser_data"]
+
+ assert list(inspect.signature(bound).parameters) == ["page"]
+
@pytest.mark.asyncio
async def test_a_persisted_parameter_named_clear_browser_data_keeps_its_value(self) -> None:
# The name was a valid parameter name before it became a helper; a block that declared it
@@ -3036,21 +3047,275 @@ class TestClearBrowserDataHelperBinding:
assert await user_function() == {"value": "keep"}
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("opener_is_open", "inherits", "expected_session_clears"),
+ [
+ (
+ True,
+ True,
+ [
+ {"securityOrigin": "https://portal.example", "isLocalStorage": False},
+ {"storageKey": "https://portal.example/", "isLocalStorage": False},
+ ],
+ ),
+ (True, False, [{"securityOrigin": "https://portal.example", "isLocalStorage": False}]),
+ (False, True, [{"storageKey": "https://portal.example/", "isLocalStorage": False}]),
+ ],
+ ids=["window_opened_on_about_blank", "tab_on_an_opaque_origin", "only_the_opened_window_is_left"],
+ )
+ async def test_a_tab_whose_url_names_no_origin_is_cleared_by_the_origin_it_inherited(
+ self, opener_is_open: bool, inherits: bool, expected_session_clears: list[dict]
+ ) -> None:
+ # A window opened on about:blank keeps a copy of its opener's sessionStorage in a tab area of
+ # its own, which clearing by origin does not reach and the opener's own clear does not
+ # address. A tab that inherited nothing has no storage area at all and must not fail the run,
+ # and one left without its opener is the only document still naming that origin.
+ context = FakeClearingBrowserContext()
+ popup = SimpleNamespace(url="about:blank", context=context, frames=[SimpleNamespace(url="about:blank")])
+ opener = SimpleNamespace(
+ url="https://portal.example/login",
+ context=context,
+ frames=[SimpleNamespace(url="https://portal.example/login")],
+ )
+ page = opener if opener_is_open else SimpleNamespace(url="about:blank", context=context, frames=[])
+ context.pages = [page, popup]
+ # A tab that inherited nothing is on an opaque origin, which reaches no storage either.
+ context.frames_without_storage = [] if opener_is_open else [page]
+ if inherits:
+ context.inherited_storage_keys = [(popup, "https://portal.example/")]
+ else:
+ context.frames_without_storage.append(popup)
+
+ user_function = self._block().generate_async_user_function(
+ 'await clear_browser_data(page)\nreturn {"cleared": True}\n',
+ page, # type: ignore[arg-type]
+ )
+
+ assert await user_function() == {"cleared": True}
+ sent = [call for _, session in context.cdp_sessions for call in session.sent]
+ assert [params["storageId"] for method, params in sent if method == "DOMStorage.clear"] == (
+ expected_session_clears
+ )
+ # The origin an inherited-origin tab names still has to reach the origin-keyed pass, which is
+ # all that clears its persistent storage once no other document spells it.
+ assert [params["origin"] for method, params in sent if method == "Storage.clearDataForOrigin"] == [
+ "https://portal.example"
+ ]
+
+ @pytest.mark.asyncio
+ async def test_a_tab_that_reaches_storage_but_cannot_be_keyed_fails_the_clear(self) -> None:
+ # Only a tab with no storage area at all has nothing to clear. A lookup that fails on a tab
+ # which CAN reach storage -- a timeout, say -- must not pass for one, or the helper reports a
+ # clear while that tab keeps its session.
+ context = FakeClearingBrowserContext()
+ popup = SimpleNamespace(url="about:blank", context=context, frames=[SimpleNamespace(url="about:blank")])
+ page = SimpleNamespace(
+ url="https://portal.example/login",
+ context=context,
+ frames=[SimpleNamespace(url="https://portal.example/login")],
+ )
+ context.pages = [page, popup]
+
+ user_function = self._block().generate_async_user_function(
+ 'await clear_browser_data(page)\nreturn {"cleared": True}\n',
+ page, # type: ignore[arg-type]
+ )
+
+ with pytest.raises(PlaywrightError):
+ await user_function()
+ assert context.clear_cookies_calls == 0
+
+ @pytest.mark.asyncio
+ async def test_an_origin_that_closes_during_the_clear_still_has_its_stored_data_cleared(self) -> None:
+ # The session-storage pass awaits, and a page can drop a frame while it does. The origin was
+ # open when the clear began, so its stored data is still the run's to clear.
+ context = FakeClearingBrowserContext()
+ embedded = SimpleNamespace(url="https://embedded.example/widget")
+ page = SimpleNamespace(
+ url="https://portal.example/login",
+ context=context,
+ frames=[SimpleNamespace(url="https://portal.example/login"), embedded],
+ )
+ context.pages = [page]
+ original_new_cdp_session = context.new_cdp_session
+
+ async def dropping_frame_session(target: object) -> object:
+ session = await original_new_cdp_session(target)
+ page.frames = [page.frames[0]]
+ return session
+
+ context.new_cdp_session = dropping_frame_session # type: ignore[assignment]
+
+ user_function = self._block().generate_async_user_function(
+ 'await clear_browser_data(page)\nreturn {"cleared": True}\n',
+ page, # type: ignore[arg-type]
+ )
+
+ assert await user_function() == {"cleared": True}
+ sent = [call for _, session in context.cdp_sessions for call in session.sent]
+ assert [params["origin"] for method, params in sent if method == "Storage.clearDataForOrigin"] == [
+ "https://portal.example",
+ "https://embedded.example",
+ ]
+
+ @pytest.mark.asyncio
+ async def test_a_frame_without_a_session_of_its_own_is_cleared_through_the_page(self) -> None:
+ # A frame sharing its parent's renderer is refused a session of its own, and is the ordinary
+ # case: same-site iframes, and any cross-origin one when site isolation is off. Its clear has
+ # to fall back to the page's session, which can reach it, or nothing clears it at all.
+ context = FakeClearingBrowserContext()
+ embedded = SimpleNamespace(url="https://embedded.example/widget")
+ page = SimpleNamespace(
+ url="https://portal.example/login",
+ context=context,
+ frames=[SimpleNamespace(url="https://portal.example/login"), embedded],
+ )
+ context.pages = [page]
+ context.frames_without_own_session = [embedded]
+
+ user_function = self._block().generate_async_user_function(
+ 'await clear_browser_data(page)\nreturn {"cleared": True}\n',
+ page, # type: ignore[arg-type]
+ )
+
+ assert await user_function() == {"cleared": True}
+ cleared = [call for _, session in context.cdp_sessions for call in session.sent]
+ assert (
+ "DOMStorage.clear",
+ {"storageId": {"securityOrigin": "https://embedded.example", "isLocalStorage": False}},
+ ) in cleared
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("has_own_session", "reaches_storage", "skipped"),
+ [
+ (True, False, True),
+ (True, True, False),
+ (False, False, False),
+ ],
+ ids=["sandboxed_frame", "real_defect", "same_process_frame_cannot_be_classified"],
+ )
+ @pytest.mark.parametrize("refusal_error", [PlaywrightError, CdpError], ids=["playwright", "raw_cdp"])
+ async def test_a_frame_whose_clear_fails_is_skipped_only_when_it_reports_no_storage_of_its_own(
+ self, has_own_session: bool, reaches_storage: bool, skipped: bool, refusal_error: type[BaseException]
+ ) -> None:
+ # A sandboxed iframe has no storage area to address, so a clear that cannot find one found
+ # nothing to clear and the block carries on. A frame that CAN reach storage is an addressing
+ # defect. And a frame sharing its parent's renderer cannot be asked at all -- the probe would
+ # answer for the page -- so its failure surfaces rather than being explained away.
+ context = FakeClearingBrowserContext()
+ embedded = SimpleNamespace(url="https://embedded.example/widget")
+ page = SimpleNamespace(
+ url="https://portal.example/login",
+ context=context,
+ frames=[SimpleNamespace(url="https://portal.example/login"), embedded],
+ )
+ context.pages = [page]
+ context.origins_refusing_clear = ["https://embedded.example"]
+ # Both engines a run can select refuse the same way; only the error family differs.
+ context.refusal_error = refusal_error
+ if not has_own_session:
+ context.frames_without_own_session = [embedded]
+ # Even with the page itself reporting no storage, the frame's failure still surfaces.
+ context.frames_without_storage = [page]
+ elif not reaches_storage:
+ context.frames_without_storage = [embedded]
+
+ user_function = self._block().generate_async_user_function(
+ 'await clear_browser_data(page)\nreturn {"cleared": True}\n',
+ page, # type: ignore[arg-type]
+ )
+
+ if not skipped:
+ with pytest.raises(refusal_error):
+ await user_function()
+ # The cookie drop comes after this pass, so the run is still recoverable.
+ assert context.clear_cookies_calls == 0
+ return
+ assert await user_function() == {"cleared": True}
+ assert context.clear_cookies_calls == 1
+
+ @pytest.mark.asyncio
+ async def test_an_origin_is_cleared_through_a_frame_that_can_reach_its_storage(self) -> None:
+ # A sandboxed frame spells its origin exactly as an ordinary frame does, so an origin can be
+ # represented by one frame that reaches no storage and another that holds it. Passing over the
+ # first has to leave the second its turn, or that storage survives a clear reporting success.
+ context = FakeClearingBrowserContext()
+ sandboxed = SimpleNamespace(url="https://shared.example/ad")
+ ordinary = SimpleNamespace(url="https://shared.example/widget")
+ page = SimpleNamespace(
+ url="https://portal.example/login",
+ context=context,
+ frames=[SimpleNamespace(url="https://portal.example/login"), sandboxed, ordinary],
+ )
+ context.pages = [page]
+ context.frames_refusing_clear = [sandboxed]
+ context.frames_without_storage = [sandboxed]
+
+ user_function = self._block().generate_async_user_function(
+ 'await clear_browser_data(page)\nreturn {"cleared": True}\n',
+ page, # type: ignore[arg-type]
+ )
+
+ assert await user_function() == {"cleared": True}
+ cleared_through = [
+ attached_to
+ for attached_to, session in context.cdp_sessions
+ for method, _ in session.sent
+ if method == "DOMStorage.clear"
+ ]
+ assert ordinary in cleared_through
+
+ @pytest.mark.asyncio
+ async def test_a_clear_failing_with_something_other_than_a_driver_error_is_not_excused(self) -> None:
+ # Only a browser driver's own refusal is a candidate for "there was nothing to clear"; anything
+ # else is a fault, and excusing it would report a clear that never happened.
+ context = FakeClearingBrowserContext()
+ embedded = SimpleNamespace(url="https://embedded.example/widget")
+ page = SimpleNamespace(
+ url="https://portal.example/login",
+ context=context,
+ frames=[SimpleNamespace(url="https://portal.example/login"), embedded],
+ )
+ context.pages = [page]
+ context.origins_failing_unexpectedly = ["https://embedded.example"]
+ context.frames_without_storage = [embedded]
+
+ user_function = self._block().generate_async_user_function(
+ 'await clear_browser_data(page)\nreturn {"cleared": True}\n',
+ page, # type: ignore[arg-type]
+ )
+
+ with pytest.raises(ValueError):
+ await user_function()
+ assert context.clear_cookies_calls == 0
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
("page_url", "expected_origin"),
[
("https://portal.example/login?next=%2Fhome", "https://portal.example"),
("https://svc:[email protected]:8443/login", "https://portal.example:8443"),
- ("about:blank", None),
+ # A blob document reaches the storage of the origin that minted it, and carries that
+ # origin inside its own URL rather than as a host of its own.
+ ("blob:https://portal.example/9f1c2f5e-7a44-4d3e", "https://portal.example"),
+ ("about:blank", ""),
+ # An opaque blob has no origin to reach, so there is nothing of its own to clear.
+ ("blob:null/9f1c2f5e-7a44-4d3e", ""),
],
- ids=["web_origin", "userinfo_stripped", "no_origin"],
+ ids=["web_origin", "userinfo_in_url", "blob_of_a_web_origin", "no_origin", "opaque_blob"],
)
- async def test_authored_code_clears_cookies_and_the_current_origin_storage(
- self, page_url: str, expected_origin: str | None
+ async def test_authored_code_clears_cookies_and_every_origin_in_the_context(
+ self, page_url: str, expected_origin: str
) -> None:
+ # Cookies always go; stored data goes for the origins the context holds a document for, and a
+ # page whose URL names none is asked which origin it inherited instead.
context = FakeClearingBrowserContext()
- page = SimpleNamespace(url=page_url, context=context)
+ page = SimpleNamespace(url=page_url, context=context, frames=[SimpleNamespace(url=page_url)])
+ context.pages = [page]
+ if not expected_origin:
+ context.frames_without_storage = [page]
user_function = self._block().generate_async_user_function(
'await clear_browser_data(page)\nreturn {"cleared": True}\n',
@@ -3060,16 +3325,29 @@ class TestClearBrowserDataHelperBinding:
assert result == {"cleared": True}
assert context.clear_cookies_calls == 1
- if expected_origin is None:
- assert context.cdp_sessions == []
+ if not expected_origin:
+ # This tab inherited no origin either, so the lookup is all that happens and nothing is
+ # cleared for it.
+ assert [(attached_to, session.sent) for attached_to, session in context.cdp_sessions] == [
+ (
+ page,
+ [
+ ("Page.getFrameTree", None),
+ ("Storage.getStorageKeyForFrame", {"frameId": "frame-of-this-session"}),
+ ("Runtime.evaluate", ANY),
+ ],
+ ),
+ ]
+ assert all(session.detached for _, session in context.cdp_sessions)
return
- [(session_page, session)] = context.cdp_sessions
- assert session_page is page
- assert session.sent == [
- ("Storage.clearDataForOrigin", {"origin": expected_origin, "storageTypes": "all"}),
- ("DOMStorage.clear", {"storageId": {"securityOrigin": expected_origin, "isLocalStorage": False}}),
+ assert [(attached_to, session.sent) for attached_to, session in context.cdp_sessions] == [
+ (
+ page.frames[0],
+ [("DOMStorage.clear", {"storageId": {"securityOrigin": expected_origin, "isLocalStorage": False}})],
+ ),
+ (page, [("Storage.clearDataForOrigin", {"origin": expected_origin, "storageTypes": "all"})]),
]
- assert session.detached
+ assert all(session.detached for _, session in context.cdp_sessions)
class TestInertSlotRenderIsTheSpliceReference:
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index a01ee57d5..5c30722ed 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -893,32 +893,18 @@ workflow_definition:
assert "button:nth-of-type" not in prompt
assert "secret-token" not in prompt
- @pytest.mark.parametrize(
- ("failure_reason", "replacement"),
- [
- (
- "CodeBlock failed because it requested an unsupported browser operation at line 2: blocked "
- "navigation to non-web scheme: 'chrome://settings/clearBrowserData'; use "
- "`await clear_browser_data(page)` to clear the run's cookies and site data.",
- "await clear_browser_data(page)",
- ),
- (
- "CodeBlock failed because it requested an unsupported browser operation at line 10: page.on is not "
- "supported by the secure CodeBlock runner; a CodeBlock cannot register a browser event callback "
- "that outlives it. Take the triggering action, then wait for its effect with a bounded call: "
- "`await click_and_claim_download(page, selector)` for a download, "
- "`await page.wait_for_url(url, timeout=...)` for navigation, or "
- "`await page.wait_for_selector(selector, timeout=...)` for whatever the event renders on the "
- "page. There is no brokered way to wait on a network response; wait on what the response "
- "renders instead.",
- "await page.wait_for_selector(selector, timeout=...)",
- ),
- ],
- ids=["clear_browsing_data_navigation", "listener_denial"],
- )
- def test_runtime_repair_prompt_carries_the_denials_named_replacement(
- self, failure_reason: str, replacement: str
- ) -> None:
+ def test_runtime_repair_prompt_carries_the_denials_named_replacement(self) -> None:
+ failure_reason = (
+ "CodeBlock failed because it requested an unsupported browser operation at line 10: page.on is not "
+ "supported by the secure CodeBlock runner; a CodeBlock cannot register a browser event callback "
+ "that outlives it. Take the triggering action, then wait for its effect with a bounded call: "
+ "`await click_and_claim_download(page, selector)` for a download, "
+ "`await page.wait_for_url(url, timeout=...)` for navigation, or "
+ "`await page.wait_for_selector(selector, timeout=...)` for whatever the event renders on the "
+ "page. There is no brokered way to wait on a network response; wait on what the response "
+ "renders instead."
+ )
+ replacement = "await page.wait_for_selector(selector, timeout=...)"
# A runner denial names the sanctioned replacement after the denied call, so a bound that
# keeps only the refusal hands the repair turn a dead end it will re-emit.
ctx = _ctx(