Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Harden script sandbox validation (SKY-18441) (#8937)
Aaron Perez31a64c1a4b5d
diff --git a/skyvern/forge/sdk/workflow/code_block_safety.py b/skyvern/forge/sdk/workflow/code_block_safety.pyindex 5d9886155..a793f8fd6 100644--- a/skyvern/forge/sdk/workflow/code_block_safety.py+++ b/skyvern/forge/sdk/workflow/code_block_safety.py@@ -66,6 +66,9 @@ BLOCKED_ATTRS: frozenset[str] = frozenset("co_consts","co_names","co_varnames",+ "CodeType",+ "FunctionType",+ "LambdaType","gi_frame","gi_code","cr_frame",@@ -104,7 +107,7 @@ SANDBOX_MODULES_GLOBAL = "__codeblock_modules__"ALLOWED_SCRIPT_ATTRS: frozenset[str] = frozenset({"format", "listdir", "makedirs", "rmdir", "stderr", "stdin", "stdout"})-BLOCKED_SCRIPT_ATTRS: frozenset[str] = (BLOCKED_ATTRS - ALLOWED_SCRIPT_ATTRS) | {"config", "read_pickle"}+BLOCKED_SCRIPT_ATTRS: frozenset[str] = (BLOCKED_ATTRS - ALLOWED_SCRIPT_ATTRS) | {"config", "read_pickle", "sys"}BLOCKED_SCRIPT_IMPORTS: frozenset[str] = frozenset({"antigravity",@@ -135,9 +138,11 @@ BLOCKED_SCRIPT_IMPORTS: frozenset[str] = frozenset("site","socket","subprocess",+ "sys","thread","timeit","trace",+ "types","webbrowser","zipfile","zipimport",diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 7a584cccb..7f60355bb 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -1518,6 +1518,17 @@ async def _load_user_script_module(if not spec.loader:return Noneloaded_script_module = importlib.util.module_from_spec(spec)+ try:+ script_service._validate_stored_script_sources(script_path)+ except Exception as exc:+ LOG.warning(+ "Refusing to load unsafe stored script body",+ script_id=script_id,+ script_revision_id=script_revision_id,+ reason="safety_validation_failed",+ error_type=type(exc).__name__,+ )+ return Nonetry:spec.loader.exec_module(loaded_script_module)except Exception:@@ -8139,10 +8150,10 @@ class WorkflowService:)written_paths = await script_service.load_scripts(script, script_files)- script_path = os.path.join(settings.TEMP_PATH, script.script_id, "main.py")- # Gate on what this run wrote, not on what is on disk. TEMP_PATH is reused- # across runs and keyed by script_id rather than revision, so an earlier run's- # copy can outlive the code it came from and make os.path.exists lie.+ script_path = os.path.join(+ settings.TEMP_PATH, script.script_id, script.script_revision_id, "main.py"+ )+ # A revision-scoped path still needs a load-time gate when artifact retrieval fails.if script_path in written_paths:# setup script runparameter_tuples = await app.DATABASE.workflow_runs.get_workflow_run_parameters(@@ -8213,6 +8224,7 @@ class WorkflowService:"Script module failed to load, blocks will fall back to agent",script_id=script.script_id,)+ script_blocks_by_label = {}else:# This run has no code for the script: either the revision's stored code# is gone, or the fetch failed. Either way every run_signature would resolvediff --git a/skyvern/services/cleanup_service.py b/skyvern/services/cleanup_service.pyindex 2d4b599ba..53017da6c 100644--- a/skyvern/services/cleanup_service.py+++ b/skyvern/services/cleanup_service.py@@ -132,8 +132,8 @@ def sweep_stale_temp_artifacts(max_age_hours: float | None = None) -> int:TEMP_PATH is intentionally excluded, with one exception: the run-scoped namespace(TEMP_PATH/runs/<org>/<run>) IS swept, because it is single-tenant and keyed by runidentity — an aged run dir is a crash-path orphan. The rest of TEMP_PATH stays out:- mtime is not a safe liveness signal there — reused generated-script caches- (TEMP_PATH/<script_id>) are overwritten in place without bumping the dir mtime, and+ mtime is not a safe liveness signal there — revision-scoped generated-script caches+ (TEMP_PATH/<script_id>/<script_revision_id>) are written without bumping the parent dir mtime, andbrowser-session profile dirs are written only at open/close — both read as stale whileactively in use. LOG_PATH/DOWNLOAD_PATH are single-tenant and keyed per run, so an agedtop-level entry there is genuinely finished.diff --git a/skyvern/services/script_service.py b/skyvern/services/script_service.pyindex 531e04f06..9d6efb8ab 100644--- a/skyvern/services/script_service.py+++ b/skyvern/services/script_service.py@@ -67,7 +67,11 @@ from skyvern.forge.sdk.schemas.tasks import Task, TaskOutput, TaskStatusfrom skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlockfrom skyvern.forge.sdk.workflow.code_block_safety import is_safe_script_codefrom skyvern.forge.sdk.workflow.context_manager import BlockMetadata, register_secret_derived_output-from skyvern.forge.sdk.workflow.exceptions import FailedToFormatJinjaStyleParameter, MissingJinjaVariables+from skyvern.forge.sdk.workflow.exceptions import (+ FailedToFormatJinjaStyleParameter,+ InsecureCodeDetected,+ MissingJinjaVariables,+)from skyvern.forge.sdk.workflow.loop_download_filter import (filter_downloaded_files_for_current_iteration as _filter_downloaded_files_for_current_iteration,)@@ -474,14 +478,10 @@ async def load_scripts(script: Script,script_files: list[ScriptFile],) -> set[str]:- """Copy the revision's files locally and return the paths actually written by THIS call.-- Callers must gate on the returned set rather than os.path.exists: TEMP_PATH is reused across- runs and keyed by script_id rather than revision, so a file on disk may belong to an earlier- run whose code has since been retention-deleted. Absence from the set means "this run has no- code for that path", which is the only question the caller can answer from here -- a retention- deletion and an exhausted-retry S3 failure both surface as empty content and are not- distinguishable at this layer.+ """Copy a revision's files locally and return the paths actually written by this call.++ Callers gate on this set rather than os.path.exists because a failed or expired artifact read+ must not let a cached copy stand in for a file that was not loaded for this revision."""organization_id = script.organization_idwritten: set[str] = set()@@ -494,7 +494,7 @@ async def load_scripts(LOG.error("Artifact not found", artifact_id=file.artifact_id, script_id=script.script_id)continuefile_content = await app.ARTIFACT_MANAGER.retrieve_artifact(artifact)- file_path = os.path.join(settings.TEMP_PATH, script.script_id, file.file_path)+ file_path = os.path.join(settings.TEMP_PATH, script.script_id, script.script_revision_id, file.file_path)if not file_content:continue# create the directory if it doesn't exist@@ -521,6 +521,15 @@ async def load_scripts(return written+def _validate_stored_script_sources(main_script_path: str) -> None:+ main_path = Path(main_script_path)+ if not main_path.is_file():+ raise InsecureCodeDetected("stored script files are unavailable")+ for script_path in main_path.parent.rglob("*"):+ if script_path.is_file() and script_path.suffix.lower() == ".py":+ is_safe_script_code(script_path.read_text(encoding="utf-8"))++async def execute_script(script_id: str,organization_id: str,@@ -543,7 +552,7 @@ async def execute_script()# step 3: copy the script files to the local directory- await load_scripts(script, script_files)+ written_paths = await load_scripts(script, script_files)# step 4: execute the scriptif workflow_run_id and not parameters:@@ -551,7 +560,10 @@ async def execute_script(parameters = {wf_param.key: run_param.value for wf_param, run_param in parameter_tuples}LOG.info("Script run Parameters is using workflow run parameters", parameters=parameters)- script_path = os.path.join(settings.TEMP_PATH, script.script_id, "main.py")+ script_path = os.path.join(settings.TEMP_PATH, script.script_id, script.script_revision_id, "main.py")+ if script_path not in written_paths:+ LOG.error("Script main.py not found", script_path=script_path, script_id=script_id)+ raise Exception(f"Script main.py not found at {script_path}")if background_tasks:# Execute asynchronously in background@@ -567,19 +579,15 @@ async def execute_script()else:# Execute synchronously- if os.path.exists(script_path):- await run_script(- script_path,- parameters=parameters,- organization_id=organization_id,- workflow_run_id=workflow_run_id,- browser_session_id=browser_session_id,- script_id=script_id,- script_revision_id=script.script_revision_id,- )- else:- LOG.error("Script main.py not found", script_path=script_path, script_id=script_id)- raise Exception(f"Script main.py not found at {script_path}")+ await run_script(+ script_path,+ parameters=parameters,+ organization_id=organization_id,+ workflow_run_id=workflow_run_id,+ browser_session_id=browser_session_id,+ script_id=script_id,+ script_revision_id=script.script_revision_id,+ )LOG.info("Script executed successfully", script_id=script_id)@@ -3588,6 +3596,18 @@ async def run_script(spec = importlib.util.spec_from_file_location("user_script", path)if not spec or not spec.loader:raise Exception(f"Failed to import script from {path}")+ if script_id is not None:+ try:+ _validate_stored_script_sources(path)+ except Exception as exc:+ LOG.warning(+ "Refusing to load unsafe stored script body",+ script_id=script_id,+ script_revision_id=script_revision_id,+ reason="safety_validation_failed",+ error_type=type(exc).__name__,+ )+ raise InsecureCodeDetected("stored script safety validation failed") from Noneuser_script = importlib.util.module_from_spec(spec)spec.loader.exec_module(user_script)diff --git a/tests/unit/test_cached_script_deploy_service.py b/tests/unit/test_cached_script_deploy_service.pyindex d1ec607f9..d2a205d1d 100644--- a/tests/unit/test_cached_script_deploy_service.py+++ b/tests/unit/test_cached_script_deploy_service.py@@ -799,6 +799,9 @@ async def run(parameters):("subprocess", "import subprocess\nsubprocess.Popen(['true'])\n"),("ctypes", "import ctypes\n"),("socket", "import socket\n"),+ ("types", "import types\nvalue = types.CodeType\n"),+ ("types", "import types as runtime\nvalue = runtime.FunctionType\n"),+ ("types", "from types import CodeType, FunctionType\n"),("operator", "import operator\noperator.attrgetter('__class__')\n"),("multiprocessing", "import multiprocessing\n"),("importlib", "import importlib\n"),@@ -830,6 +833,42 @@ def test_uploaded_python_rejects_module_execution_imports(module_name: str, sourassert module_name in str(exc.value.detail)+ "source",+ [+ "import types\n"+ "code = types.CodeType(0, 0, 0, 0, 0, 0, b'', (), (), (), '', '', '', 0, b'', b'', (), ())\n"+ "types.FunctionType(code, {})()\n",+ "from types import CodeType, FunctionType\nFunctionType(CodeType, {})()\n",+ "import types as runtime\nrebuilt = runtime.FunctionType\n",+ # Attribute access must be rejected independently of import checks.+ "import asyncio\nrebuilt = asyncio.coroutines.types.FunctionType\n",+ "import asyncio\ncode = asyncio.coroutines.types.CodeType\n",+ "import asyncio\nrebuilt = asyncio.coroutines.types.LambdaType\n",+ ],+)+def test_uploaded_python_rejects_bytecode_reconstruction(source: str) -> None:+ with pytest.raises(HTTPException) as exc:+ _validate_uploaded_source(source)++ assert exc.value.status_code == 400+++ "source",+ [+ "import sys\nsys.path.insert(0, '../old_revision')\nimport helper\n",+ "import asyncio\nasyncio.sys.path.insert(0, '../old_revision')\nimport helper\n",+ ],+)+def test_uploaded_python_rejects_sys_module_access(source: str) -> None:+ with pytest.raises(HTTPException) as exc:+ _validate_uploaded_source(source)++ assert exc.value.status_code == 400+ assert "sys" in str(exc.value.detail)++@pytest.mark.parametrize("module_name", ["os", "shutil", "nt", "posix"])def test_uploaded_python_rejects_wildcard_imports(module_name: str) -> None:source = f"from {module_name} import *\n"@@ -917,7 +956,6 @@ def test_uploaded_python_rejects_locals_and_builtins_module_escapes(blocked_name"value = page.request\n","from __future__ import annotations\n","import os.path\n",- "import sys\n","value = '{}-{}'.format(a, b)\n","template = '{}/{}'\nvalue = template.format(a, b)\n","class C:\n def __init__(self):\n self._value = 1\n\n def get(self):\n return self._value\n",diff --git a/tests/unit/test_code_block_sandbox.py b/tests/unit/test_code_block_sandbox.pyindex 8e69a0259..50b6cdc70 100644--- a/tests/unit/test_code_block_sandbox.py+++ b/tests/unit/test_code_block_sandbox.py@@ -3061,6 +3061,11 @@ class TestIsSafeCodeClassStatements:def test_script_path_keeps_metaclass_support(self) -> None:is_safe_script_code("class Weird(metaclass=type):\n pass")+ @pytest.mark.parametrize("code", ["import sys", "import asyncio\nvalue = asyncio.sys"])+ def test_script_cannot_access_sys_module(self, code: str) -> None:+ with pytest.raises(InsecureCodeDetected, match="sys"):+ is_safe_script_code(code)+class TestCodeBlockMagicLink:"""SKY-14056: a credential can request an emailed sign-in link and open it."""diff --git a/tests/unit/test_run_script_lifecycle.py b/tests/unit/test_run_script_lifecycle.pyindex 91fc757cb..c17bfa1ee 100644--- a/tests/unit/test_run_script_lifecycle.py+++ b/tests/unit/test_run_script_lifecycle.py@@ -19,6 +19,7 @@ import pytestfrom skyvern.forge import appfrom skyvern.forge.sdk.artifact.manager import ArtifactManagerfrom skyvern.forge.sdk.core import skyvern_context+from skyvern.forge.sdk.workflow.exceptions import InsecureCodeDetectedfrom skyvern.schemas.workflows import BlockTypefrom skyvern.services.script_service import _create_video_artifact, _create_workflow_block_run_and_task, run_scriptfrom skyvern.webeye.browser_artifacts import BrowserArtifacts, VideoArtifact@@ -47,6 +48,7 @@ def _reset_skyvern_context():def _write_script(tmp_path: Path, body: str) -> str:path = tmp_path / "user_script.py"+ path.parent.mkdir(parents=True, exist_ok=True)path.write_text(body)return str(path)@@ -81,19 +83,51 @@ async def test_cached_script_container_task_stamps_started_at(monkeypatch: pytes@pytest.mark.asyncio-async def test_run_script_standalone_success_runs_terminal_cleanup(+async def test_run_script_ignores_sources_from_other_revisions_and_runs_cleanup(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:manager = MagicMock()manager.cleanup_for_script = AsyncMock()monkeypatch.setattr(app, "BROWSER_MANAGER", manager)- path = _write_script(tmp_path, SUCCESS_SCRIPT)+ current_revision = tmp_path / "current_revision"+ path = _write_script(current_revision, SUCCESS_SCRIPT)+ old_revision = tmp_path / "old_revision"+ old_revision.mkdir()+ (old_revision / "stale.py").write_text("import types\n")await run_script(path, script_id="scr_1", organization_id="org_1", browser_session_id="sess_1")manager.cleanup_for_script.assert_awaited_once_with("scr_1", browser_session_id="sess_1", organization_id="org_1")+async def test_run_script_revalidates_stored_script_before_execution(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ monkeypatch.setattr("skyvern.services.script_service.ensure_in_process_script_execution_allowed", AsyncMock())+ path = _write_script(tmp_path, "import types\n")++ with pytest.raises(InsecureCodeDetected, match="stored script safety validation failed"):+ await run_script(path, script_id="scr_1")+++async def test_run_script_revalidates_sibling_python_sources_before_execution(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ monkeypatch.setattr("skyvern.services.script_service.ensure_in_process_script_execution_allowed", AsyncMock())+ current_revision = tmp_path / "current_revision"+ path = _write_script(+ current_revision, "import helper\n\nasync def run_workflow(parameters=None):\n return helper.VALUE\n"+ )+ monkeypatch.syspath_prepend(str(current_revision))+ helper_path = current_revision / "helper.py"+ helper_path.write_text("import types\nVALUE = True\n")++ with pytest.raises(InsecureCodeDetected, match="stored script safety validation failed"):+ await run_script(path, script_id="scr_1")++@pytest.mark.asyncioasync def test_run_script_releases_effective_session_and_org_from_context(monkeypatch: pytest.MonkeyPatch, tmp_path: Path@@ -152,7 +186,12 @@ async def test_run_script_failure_with_release_failure_preserves_script_error(path = _write_script(tmp_path, FAILING_SCRIPT)with pytest.raises(RuntimeError, match="script boom"):- await run_script(path, script_id="scr_1", organization_id="org_1", browser_session_id="sess_1")+ await run_script(+ path,+ script_id="scr_1",+ organization_id="org_1",+ browser_session_id="sess_1",+ )sessions.release_browser_session.assert_awaited_once() # cleanup ran and swallowed the release failureassert "scr_1" not in manager.pages # the page was still reclaimed@@ -174,7 +213,12 @@ async def test_run_script_persistent_session_closes_reusable_and_releases(monkeyorder.attach_mock(state.close, "close")order.attach_mock(sessions.release_browser_session, "release")path = _write_script(tmp_path, SUCCESS_SCRIPT)- await run_script(path, script_id="scr_1", organization_id="org_1", browser_session_id="sess_1")+ await run_script(+ path,+ script_id="scr_1",+ organization_id="org_1",+ browser_session_id="sess_1",+ )state.close.assert_awaited_once_with(close_browser_on_completion=False, release_driver=False)sessions.release_browser_session.assert_awaited_once_with(session_id="sess_1",diff --git a/tests/unit/test_script_service_loop_download_filter.py b/tests/unit/test_script_service_loop_download_filter.pyindex f283f94df..7c4c2525f 100644--- a/tests/unit/test_script_service_loop_download_filter.py+++ b/tests/unit/test_script_service_loop_download_filter.py@@ -10,6 +10,7 @@ from skyvern.services.script_service import (_append_to_loop_output,_filter_downloaded_files_for_current_iteration,_to_downloaded_file_signature,+ execute_script,load_scripts,)@@ -250,9 +251,9 @@ def test_to_downloaded_file_signature_strips_fragment_without_query() -> None:async def test_load_scripts_omits_a_path_it_could_not_write(tmp_path: Path) -> None:"""The caller gates on this set, so empty content must not be reported as written -- otherwise astale copy from an earlier run gets loaded as if it were this revision's code."""- script = MagicMock(script_id="s_1", organization_id="o_1")+ script = MagicMock(script_id="s_1", script_revision_id="sr_1", organization_id="o_1")script_file = MagicMock(artifact_id="a_1", file_path="main.py", mime_type="text/x-python")- stale = tmp_path / "s_1" / "main.py"+ stale = tmp_path / "s_1" / "sr_1" / "main.py"stale.parent.mkdir(parents=True)stale.write_text("print('code the retention sweep already deleted')")@@ -267,6 +268,29 @@ async def test_load_scripts_omits_a_path_it_could_not_write(tmp_path: Path) -> Nassert str(stale) not in written+async def test_execute_script_does_not_schedule_an_old_revision_main(+ tmp_path: Path,+) -> None:+ script = MagicMock(script_id="s_1", script_revision_id="sr_current", organization_id="o_1")+ stale_main = tmp_path / "s_1" / "sr_old" / "main.py"+ stale_main.parent.mkdir(parents=True)+ stale_main.write_text("raise AssertionError('old revision')")+ background_tasks = MagicMock()++ with (+ patch("skyvern.services.script_service.settings.TEMP_PATH", str(tmp_path)),+ patch("skyvern.services.script_service.app") as mock_app,+ patch("skyvern.services.script_service.load_scripts", new_callable=AsyncMock, return_value=set()),+ ):+ mock_app.DATABASE.scripts.get_script = AsyncMock(return_value=script)+ mock_app.DATABASE.scripts.get_script_files = AsyncMock(return_value=[])+ with pytest.raises(Exception, match="Script main.py not found"):+ await execute_script("s_1", "o_1", background_tasks=background_tasks)++ background_tasks.add_task.assert_not_called()++@pytest.mark.asyncioasync def test_load_scripts_leaves_an_existing_local_copy_alone_when_the_fetch_returns_nothing(tmp_path: Path,@@ -275,9 +299,9 @@ async def test_load_scripts_leaves_an_existing_local_copy_alone_when_the_fetch_rdeletion -- download_file returns None on both paths -- so this layer cannot tell them apart.Gating on the written set rather than deleting means a transient failure costs this run itscached code without destroying the copy for the next one."""- script = MagicMock(script_id="s_1", organization_id="o_1")+ script = MagicMock(script_id="s_1", script_revision_id="sr_1", organization_id="o_1")script_file = MagicMock(artifact_id="a_1", file_path="main.py", mime_type="text/x-python")- cached = tmp_path / "s_1" / "main.py"+ cached = tmp_path / "s_1" / "sr_1" / "main.py"cached.parent.mkdir(parents=True)cached.write_text("print('a perfectly good cached script')")@@ -295,7 +319,7 @@ async def test_load_scripts_leaves_an_existing_local_copy_alone_when_the_fetch_r@pytest.mark.asyncioasync def test_load_scripts_reports_a_path_it_did_write(tmp_path: Path) -> None:- script = MagicMock(script_id="s_2", organization_id="o_1")+ script = MagicMock(script_id="s_2", script_revision_id="sr_2", organization_id="o_1")script_file = MagicMock(artifact_id="a_1", file_path="main.py", mime_type="text/x-python")with (@@ -306,5 +330,5 @@ async def test_load_scripts_reports_a_path_it_did_write(tmp_path: Path) -> None:mock_app.ARTIFACT_MANAGER.retrieve_artifact = AsyncMock(return_value=b"print('fresh')")written = await load_scripts(script, [script_file])- target = tmp_path / "s_2" / "main.py"+ target = tmp_path / "s_2" / "sr_2" / "main.py"assert str(target) in written and target.read_text() == "print('fresh')"