Skip to content

Automate browser based workflows with AI

fix(SKY-11992): capture blob: URL downloads in the CDP download monitor (#7192)

LawyZhengc78637ae87b1
diff --git a/skyvern/webeye/cdp_download_interceptor.py b/skyvern/webeye/cdp_download_interceptor.py
index 96320c0b1..6b5deb797 100644
--- a/skyvern/webeye/cdp_download_interceptor.py
+++ b/skyvern/webeye/cdp_download_interceptor.py
@@ -32,6 +32,8 @@ from urllib.parse import unquote, urlparse
import structlog
from playwright.async_api import Browser, BrowserContext, CDPSession, Page
+from skyvern.webeye.utils.page import SkyvernFrame
+
LOG = structlog.get_logger()
# Chunk size for IO.read streaming
@@ -455,22 +457,21 @@ class CDPDownloadInterceptor:
LOG.warning("Empty download URL, skipping")
return
- # Skip if already downloaded via CDP Fetch interception.
- # Fetch always fires before Browser.downloadWillBegin (Fetch intercepts at
- # response stage, browser download manager fires after fulfillRequest), so
- # this check is purely one-directional: only _handle_download writes the set.
+ # Skip if this exact URL was already captured. Both the Fetch path
+ # (_handle_download) and the blob path (_download_blob_url, after a successful save)
+ # record URLs here. We record only AFTER a successful save — not before the read — so
+ # a transient failure can't block a later retry of the same URL; a rare duplicate
+ # downloadWillBegin for the same blob URL is a benign re-save/overwrite.
if url in self._downloaded_urls:
LOG.debug("URL already captured via Fetch, skipping direct download", url=url)
return
if url.startswith("blob:"):
- # blob: URLs are in-memory browser references — not fetchable over HTTP.
- # They are already handled by the Fetch path which intercepts the resolved blob.
- # TODO: handle the edge case where Fetch doesn't catch a blob download.
- LOG.warning(
- "blob: URL download not yet supported, skipping", url=url, suggested_filename=suggested_filename
- )
- return
+ # blob: URLs are in-memory browser references — not fetchable over HTTP. When the
+ # page builds the file client-side (e.g. Blob + createObjectURL), the CDP Fetch
+ # path never sees a network response, so read the bytes back from a same-origin
+ # page instead of dropping the download.
+ await self._download_blob_url(url, suggested_filename)
elif url.startswith("http"):
await self._download_url_directly(url, suggested_filename)
else:
@@ -556,6 +557,57 @@ class CDPDownloadInterceptor:
method=method,
)
+ async def _download_blob_url(self, url: str, suggested_filename: str) -> None:
+ """Save a blob: URL download by reading its bytes back from a same-origin page.
+
+ blob: URLs are in-memory references owned by the document that created them, so they
+ can't be fetched over HTTP. ``SkyvernFrame.read_blob_url_bytes`` runs the shared blob
+ read-back script inside a same-origin frame. Best-effort: a page may revoke the object
+ URL before we read it.
+ """
+ if not self._output_dir or self._browser_context is None:
+ LOG.warning("Cannot read blob download: no output dir or browser context", url=url)
+ return
+
+ # probe=True: this fans out over every open page as a best-effort fallback, so the
+ # shared reader must not emit ERROR logs for pages that don't own the blob's origin.
+ data: bytes | None = None
+ for page in list(self._browser_context.pages):
+ data = await SkyvernFrame.read_blob_url_bytes(
+ page=page, blob_url=url, max_size_bytes=MAX_FILE_SIZE_BYTES, probe=True
+ )
+ if data is not None:
+ break
+
+ if data is None:
+ LOG.warning(
+ "Could not read blob download from any page",
+ url=url,
+ suggested_filename=suggested_filename,
+ )
+ return
+ # Defense-in-depth: read_blob_url_bytes already rejects oversized blobs in-page before
+ # serialization, but guard again in case a caller passes no limit.
+ if len(data) > MAX_FILE_SIZE_BYTES:
+ LOG.warning(
+ "Blob download exceeds size limit, discarding",
+ url=url,
+ size=len(data),
+ max_size=MAX_FILE_SIZE_BYTES,
+ )
+ return
+ save_path, filename = self._resolve_save_path(suggested_filename)
+ with open(save_path, "wb") as f:
+ f.write(data)
+ self._downloaded_urls.add(url)
+ LOG.info(
+ "CDP download saved (blob)",
+ filename=filename,
+ size=len(data),
+ save_path=str(save_path),
+ download_index=self._download_index,
+ )
+
async def disable(self) -> None:
"""Disable Fetch interception on all CDP sessions and clean up browser monitor."""
session_count = len(self._cdp_sessions)
diff --git a/skyvern/webeye/utils/page.py b/skyvern/webeye/utils/page.py
index 611e2f160..3264a6d1e 100644
--- a/skyvern/webeye/utils/page.py
+++ b/skyvern/webeye/utils/page.py
@@ -363,13 +363,19 @@ def _merge_images_by_position(images: list[Image.Image], positions: list[int]) -
# FileReader keeps the payload binary-safe without arrayBuffer/Uint8Array
# transcoding back across CDP.
_BLOB_FETCH_JS = """
-async (blobUrl) => {
+async (args) => {
try {
+ const { blobUrl, maxSizeBytes } = args;
const response = await fetch(blobUrl);
if (!response.ok) {
return { ok: false, status: response.status };
}
const blob = await response.blob();
+ // Reject oversized blobs before serializing them to a data URL, so a huge
+ // client-side blob can't be read fully into memory / base64-transcoded.
+ if (maxSizeBytes != null && blob.size > maxSizeBytes) {
+ return { ok: false, error: 'too_large', size: blob.size };
+ }
return await new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => {
@@ -430,6 +436,19 @@ def _frames_for_blob_origin(page: Page, blob_origin: str) -> list[Frame]:
return matches
+def _all_page_frames(page: Page) -> list[Frame]:
+ """All frames on the page, main frame first, deduped."""
+ seen: set[int] = set()
+ frames: list[Frame] = []
+ for frame in [page.main_frame, *page.frames]:
+ frame_id = id(frame)
+ if frame_id in seen:
+ continue
+ seen.add(frame_id)
+ frames.append(frame)
+ return frames
+
+
class SkyvernFrame:
@staticmethod
async def evaluate(
@@ -565,23 +584,32 @@ class SkyvernFrame:
page: Page,
blob_url: str,
workflow_run_id: str | None = None,
+ max_size_bytes: int | None = None,
+ probe: bool = False,
) -> bytes | None:
+ # probe=True is for best-effort multi-page fallback where the caller tries every open
+ # page; expected misses on non-owning pages shouldn't spam ERROR/WARN logs, so downgrade
+ # give-up/retry logging to debug. The final failure signal stays with the caller.
+ give_up_log = LOG.debug if probe else LOG.error
+ retry_log = LOG.debug if probe else LOG.warning
+
blob_origin = _blob_url_origin(blob_url)
- if blob_origin is None:
- LOG.error(
- "blob URL read aborted: unparseable origin",
- workflow_run_id=workflow_run_id,
- )
+ if blob_origin is not None:
+ frames = _frames_for_blob_origin(page, blob_origin)
+ elif blob_url.startswith("blob:"):
+ # Opaque-origin blobs (blob:null/...) from sandboxed iframes or data: documents have
+ # no matchable origin — probe every frame since we can't identify the owner by origin.
+ frames = _all_page_frames(page)
+ else:
+ give_up_log("blob URL read aborted: not a blob URL", workflow_run_id=workflow_run_id)
return None
- frames = _frames_for_blob_origin(page, blob_origin)
if not frames:
- LOG.error(
- "blob URL read found no frame at the blob origin",
- workflow_run_id=workflow_run_id,
- )
+ give_up_log("blob URL read found no candidate frame", workflow_run_id=workflow_run_id)
return None
+ # blob.size is checked in-page against this before the payload is serialized.
+ blob_arg = {"blobUrl": blob_url, "maxSizeBytes": max_size_bytes}
main_frame = page.main_frame
for frame in frames:
try:
@@ -589,41 +617,49 @@ class SkyvernFrame:
# context-level main-world prefix stays attached; sub-frames use
# frame.evaluate (main-world prefixes are page-scoped).
if frame is main_frame:
- result = await evaluate_in_main_world(page, _BLOB_FETCH_JS, blob_url)
+ result = await evaluate_in_main_world(page, _BLOB_FETCH_JS, blob_arg)
else:
- result = await frame.evaluate(_BLOB_FETCH_JS, blob_url)
+ result = await frame.evaluate(_BLOB_FETCH_JS, blob_arg)
except Exception:
- LOG.warning(
+ retry_log(
"blob URL in-frame fetch raised; trying next frame if any",
workflow_run_id=workflow_run_id,
exc_info=True,
)
continue
- if not isinstance(result, dict) or not result.get("ok"):
+ if isinstance(result, dict) and result.get("error") == "too_large":
LOG.warning(
+ "blob URL exceeds max size; not reading",
+ workflow_run_id=workflow_run_id,
+ size=result.get("size"),
+ max_size_bytes=max_size_bytes,
+ )
+ return None
+ if not isinstance(result, dict) or not result.get("ok"):
+ retry_log(
"blob URL in-frame fetch returned not-ok; trying next frame if any",
workflow_run_id=workflow_run_id,
result=result if isinstance(result, dict) else None,
)
continue
b64_payload = result.get("base64")
- if not isinstance(b64_payload, str) or not b64_payload:
- LOG.warning(
- "blob URL in-frame fetch returned empty payload; trying next frame if any",
+ if not isinstance(b64_payload, str):
+ retry_log(
+ "blob URL in-frame fetch returned non-string payload; trying next frame if any",
workflow_run_id=workflow_run_id,
)
continue
try:
return base64.b64decode(b64_payload, validate=True)
except Exception:
- LOG.warning(
+ retry_log(
"blob URL in-frame fetch payload was not valid base64; trying next frame if any",
workflow_run_id=workflow_run_id,
exc_info=True,
)
continue
- LOG.error(
+ give_up_log(
"blob URL read could not retrieve bytes from any matching frame",
workflow_run_id=workflow_run_id,
)
diff --git a/tests/unit/test_cdp_download_interceptor.py b/tests/unit/test_cdp_download_interceptor.py
index c249314c5..37892c6f9 100644
--- a/tests/unit/test_cdp_download_interceptor.py
+++ b/tests/unit/test_cdp_download_interceptor.py
@@ -1,7 +1,7 @@
"""Unit tests for CDPDownloadInterceptor pure functions and proxy auth handling."""
from pathlib import Path
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -705,3 +705,120 @@ class TestCDPDownloadInterceptorProxyAuth:
await interceptor._handle_auth_required(event, cdp_session)
second_call = cdp_session.send.call_args
assert second_call.args[1]["authChallengeResponse"]["response"] == "CancelAuth"
+
+
+class TestBlobDownloadCapture:
+ """Browser-initiated blob: URL downloads (e.g. a page that builds the file client-side and
+ triggers a blob download) must be read back via SkyvernFrame and saved, not dropped."""
+
+ _READ_BLOB = "skyvern.webeye.cdp_download_interceptor.SkyvernFrame.read_blob_url_bytes"
+
+ @staticmethod
+ def _context(num_pages: int = 1) -> MagicMock:
+ context = MagicMock()
+ context.pages = [MagicMock() for _ in range(num_pages)]
+ return context
+
+ @pytest.mark.asyncio
+ async def test_blob_download_read_and_saved(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ interceptor._browser_context = self._context()
+ pdf_bytes = b"%PDF-1.4 fake blob invoice bytes"
+
+ with patch(self._READ_BLOB, new=AsyncMock(return_value=pdf_bytes)):
+ await interceptor._handle_browser_download(
+ {"url": "blob:https://example.com/abc-123", "suggestedFilename": "invoice.pdf"}
+ )
+
+ saved = list(tmp_path.iterdir())
+ assert len(saved) == 1
+ assert saved[0].name == "invoice.pdf"
+ assert saved[0].read_bytes() == pdf_bytes
+
+ @pytest.mark.asyncio
+ async def test_blob_download_falls_through_pages_until_readable(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ interceptor._browser_context = self._context(num_pages=2)
+ pdf_bytes = b"%PDF blob"
+ read = AsyncMock(side_effect=[None, pdf_bytes])
+
+ with patch(self._READ_BLOB, new=read):
+ await interceptor._handle_browser_download(
+ {"url": "blob:https://example.com/xyz", "suggestedFilename": "bill.pdf"}
+ )
+
+ saved = list(tmp_path.iterdir())
+ assert len(saved) == 1
+ assert saved[0].read_bytes() == pdf_bytes
+ assert read.await_count == 2
+
+ @pytest.mark.asyncio
+ async def test_blob_download_threads_max_size_and_guards_oversize(self, tmp_path: Path) -> None:
+ import skyvern.webeye.cdp_download_interceptor as mod
+
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ interceptor._browser_context = self._context()
+ read = AsyncMock(return_value=b"x" * 2048) # exceeds the patched limit (defense-in-depth)
+
+ with patch.object(mod, "MAX_FILE_SIZE_BYTES", 1024), patch(self._READ_BLOB, new=read):
+ await interceptor._handle_browser_download(
+ {"url": "blob:https://example.com/big", "suggestedFilename": "huge.pdf"}
+ )
+
+ assert list(tmp_path.iterdir()) == []
+ # the in-page size limit is threaded to the shared reader, and probe mode quiets the
+ # per-page fallback so non-owning pages don't spam ERROR logs
+ assert read.await_args.kwargs["max_size_bytes"] == 1024
+ assert read.await_args.kwargs["probe"] is True
+
+ @pytest.mark.asyncio
+ async def test_blob_download_unreadable_is_noop(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ interceptor._browser_context = self._context()
+
+ with patch(self._READ_BLOB, new=AsyncMock(return_value=None)):
+ await interceptor._handle_browser_download(
+ {"url": "blob:https://example.com/gone", "suggestedFilename": "x.pdf"}
+ )
+
+ assert list(tmp_path.iterdir()) == []
+
+ @pytest.mark.asyncio
+ async def test_blob_download_saves_distinct_file_with_identical_bytes(self, tmp_path: Path) -> None:
+ # Two independent downloads can share bytes but differ by name — the second must not be
+ # dropped just because matching bytes already exist on disk.
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ interceptor._browser_context = self._context()
+ pdf_bytes = b"%PDF identical bytes, different download"
+ (tmp_path / "prior.pdf").write_bytes(pdf_bytes)
+
+ with patch(self._READ_BLOB, new=AsyncMock(return_value=pdf_bytes)):
+ await interceptor._handle_browser_download(
+ {"url": "blob:https://example.com/second", "suggestedFilename": "invoice.pdf"}
+ )
+
+ names = sorted(p.name for p in tmp_path.iterdir())
+ assert names == ["invoice.pdf", "prior.pdf"]
+
+ @pytest.mark.asyncio
+ async def test_blob_download_no_context_is_noop(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ with patch(self._READ_BLOB, new=AsyncMock()) as read:
+ await interceptor._handle_browser_download(
+ {"url": "blob:https://example.com/none", "suggestedFilename": "x.pdf"}
+ )
+ read.assert_not_awaited()
+ assert list(tmp_path.iterdir()) == []
+
+ @pytest.mark.asyncio
+ async def test_blob_download_already_captured_via_fetch_is_skipped(self, tmp_path: Path) -> None:
+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))
+ url = "blob:https://example.com/dup"
+ interceptor._downloaded_urls.add(url)
+ interceptor._browser_context = self._context()
+
+ with patch(self._READ_BLOB, new=AsyncMock()) as read:
+ await interceptor._handle_browser_download({"url": url, "suggestedFilename": "x.pdf"})
+
+ read.assert_not_awaited()
+ assert list(tmp_path.iterdir()) == []
diff --git a/tests/unit/test_read_blob_url_bytes.py b/tests/unit/test_read_blob_url_bytes.py
new file mode 100644
index 000000000..5987ba24c
--- /dev/null
+++ b/tests/unit/test_read_blob_url_bytes.py
@@ -0,0 +1,166 @@
+import base64
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from skyvern.webeye.utils.page import SkyvernFrame
+
+_MOD = "skyvern.webeye.utils.page"
+
+
+async def test_read_blob_url_bytes_rejects_oversized_blob() -> None:
+ """An oversized blob is rejected in-page (before base64 serialization) and yields None."""
+ page = MagicMock()
+ main_frame = MagicMock()
+ page.main_frame = main_frame
+ eval_mock = AsyncMock(return_value={"ok": False, "error": "too_large", "size": 500_000_000})
+
+ with (
+ patch(f"{_MOD}._frames_for_blob_origin", return_value=[main_frame]),
+ patch(f"{_MOD}.evaluate_in_main_world", new=eval_mock),
+ ):
+ result = await SkyvernFrame.read_blob_url_bytes(
+ page=page, blob_url="blob:https://example.com/big", max_size_bytes=1024
+ )
+
+ assert result is None
+ # max size is threaded into the in-page arg so the guard runs before serialization
+ _page, _js, arg = eval_mock.await_args.args
+ assert arg == {"blobUrl": "blob:https://example.com/big", "maxSizeBytes": 1024}
+
+
+async def test_read_blob_url_bytes_returns_bytes_within_limit() -> None:
+ page = MagicMock()
+ main_frame = MagicMock()
+ page.main_frame = main_frame
+ payload = b"%PDF small within limit"
+ eval_mock = AsyncMock(return_value={"ok": True, "base64": base64.b64encode(payload).decode()})
+
+ with (
+ patch(f"{_MOD}._frames_for_blob_origin", return_value=[main_frame]),
+ patch(f"{_MOD}.evaluate_in_main_world", new=eval_mock),
+ ):
+ result = await SkyvernFrame.read_blob_url_bytes(
+ page=page, blob_url="blob:https://example.com/ok", max_size_bytes=1024
+ )
+
+ assert result == payload
+ _page, _js, arg = eval_mock.await_args.args
+ assert arg["maxSizeBytes"] == 1024
+
+
+async def test_read_blob_url_bytes_returns_empty_bytes_for_zero_byte_blob() -> None:
+ page = MagicMock()
+ main_frame = MagicMock()
+ page.main_frame = main_frame
+ eval_mock = AsyncMock(return_value={"ok": True, "base64": ""})
+
+ with (
+ patch(f"{_MOD}._frames_for_blob_origin", return_value=[main_frame]),
+ patch(f"{_MOD}.evaluate_in_main_world", new=eval_mock),
+ ):
+ result = await SkyvernFrame.read_blob_url_bytes(
+ page=page, blob_url="blob:https://example.com/empty", max_size_bytes=1024
+ )
+
+ assert result == b""
+
+
+async def test_read_blob_url_bytes_no_limit_passes_none() -> None:
+ """Existing callers that pass no limit still work; maxSizeBytes is None (no in-page check)."""
+ page = MagicMock()
+ main_frame = MagicMock()
+ page.main_frame = main_frame
+ payload = b"unbounded"
+ eval_mock = AsyncMock(return_value={"ok": True, "base64": base64.b64encode(payload).decode()})
+
+ with (
+ patch(f"{_MOD}._frames_for_blob_origin", return_value=[main_frame]),
+ patch(f"{_MOD}.evaluate_in_main_world", new=eval_mock),
+ ):
+ result = await SkyvernFrame.read_blob_url_bytes(page=page, blob_url="blob:https://example.com/x")
+
+ assert result == payload
+ _page, _js, arg = eval_mock.await_args.args
+ assert arg["maxSizeBytes"] is None
+
+
+async def test_read_blob_url_bytes_opaque_origin_probes_frames_and_succeeds() -> None:
+ """Opaque-origin blob (blob:null/...) has no matchable origin; probe frames and read the
+ bytes from whichever frame owns it (here a later sub-frame)."""
+ page = MagicMock()
+ main_frame = MagicMock()
+ page.main_frame = main_frame
+ sub_frame = MagicMock()
+ payload = b"%PDF opaque-origin blob"
+ sub_frame.evaluate = AsyncMock(return_value={"ok": True, "base64": base64.b64encode(payload).decode()})
+ main_eval = AsyncMock(return_value={"ok": False, "error": "not_owner"}) # main frame doesn't own it
+
+ with (
+ patch(f"{_MOD}._all_page_frames", return_value=[main_frame, sub_frame]) as all_frames,
+ patch(f"{_MOD}._frames_for_blob_origin") as origin_frames,
+ patch(f"{_MOD}.evaluate_in_main_world", new=main_eval),
+ ):
+ result = await SkyvernFrame.read_blob_url_bytes(page=page, blob_url="blob:null/abc-123", max_size_bytes=1024)
+
+ assert result == payload
+ all_frames.assert_called_once() # opaque path probes all frames
+ origin_frames.assert_not_called() # not the origin-matched path
+
+
+async def test_read_blob_url_bytes_opaque_origin_returns_none_when_all_probes_fail() -> None:
+ page = MagicMock()
+ main_frame = MagicMock()
+ page.main_frame = main_frame
+ sub_frame = MagicMock()
+ sub_frame.evaluate = AsyncMock(return_value={"ok": False, "error": "not_owner"})
+ main_eval = AsyncMock(return_value={"ok": False, "error": "not_owner"})
+
+ with (
+ patch(f"{_MOD}._all_page_frames", return_value=[main_frame, sub_frame]),
+ patch(f"{_MOD}.evaluate_in_main_world", new=main_eval),
+ ):
+ result = await SkyvernFrame.read_blob_url_bytes(page=page, blob_url="blob:null/xyz")
+
+ assert result is None
+
+
+async def test_read_blob_url_bytes_probe_mode_does_not_emit_error_on_miss() -> None:
+ """A page that doesn't own the blob origin is an expected miss during multi-page fallback —
+ probe=True must not spam ERROR logs; the caller keeps the one final failure signal."""
+ page = MagicMock()
+ page.main_frame = MagicMock()
+ log_mock = MagicMock()
+
+ with (
+ patch(f"{_MOD}._frames_for_blob_origin", return_value=[]),
+ patch(f"{_MOD}.LOG", log_mock),
+ ):
+ result = await SkyvernFrame.read_blob_url_bytes(page=page, blob_url="blob:https://example.com/x", probe=True)
+
+ assert result is None
+ log_mock.error.assert_not_called()
+ assert log_mock.debug.called
+
+
+async def test_read_blob_url_bytes_non_probe_logs_error_on_miss() -> None:
+ page = MagicMock()
+ page.main_frame = MagicMock()
+ log_mock = MagicMock()
+
+ with (
+ patch(f"{_MOD}._frames_for_blob_origin", return_value=[]),
+ patch(f"{_MOD}.LOG", log_mock),
+ ):
+ result = await SkyvernFrame.read_blob_url_bytes(page=page, blob_url="blob:https://example.com/x", probe=False)
+
+ assert result is None
+ log_mock.error.assert_called()