Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-10627): restore session cookies on saved browser profile reuse (#6362)
Celal Zamanoğlu47c6e0f2685b
diff --git a/skyvern/forge/sdk/artifact/storage/local.py b/skyvern/forge/sdk/artifact/storage/local.pyindex 1761f4033..63a7210c0 100644--- a/skyvern/forge/sdk/artifact/storage/local.py+++ b/skyvern/forge/sdk/artifact/storage/local.py@@ -22,10 +22,16 @@ from skyvern.forge.sdk.schemas.ai_suggestions import AISuggestionfrom skyvern.forge.sdk.schemas.files import FileInfofrom skyvern.forge.sdk.schemas.task_v2 import TaskV2, Thoughtfrom skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock+from skyvern.webeye.session_cookies import SESSION_COOKIES_FILENAMELOG = structlog.get_logger()WINDOWS = os.name == "nt"+# Live Chromium profiles carry runtime files that exist but can't be copied as regular files+# (Singleton sockets/locks). These are skipped during a store; a copy failure on any other file+# means an incomplete profile and is re-raised.+_TRANSIENT_PROFILE_FILES = {"RunningChromeVersion", "SingletonLock", "SingletonSocket", "SingletonCookie"}+def _safe_timestamp() -> str:ts = datetime.utcnow().isoformat()@@ -182,6 +188,36 @@ class LocalStorage(BaseStorage):except Exception:return None+ def _drop_stale_session_sidecar(self, source_directory: Path, stored_folder_path: Path) -> None:+ # These stores overlay onto an existing dir. persist_session_cookies removes the sidecar at the+ # source when a session ends with no session cookies; without this the old sidecar survives in the+ # destination and a dead session gets re-injected on the next reuse.+ if (source_directory / SESSION_COOKIES_FILENAME).exists():+ return+ stale_sidecar = stored_folder_path / SESSION_COOKIES_FILENAME+ if stale_sidecar.exists():+ stale_sidecar.unlink(missing_ok=True)++ def _copy_directory_best_effort(self, source_directory: Path, stored_folder_path: Path) -> None:+ # Source may be a live browser profile. Skip only transient runtime files: ones that vanish+ # mid-walk (FileNotFoundError) or Chrome's Singleton sockets/locks that can't be copied as+ # regular files. Re-raise anything else (e.g. ENOSPC/permission on Cookies or localStorage) so+ # a partial profile isn't silently stored and later reused as if it were valid.+ for root, _, files in os.walk(source_directory):+ for file in files:+ source_file_path = Path(root) / file+ target_file_path = stored_folder_path / source_file_path.relative_to(source_directory)+ try:+ self._create_directories_if_not_exists(target_file_path)+ shutil.copy2(source_file_path, target_file_path)+ except OSError as e:+ if isinstance(e, FileNotFoundError) or file in _TRANSIENT_PROFILE_FILES:+ LOG.debug(+ "Skipped transient profile file while storing browser dir", path=str(source_file_path)+ )+ else:+ raise+async def store_browser_session(self, organization_id: str, workflow_permanent_id: str, directory: str) -> None:stored_folder_path = self._resolve_browser_storage_path(organization_id, workflow_permanent_id)if stored_folder_path is None:@@ -204,14 +240,8 @@ class LocalStorage(BaseStorage):browser_session_path=str(stored_folder_path),)- # Copy all files from the directory to the stored folder- for root, _, files in os.walk(source_directory):- for file in files:- source_file_path = Path(root) / file- relative_path = source_file_path.relative_to(source_directory)- target_file_path = stored_folder_path / relative_path- self._create_directories_if_not_exists(target_file_path)- shutil.copy2(source_file_path, target_file_path)+ self._drop_stale_session_sidecar(source_directory, stored_folder_path)+ self._copy_directory_best_effort(source_directory, stored_folder_path)async def retrieve_browser_session(self, organization_id: str, workflow_permanent_id: str) -> str | None:stored_folder_path = self._resolve_browser_storage_path(organization_id, workflow_permanent_id)@@ -273,13 +303,8 @@ class LocalStorage(BaseStorage):browser_profile_path=str(stored_folder_path),)- for root, _, files in os.walk(source_directory):- for file in files:- source_file_path = Path(root) / file- relative_path = source_file_path.relative_to(source_directory)- target_file_path = stored_folder_path / relative_path- self._create_directories_if_not_exists(target_file_path)- shutil.copy2(source_file_path, target_file_path)+ self._drop_stale_session_sidecar(source_directory, stored_folder_path)+ self._copy_directory_best_effort(source_directory, stored_folder_path)async def retrieve_browser_profile(self, organization_id: str, profile_id: str) -> str | None:"""Retrieve browser profile from local storage."""diff --git a/skyvern/webeye/browser_factory.py b/skyvern/webeye/browser_factory.pyindex 03781fa83..1bcbf974c 100644--- a/skyvern/webeye/browser_factory.py+++ b/skyvern/webeye/browser_factory.py@@ -55,6 +55,7 @@ from skyvern.webeye.cdp_connection import ()from skyvern.webeye.cdp_download_interceptor import CDPDownloadInterceptorfrom skyvern.webeye.dialog_handler import set_dialog_handler+from skyvern.webeye.session_cookies import restore_session_cookiesLOG = structlog.get_logger()@@ -419,6 +420,7 @@ class BrowserContextFactory:if not creator:raise UnknownBrowserType(browser_type)browser_context, browser_artifacts, cleanup_func = await creator(playwright, **kwargs)+ await restore_session_cookies(browser_context, browser_artifacts.browser_session_dir)if settings.BROWSER_LOGS_ENABLED:set_browser_console_log(browser_context=browser_context, browser_artifacts=browser_artifacts)set_popup_video_listener(browser_context=browser_context, browser_artifacts=browser_artifacts)diff --git a/skyvern/webeye/default_persistent_sessions_manager.py b/skyvern/webeye/default_persistent_sessions_manager.pyindex 41f60960e..33b71075a 100644--- a/skyvern/webeye/default_persistent_sessions_manager.py+++ b/skyvern/webeye/default_persistent_sessions_manager.py@@ -26,6 +26,7 @@ from skyvern.webeye.browser_state import BrowserStatefrom skyvern.webeye.cdp_ports import _release_cdp_portfrom skyvern.webeye.persistent_sessions_manager import PersistentSessionsManagerfrom skyvern.webeye.real_browser_manager import RealBrowserManager+from skyvern.webeye.session_cookies import persist_session_cookiesLOG = structlog.get_logger()@@ -458,6 +459,11 @@ class DefaultPersistentSessionsManager(PersistentSessionsManager):# Export session profile before closing (so it can be used to create browser profiles)browser_artifacts = browser_session.browser_state.browser_artifactsif browser_artifacts and browser_artifacts.browser_session_dir:+ # Load-bearing: write the sidecar before store_browser_profile copies the dir; close()+ # also persists but runs after the export, too late for this path.+ await persist_session_cookies(+ browser_session.browser_state.browser_context, browser_artifacts.browser_session_dir+ )try:await app.STORAGE.store_browser_profile(organization_id=organization_id,diff --git a/skyvern/webeye/real_browser_state.py b/skyvern/webeye/real_browser_state.pyindex 4cd04c143..93a5aba29 100644--- a/skyvern/webeye/real_browser_state.py+++ b/skyvern/webeye/real_browser_state.py@@ -27,6 +27,7 @@ from skyvern.webeye.browser_state import BrowserStatefrom skyvern.webeye.navigation import is_permanent_navigation_error, navigate_with_retryfrom skyvern.webeye.scraper import scraperfrom skyvern.webeye.scraper.scraped_page import CleanupElementTreeFunc, ScrapedPage, ScrapeExcludeFunc+from skyvern.webeye.session_cookies import persist_session_cookiesfrom skyvern.webeye.utils.page import ScreenshotMode, SkyvernFrameLOG = structlog.get_logger()@@ -432,6 +433,8 @@ class RealBrowserState(BrowserState):async with asyncio.timeout(BROWSER_CLOSE_TIMEOUT):if self.browser_context and close_browser_on_completion:LOG.info("Closing browser context and its pages")+ session_dir = self.browser_artifacts.browser_session_dir if self.browser_artifacts else None+ await persist_session_cookies(self.browser_context, session_dir)try:await self.browser_context.close()except Exception:diff --git a/skyvern/webeye/session_cookies.py b/skyvern/webeye/session_cookies.pynew file mode 100644index 000000000..5b6836b91--- /dev/null+++ b/skyvern/webeye/session_cookies.py@@ -0,0 +1,92 @@+"""Persist/restore session-only cookies that Chromium drops from a profile's user_data_dir snapshot."""++import contextlib+import json+import os++import structlog+from playwright.async_api import BrowserContext++LOG = structlog.get_logger()++SESSION_COOKIES_FILENAME = ".skyvern_session_cookies.json"++# Keys accepted by Playwright's add_cookies; drop anything else (e.g. partitionKey)+# so one unexpected field can't reject the whole batch.+_ALLOWED_COOKIE_KEYS = {"name", "value", "domain", "path", "expires", "httpOnly", "secure", "sameSite"}++# A session cookie reports expires -1 (Playwright) or 0 (patchright/stealth-chromium fork); persistent+# cookies carry a real future timestamp and re-hydrate from the snapshot on their own.+_SESSION_COOKIE_EXPIRES = (-1, 0)+++async def persist_session_cookies(browser_context: BrowserContext | None, user_data_dir: str | None) -> None:+ """Snapshot the live context's session cookies into a sidecar inside ``user_data_dir``."""+ try:+ if browser_context is None or not user_data_dir or not os.path.isdir(user_data_dir):+ return+ path = os.path.join(user_data_dir, SESSION_COOKIES_FILENAME)+ # A cookie with no "expires" key defaults to -1 here: unknown expiry, treat as a session cookie.+ cookies = [+ cookie for cookie in await browser_context.cookies() if cookie.get("expires", -1) in _SESSION_COOKIE_EXPIRES+ ]+ if not cookies:+ # Drop a stale sidecar from a prior save so a dead session isn't re-injected on the next reuse.+ with contextlib.suppress(FileNotFoundError):+ os.remove(path)+ return+ # 0o600: the sidecar holds auth cookies. Write to a temp file and atomically replace so a failed+ # write can't leave a partial file or destroy the previous good sidecar.+ tmp = f"{path}.tmp"+ try:+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)+ with os.fdopen(fd, "w") as f:+ json.dump(cookies, f)+ os.replace(tmp, path)+ finally:+ # os.replace consumes tmp on success; clean it up if the write or replace failed partway.+ with contextlib.suppress(FileNotFoundError):+ os.remove(tmp)+ LOG.info("Persisted session cookies for browser profile", cookie_count=len(cookies))+ except Exception:+ LOG.warning("Failed to persist session cookies", exc_info=True)+++async def restore_session_cookies(browser_context: BrowserContext | None, user_data_dir: str | None) -> None:+ """Re-inject session cookies captured by ``persist_session_cookies`` if a sidecar exists."""+ try:+ if browser_context is None or not user_data_dir or not os.path.isdir(user_data_dir):+ return+ path = os.path.join(user_data_dir, SESSION_COOKIES_FILENAME)+ if not os.path.exists(path):+ return+ with open(path) as f:+ cookies = json.load(f)+ # Re-filter so a sidecar written before this filter existed (full cookie set) still narrows.+ sanitized = [+ {k: v for k, v in cookie.items() if k in _ALLOWED_COOKIE_KEYS}+ for cookie in cookies+ if cookie.get("expires", -1) in _SESSION_COOKIE_EXPIRES+ ]+ if not sanitized:+ return+ try:+ await browser_context.add_cookies(sanitized)+ LOG.info("Restored session cookies into browser profile", cookie_count=len(sanitized))+ except Exception:+ restored = 0+ for cookie in sanitized:+ try:+ await browser_context.add_cookies([cookie])+ restored += 1+ except Exception:+ LOG.debug("Skipped a cookie during restore", name=cookie.get("name"), exc_info=True)+ continue+ LOG.warning(+ "Batch cookie restore failed; restored individually",+ restored=restored,+ failed=len(sanitized) - restored,+ total=len(sanitized),+ )+ except Exception:+ LOG.warning("Failed to restore session cookies", exc_info=True)diff --git a/tests/unit/test_local_storage_browser_copy.py b/tests/unit/test_local_storage_browser_copy.pynew file mode 100644index 000000000..e0f224b1a--- /dev/null+++ b/tests/unit/test_local_storage_browser_copy.py@@ -0,0 +1,76 @@+from __future__ import annotations++import shutil+from pathlib import Path++import pytest++from skyvern.forge.sdk.artifact.storage.local import LocalStorage+from skyvern.webeye.session_cookies import SESSION_COOKIES_FILENAME+++def test_copy_directory_best_effort_skips_uncopyable_files(tmp_path: Path) -> None:+ src = tmp_path / "src"+ (src / "Default").mkdir(parents=True)+ (src / "good.txt").write_text("hello")+ (src / "Default" / "Cookies").write_text("db")+ (src / ".skyvern_session_cookies.json").write_text("[]")+ # Mimics a live Chromium profile: a path that resolves to nothing (e.g. RunningChromeVersion+ # deleted mid-walk) — shutil.copy2 raises FileNotFoundError, which must be skipped, not fatal.+ (src / "RunningChromeVersion").symlink_to(tmp_path / "missing")++ dst = tmp_path / "dst"+ LocalStorage()._copy_directory_best_effort(src, dst)++ assert (dst / "good.txt").read_text() == "hello"+ assert (dst / "Default" / "Cookies").read_text() == "db"+ assert (dst / ".skyvern_session_cookies.json").read_text() == "[]"+ assert not (dst / "RunningChromeVersion").exists()+++def test_copy_directory_best_effort_reraises_non_transient_failure(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ # A real failure on a needed file (e.g. ENOSPC/permission on Cookies) must abort the store, not+ # silently produce a partial profile that later gets reused as valid.+ src = tmp_path / "src"+ src.mkdir()+ (src / "Cookies").write_text("auth-db")+ dst = tmp_path / "dst"++ real_copy2 = shutil.copy2++ def fake_copy2(s: str | Path, d: str | Path, *args: object, **kwargs: object) -> str | Path:+ if Path(s).name == "Cookies":+ raise PermissionError("disk full")+ return real_copy2(s, d)++ monkeypatch.setattr(shutil, "copy2", fake_copy2)++ with pytest.raises(PermissionError):+ LocalStorage()._copy_directory_best_effort(src, dst)+++def test_drop_stale_session_sidecar_removes_dest_when_absent_in_source(tmp_path: Path) -> None:+ src = tmp_path / "src"+ src.mkdir()+ dst = tmp_path / "dst"+ dst.mkdir()+ (dst / SESSION_COOKIES_FILENAME).write_text("[stale]")++ LocalStorage()._drop_stale_session_sidecar(src, dst)++ assert not (dst / SESSION_COOKIES_FILENAME).exists()+++def test_drop_stale_session_sidecar_keeps_dest_when_present_in_source(tmp_path: Path) -> None:+ src = tmp_path / "src"+ src.mkdir()+ (src / SESSION_COOKIES_FILENAME).write_text("[fresh]")+ dst = tmp_path / "dst"+ dst.mkdir()+ (dst / SESSION_COOKIES_FILENAME).write_text("[stale]")++ LocalStorage()._drop_stale_session_sidecar(src, dst)++ assert (dst / SESSION_COOKIES_FILENAME).exists()diff --git a/tests/unit/test_session_cookies.py b/tests/unit/test_session_cookies.pynew file mode 100644index 000000000..a3d1ac4c4--- /dev/null+++ b/tests/unit/test_session_cookies.py@@ -0,0 +1,122 @@+from __future__ import annotations++import json+import os+import stat+from pathlib import Path+from typing import cast++import pytest+from playwright.async_api import BrowserContext++from skyvern.webeye.session_cookies import (+ SESSION_COOKIES_FILENAME,+ persist_session_cookies,+ restore_session_cookies,+)++_SESSION = {"name": "sess", "value": "a", "domain": "x.com", "path": "/", "expires": -1}+_SESSION_ZERO = {"name": "sess0", "value": "c", "domain": "x.com", "path": "/", "expires": 0}+_PERSISTENT = {"name": "persist", "value": "b", "domain": "x.com", "path": "/", "expires": 9999999999}+++class FakeContext:+ def __init__(self, cookies: list[dict] | None = None) -> None:+ self._cookies = cookies or []+ self.added: list[list[dict]] = []++ async def cookies(self) -> list[dict]:+ return list(self._cookies)++ async def add_cookies(self, cookies: list[dict]) -> None:+ self.added.append(cookies)+++class RaisingContext:+ async def cookies(self) -> list[dict]:+ raise RuntimeError("boom")++ async def add_cookies(self, cookies: list[dict]) -> None:+ raise RuntimeError("boom")+++def _ctx(fake: object) -> BrowserContext:+ return cast(BrowserContext, fake)+++def _sidecar(tmp_path: Path) -> Path:+ return tmp_path / SESSION_COOKIES_FILENAME+++async def test_persist_writes_only_session_cookies(tmp_path: Path) -> None:+ await persist_session_cookies(_ctx(FakeContext([_SESSION, _PERSISTENT])), str(tmp_path))+ written = json.loads(_sidecar(tmp_path).read_text())+ assert [c["name"] for c in written] == ["sess"]+++async def test_persist_treats_zero_expiry_as_session(tmp_path: Path) -> None:+ # patchright/stealth-chromium can report a session cookie's expiry as 0 instead of -1.+ await persist_session_cookies(_ctx(FakeContext([_SESSION_ZERO, _PERSISTENT])), str(tmp_path))+ written = json.loads(_sidecar(tmp_path).read_text())+ assert [c["name"] for c in written] == ["sess0"]+++async def test_persist_owner_only_permissions(tmp_path: Path) -> None:+ await persist_session_cookies(_ctx(FakeContext([_SESSION])), str(tmp_path))+ assert stat.S_IMODE(_sidecar(tmp_path).stat().st_mode) & 0o077 == 0+++async def test_persist_removes_stale_sidecar_when_no_session_cookies(tmp_path: Path) -> None:+ _sidecar(tmp_path).write_text(json.dumps([_SESSION]))+ await persist_session_cookies(_ctx(FakeContext([_PERSISTENT])), str(tmp_path))+ assert not _sidecar(tmp_path).exists()+++async def test_persist_cleans_tmp_on_replace_failure(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ def boom(*args: object, **kwargs: object) -> None:+ raise OSError("replace failed")++ monkeypatch.setattr(os, "replace", boom)+ # persist is best-effort: it swallows the failure and must not leave an orphaned .tmp behind.+ await persist_session_cookies(_ctx(FakeContext([_SESSION])), str(tmp_path))++ assert not (tmp_path / f"{SESSION_COOKIES_FILENAME}.tmp").exists()+ assert not _sidecar(tmp_path).exists()+++async def test_restore_sanitizes_keys_and_filters_session_only(tmp_path: Path) -> None:+ _sidecar(tmp_path).write_text(json.dumps([{**_SESSION, "partitionKey": "drop"}, _PERSISTENT]))+ fake = FakeContext()+ await restore_session_cookies(_ctx(fake), str(tmp_path))+ assert len(fake.added) == 1+ assert [c["name"] for c in fake.added[0]] == ["sess"]+ assert "partitionKey" not in fake.added[0][0]+++async def test_restore_noop_without_sidecar(tmp_path: Path) -> None:+ fake = FakeContext()+ await restore_session_cookies(_ctx(fake), str(tmp_path))+ assert fake.added == []+++async def test_best_effort_never_raises(tmp_path: Path) -> None:+ await persist_session_cookies(None, str(tmp_path))+ await persist_session_cookies(_ctx(RaisingContext()), str(tmp_path))+ _sidecar(tmp_path).write_text(json.dumps([_SESSION]))+ await restore_session_cookies(_ctx(RaisingContext()), str(tmp_path))+++async def test_restore_tolerates_corrupt_sidecar(tmp_path: Path) -> None:+ _sidecar(tmp_path).write_text("{ not valid json")+ fake = FakeContext()+ await restore_session_cookies(_ctx(fake), str(tmp_path))+ assert fake.added == []