Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Authenticate the download urllib fallback and reject HTML login pages saved as binary files (#7411)
LawyZhenga10656afd8c2
diff --git a/skyvern/webeye/cdp_download_interceptor.py b/skyvern/webeye/cdp_download_interceptor.pyindex e32f8f274..66fdd51e8 100644--- a/skyvern/webeye/cdp_download_interceptor.py+++ b/skyvern/webeye/cdp_download_interceptor.py@@ -174,6 +174,60 @@ def _download_extension_for_content_type(content_type: str) -> str:return DOWNLOAD_EXTENSION_BY_MIME_TYPE.get(_normalized_content_type(content_type), "")+_HTML_FILENAME_EXTENSIONS = frozenset({".html", ".htm", ".xhtml"})+_HTML_START_TAG_RE = re.compile(rb"^<(?:html|head|body)(?:[\t\n\f\r ]|>)")+++def _body_starts_with_html(data: bytes) -> bool:+ head = data[:4096].removeprefix(b"\xef\xbb\xbf").lstrip().lower()+ while True:+ if head.startswith(b"<!--"):+ marker_end = head.find(b"-->")+ if marker_end < 0:+ return False+ head = head[marker_end + 3 :].lstrip()+ continue+ if head.startswith(b"<?"):+ marker_end = head.find(b"?>")+ if marker_end < 0:+ return False+ head = head[marker_end + 2 :].lstrip()+ continue+ break+ head = head[:64]+ return head.startswith(b"<!doctype html") or bool(_HTML_START_TAG_RE.match(head))+++def _has_control_chars(text: str) -> bool:+ return any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in text)+++def _payload_is_html_login_masquerade(data: bytes, content_type: str, filename: str) -> bool:+ """True when a download's bytes are an HTML document but the download does not claim to be HTML.++ A session-gated download endpoint fetched without the browser's auth cookies answers with its+ HTML login/session-gate page (HTTP 200) instead of the file. Saving that under the requested+ binary name (e.g. ``*.zip``) yields a "successful" but corrupt download, so callers reject it.+ A genuine binary payload or an honest ``.html`` download is left untouched.+ """+ # The body is the ground truth: sniff it rather than trusting Content-Type, so a real binary+ # a server mislabels as text/html is not wrongly discarded.+ if not _body_starts_with_html(data):+ return False+ suffix = Path(filename).suffix.lower()+ if suffix in _HTML_FILENAME_EXTENSIONS:+ return False+ if suffix:+ return True+ if filename:+ return True+ # Nameless download: an HTML body only masquerades if the Content-Type still claims a+ # non-HTML (binary) type. A nameless HTML-or-typeless response makes no binary claim, so+ # saving the HTML is honest, not corrupt.+ normalized_ct = _normalized_content_type(content_type)+ return bool(normalized_ct) and "html" not in normalized_ct++def normalize_download_filename(filename: str, content_type: str = "") -> str:"""Sanitize a server-provided filename and add a trusted extension when missing."""filename = unquote(filename).strip()@@ -496,6 +550,28 @@ class CDPDownloadInterceptor:except Exception:LOG.warning("Error handling browser download event", exc_info=True)+ async def _cookie_header_for_url(self, url: str) -> str:+ """Build a Cookie header from the browser context's cookies applicable to ``url``.++ The urllib fallback in ``_download_url_directly`` does not share the BrowserContext, so+ without this it fetches unauthenticated and a session-gated endpoint answers with its+ login page. Best-effort: returns "" if there is no context or cookies can't be read.+ """+ if self._browser_context is None:+ return ""+ try:+ cookies = await self._browser_context.cookies(url)+ except Exception as e:+ LOG.debug("Could not read browser cookies for download fallback", url=url, error=str(e))+ return ""+ parts: list[str] = []+ for cookie in cookies:+ name, value = cookie.get("name") or "", cookie.get("value") or ""+ # Skip control chars (CR/LF/NUL/DEL) so a stored value can't inject into the header line.+ if name and not _has_control_chars(name) and not _has_control_chars(value):+ parts.append(f"{name}={value}")+ return "; ".join(parts)+async def _download_url_directly(self, url: str, suggested_filename: str) -> None:"""Download a URL directly via HTTP and save to the output directory.@@ -529,10 +605,22 @@ class CDPDownloadInterceptor:except Exception as e:LOG.debug("Playwright APIRequestContext download failed, trying urllib", url=url, error=str(e))- # Fallback: direct HTTP via urllib (works for pre-signed URLs)+ # Fallback: direct HTTP via urllib (works for pre-signed URLs). This does not share the+ # BrowserContext, so it must carry the session cookies itself — otherwise a session-gated+ # endpoint answers an unauthenticated request with its login page (saved as a corrupt file).if data is None:try:req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})+ cookie_header = await self._cookie_header_for_url(url)+ if cookie_header:+ # Unredirected header: urllib's HTTPRedirectHandler copies req.headers but not+ # unredirected_hdrs across redirects, so the cookie reaches only the original host+ # and is never replayed to another domain (cross-host session-cookie leak).+ # Trade-off: a same-host redirect also drops the cookie; if that final hop is+ # session-gated it returns a login page, which the HTML-masquerade guard below+ # rejects instead of saving a corrupt file. Per-hop cookie replay is intentionally+ # not implemented — cross-host safety outweighs that narrow convenience.+ req.add_unredirected_header("Cookie", cookie_header)ssl_ctx = ssl.create_default_context()def _fetch() -> tuple[bytes, str]:@@ -558,6 +646,19 @@ class CDPDownloadInterceptor:)return+ normalized_filename = normalize_download_filename(suggested_filename, content_type)+ if _payload_is_html_login_masquerade(data, content_type, normalized_filename):+ LOG.error(+ "Direct download returned an HTML page for a non-HTML file; not saving "+ "(likely an unauthenticated fetch landing on a login/session-gate page)",+ url=url,+ suggested_filename=normalized_filename,+ content_type=content_type,+ size=len(data),+ method=method,+ )+ return+save_path, filename = self._resolve_save_path(suggested_filename, content_type)with open(save_path, "wb") as f:diff --git a/tests/unit/test_cdp_download_interceptor.py b/tests/unit/test_cdp_download_interceptor.pyindex 7fbdf7e89..09306e6f2 100644--- a/tests/unit/test_cdp_download_interceptor.py+++ b/tests/unit/test_cdp_download_interceptor.py@@ -911,3 +911,275 @@ class TestBlobDownloadCapture:read.assert_not_awaited()assert list(tmp_path.iterdir()) == []+++class TestDirectHttpDownloadAuthAndHtmlGuard:+ """_download_url_directly falls back from the cookie-sharing Playwright APIRequestContext to a+ raw urllib fetch. That fallback must (1) still carry the browser session's cookies, and (2) not+ silently save an HTML login/session-gate page under a binary filename.++ Regression: a session-gated download endpoint fetched without cookies returns its HTML login+ page (HTTP 200); the old fallback issued a cookieless request and saved that HTML as e.g. a+ .zip while reporting the download as successful.+ """++ _URLOPEN = "urllib.request.urlopen"++ @staticmethod+ def _fake_urlopen(body: bytes, content_type: str) -> MagicMock:+ class _Resp:+ headers = {"content-type": content_type}++ def read(self) -> bytes:+ return body++ def __enter__(self) -> "_Resp":+ return self++ def __exit__(self, *exc: object) -> bool:+ return False++ return MagicMock(return_value=_Resp())++ @staticmethod+ def _context_forcing_urllib(cookies: list[dict]) -> MagicMock:+ """Browser context whose APIRequestContext returns proxy-407 (non-OK), forcing the urllib+ fallback, and whose cookies() returns the given session cookies."""+ ctx = MagicMock()+ non_ok = MagicMock()+ non_ok.ok = False+ non_ok.status = 407+ ctx.request.get = AsyncMock(return_value=non_ok)+ ctx.cookies = AsyncMock(return_value=cookies)+ return ctx++ _LOGIN_HTML = (+ b'\n<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\n'+ b"<html><head><title>Login</title></head>"+ b"<body><form method='post' action='./Login.aspx'></form></body></html>"+ )++ @pytest.mark.asyncio+ async def test_urllib_fallback_forwards_browser_cookies(self, tmp_path: Path) -> None:+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context_forcing_urllib(+ [{"name": "ASP.NET_SessionId", "value": "sess123"}, {"name": "auth", "value": "tok"}]+ )+ zip_bytes = b"PK\x03\x04 real zip payload"+ urlopen = self._fake_urlopen(zip_bytes, "application/zip")++ with patch(self._URLOPEN, urlopen):+ await interceptor._download_url_directly("https://site.example/download?f=statement.zip", "statement.zip")++ sent_request = urlopen.call_args.args[0]+ assert sent_request.get_header("Cookie") == "ASP.NET_SessionId=sess123; auth=tok"+ # The cookie must be an unredirected header so urllib does not replay it across a cross-host+ # redirect (session-cookie leak): urllib copies req.headers on redirect, not unredirected_hdrs.+ assert "Cookie" not in sent_request.headers+ assert sent_request.unredirected_hdrs.get("Cookie") == "ASP.NET_SessionId=sess123; auth=tok"+ saved = list(tmp_path.iterdir())+ assert [p.name for p in saved] == ["statement.zip"]+ assert saved[0].read_bytes() == zip_bytes++ @pytest.mark.asyncio+ async def test_cookie_header_skips_control_char_values(self, tmp_path: Path) -> None:+ # A stored cookie value with CR/LF must not inject extra directives into the Cookie line.+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context_forcing_urllib(+ [{"name": "good", "value": "ok"}, {"name": "bad", "value": "x\r\nSet-Cookie: evil=1"}]+ )+ urlopen = self._fake_urlopen(b"PK\x03\x04 zip payload", "application/zip")++ with patch(self._URLOPEN, urlopen):+ await interceptor._download_url_directly("https://site.example/download?f=statement.zip", "statement.zip")++ assert urlopen.call_args.args[0].get_header("Cookie") == "good=ok"++ @pytest.mark.asyncio+ async def test_html_login_page_for_binary_filename_not_saved(self, tmp_path: Path) -> None:+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context_forcing_urllib([])+ urlopen = self._fake_urlopen(self._LOGIN_HTML, "text/html; charset=utf-8")++ with patch(self._URLOPEN, urlopen):+ await interceptor._download_url_directly("https://site.example/download?f=statement.zip", "statement.zip")++ assert list(tmp_path.iterdir()) == []++ @pytest.mark.asyncio+ async def test_html_login_page_for_encoded_binary_filename_not_saved(self, tmp_path: Path) -> None:+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context_forcing_urllib([])+ urlopen = self._fake_urlopen(self._LOGIN_HTML, "text/html; charset=utf-8")++ with patch(self._URLOPEN, urlopen):+ await interceptor._download_url_directly("https://site.example/download?f=statement.zip", "statement%2Ezip")++ assert list(tmp_path.iterdir()) == []++ @pytest.mark.asyncio+ async def test_html_payload_for_encoded_html_filename_is_saved(self, tmp_path: Path) -> None:+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context_forcing_urllib([])+ urlopen = self._fake_urlopen(b"<!DOCTYPE html><html><body>report</body></html>", "text/html")++ with patch(self._URLOPEN, urlopen):+ await interceptor._download_url_directly("https://site.example/report", "report%2Ehtml")++ assert [path.name for path in tmp_path.iterdir()] == ["report.html"]++ @pytest.mark.asyncio+ async def test_html_payload_for_double_encoded_binary_filename_is_not_saved(self, tmp_path: Path) -> None:+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context_forcing_urllib([])+ urlopen = self._fake_urlopen(self._LOGIN_HTML, "text/html")++ with patch(self._URLOPEN, urlopen):+ await interceptor._download_url_directly(+ "https://site.example/download?f=statement%252Ezip", "statement%252Ezip"+ )++ assert list(tmp_path.iterdir()) == []++ @pytest.mark.asyncio+ async def test_html_body_without_html_content_type_still_rejected(self, tmp_path: Path) -> None:+ # Some servers mislabel the login page's content-type; sniff the body markup too.+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context_forcing_urllib([])+ urlopen = self._fake_urlopen(self._LOGIN_HTML, "application/octet-stream")++ with patch(self._URLOPEN, urlopen):+ await interceptor._download_url_directly("https://site.example/download?f=statement.zip", "statement.zip")++ assert list(tmp_path.iterdir()) == []++ @pytest.mark.parametrize(+ "body",+ [+ pytest.param(b"<!-- generated --><!DOCTYPE html><html><body>login</body></html>", id="comment"),+ pytest.param(b'<?xml version="1.0"?><html><body>login</body></html>', id="xml-declaration"),+ pytest.param(b"<head><title>Login</title></head><body>login</body>", id="omitted-html-root"),+ pytest.param(b"<head\n><title>Login</title></head><body>login</body>", id="tag-newline"),+ ],+ )+ @pytest.mark.asyncio+ async def test_html_body_with_legal_leading_markup_is_rejected(self, tmp_path: Path, body: bytes) -> None:+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context_forcing_urllib([])+ urlopen = self._fake_urlopen(body, "application/octet-stream")++ with patch(self._URLOPEN, urlopen):+ await interceptor._download_url_directly("https://site.example/download", "statement.zip")++ assert list(tmp_path.iterdir()) == []++ @pytest.mark.asyncio+ async def test_real_binary_payload_is_saved(self, tmp_path: Path) -> None:+ # Guard must not over-reject genuine binary downloads.+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context_forcing_urllib([])+ pdf = b"%PDF-1.7 real invoice bytes"+ urlopen = self._fake_urlopen(pdf, "application/pdf")++ with patch(self._URLOPEN, urlopen):+ await interceptor._download_url_directly("https://site.example/download?i=1", "invoice.pdf")++ saved = list(tmp_path.iterdir())+ assert [p.name for p in saved] == ["invoice.pdf"]+ assert saved[0].read_bytes() == pdf++ @pytest.mark.asyncio+ async def test_html_payload_for_html_filename_is_saved(self, tmp_path: Path) -> None:+ # An HTML document downloaded under an .html name is honest, not a masquerade — keep it.+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context_forcing_urllib([])+ urlopen = self._fake_urlopen(b"<!DOCTYPE html><html><body>report</body></html>", "text/html")++ with patch(self._URLOPEN, urlopen):+ await interceptor._download_url_directly("https://site.example/report", "report.html")++ saved = list(tmp_path.iterdir())+ assert [p.name for p in saved] == ["report.html"]++ @pytest.mark.asyncio+ async def test_http_browser_download_routes_through_direct_download(self, tmp_path: Path) -> None:+ # Real wiring: an http(s) browser download goes through _download_url_directly, which+ # forwards cookies and rejects the HTML login masquerade.+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context_forcing_urllib([{"name": "sid", "value": "x"}])+ urlopen = self._fake_urlopen(self._LOGIN_HTML, "text/html")++ with patch(self._URLOPEN, urlopen):+ await interceptor._handle_browser_download(+ {+ "url": "https://site.example/download?f=report.zip",+ "suggestedFilename": "report.zip",+ }+ )++ assert list(tmp_path.iterdir()) == []+ assert urlopen.call_args.args[0].get_header("Cookie") == "sid=x"++ @pytest.mark.asyncio+ async def test_nameless_binary_content_type_html_body_not_saved(self, tmp_path: Path) -> None:+ # No filename extension but a binary content-type + HTML body is still a masquerade.+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context_forcing_urllib([])+ urlopen = self._fake_urlopen(self._LOGIN_HTML, "application/octet-stream")++ with patch(self._URLOPEN, urlopen):+ await interceptor._download_url_directly("https://site.example/download", "")++ assert list(tmp_path.iterdir()) == []++ @pytest.mark.asyncio+ async def test_nameless_html_content_type_is_saved(self, tmp_path: Path) -> None:+ # A nameless download that is honestly HTML (html content-type, no binary claim) is kept.+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context_forcing_urllib([])+ urlopen = self._fake_urlopen(self._LOGIN_HTML, "text/html; charset=utf-8")++ with patch(self._URLOPEN, urlopen):+ await interceptor._download_url_directly("https://site.example/page", "")++ assert len(list(tmp_path.iterdir())) == 1++ @pytest.mark.asyncio+ async def test_extensionless_named_html_login_page_is_not_saved(self, tmp_path: Path) -> None:+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context_forcing_urllib([])+ urlopen = self._fake_urlopen(self._LOGIN_HTML, "text/html; charset=utf-8")++ with patch(self._URLOPEN, urlopen):+ await interceptor._download_url_directly("https://site.example/download", "statement")++ assert list(tmp_path.iterdir()) == []++ @pytest.mark.asyncio+ async def test_binary_payload_mislabeled_as_html_is_saved(self, tmp_path: Path) -> None:+ # A real binary payload a server mislabels as text/html must be saved, not discarded:+ # the body is the ground truth, so a non-HTML body is never treated as a masquerade.+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context_forcing_urllib([])+ zip_bytes = b"PK\x03\x04 genuine archive, not html"+ urlopen = self._fake_urlopen(zip_bytes, "text/html")++ with patch(self._URLOPEN, urlopen):+ await interceptor._download_url_directly("https://site.example/download?f=statement.zip", "statement.zip")++ saved = list(tmp_path.iterdir())+ assert [p.name for p in saved] == ["statement.zip"]+ assert saved[0].read_bytes() == zip_bytes++ @pytest.mark.asyncio+ async def test_nameless_no_content_type_html_is_saved(self, tmp_path: Path) -> None:+ # Nameless download with no content-type and an HTML body makes no binary claim, so it is+ # saved as-is (intentional "no claim, no mismatch"), not rejected.+ interceptor = CDPDownloadInterceptor(output_dir=str(tmp_path))+ interceptor._browser_context = self._context_forcing_urllib([])+ urlopen = self._fake_urlopen(self._LOGIN_HTML, "")++ with patch(self._URLOPEN, urlopen):+ await interceptor._download_url_directly("https://site.example/page", "")++ assert len(list(tmp_path.iterdir())) == 1