Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Validate deployed script content before persistence (SKY-13066) (#8037)
Trevor Cheung701f0a8c4f21
diff --git a/skyvern/forge/sdk/routes/scripts.py b/skyvern/forge/sdk/routes/scripts.pyindex 3ecefeda6..97c2a26fa 100644--- a/skyvern/forge/sdk/routes/scripts.py+++ b/skyvern/forge/sdk/routes/scripts.py@@ -1,5 +1,4 @@import asyncio-import base64import hashlibfrom typing import TYPE_CHECKING@@ -585,6 +584,7 @@ async def deploy_script(if not latest_script:raise HTTPException(status_code=404, detail="Script not found")+ file_bytes_by_path = script_service.validate_uploaded_script_files(data.files)# Create a new version of the scriptnew_version = latest_script.version + 1new_script = await app.DATABASE.scripts.create_script(@@ -610,7 +610,7 @@ async def deploy_script(if data.files:file_count = len(data.files)for file in data.files:- content_bytes = base64.b64decode(file.content)+ content_bytes = file_bytes_by_path[file.path]content_hash = hashlib.sha256(content_bytes).hexdigest()file_name = file.path.split("/")[-1]deployed_file_paths.add(file.path)diff --git a/skyvern/forge/sdk/workflow/code_block_safety.py b/skyvern/forge/sdk/workflow/code_block_safety.pyindex 5209dc8f4..e40046b4d 100644--- a/skyvern/forge/sdk/workflow/code_block_safety.py+++ b/skyvern/forge/sdk/workflow/code_block_safety.py@@ -4,7 +4,9 @@ from __future__ import annotationsimport astimport textwrap+from collections import Counterfrom collections.abc import Callable+from string import Formatterfrom skyvern.forge.sdk.workflow.exceptions import InsecureCodeDetected@@ -13,6 +15,8 @@ BLOCKED_ATTRS: frozenset[str] = frozenset({"create_subprocess_exec","create_subprocess_shell",+ "subprocess_exec",+ "subprocess_shell","system","popen","Popen",@@ -22,16 +26,25 @@ BLOCKED_ATTRS: frozenset[str] = frozenset("spawnle","spawnlp","spawnlpe",+ "spawnv",+ "spawnve",+ "spawnvp",+ "spawnvpe",+ "posix_spawn",+ "posix_spawnp","check_call","check_output","execv","execve","execvp","execvpe",+ "fexecve","execl",+ "execle","execlp","execlpe","fork",+ "forkpty","open_connection","start_server","create_connection",@@ -64,12 +77,458 @@ BLOCKED_ATTRS: frozenset[str] = frozenset("setattr","delattr","globals",+ "dictConfig",+ "fileConfig",+ "locals","eval","vars","format","format_map",+ "vformat",+ "get_field",+ "get_type_hints",})+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_IMPORTS: frozenset[str] = frozenset(+ {+ "antigravity",+ "bdb",+ "builtins",+ "cProfile",+ "code",+ "codeop",+ "ctypes",+ "dis",+ "doctest",+ "imp",+ "importlib",+ "inspect",+ "marshal",+ "multiprocessing",+ "operator",+ "nt",+ "pdb",+ "pickle",+ "pkgutil",+ "posix",+ "posixsubprocess",+ "profile",+ "pydoc",+ "pyrepl",+ "runpy",+ "site",+ "socket",+ "subprocess",+ "thread",+ "timeit",+ "trace",+ "webbrowser",+ "zipfile",+ "zipimport",+ }+)+BLOCKED_SCRIPT_IMPORT_PATHS: frozenset[str] = frozenset({"logging.config"})+BLOCKED_SCRIPT_BUILTINS: frozenset[str] = frozenset(+ {"__import__", "compile", "delattr", "eval", "exec", "getattr", "globals", "locals", "setattr", "vars"}+)+BLOCKED_SCRIPT_ESCAPE_ATTRS: frozenset[str] = frozenset(+ {+ "__bases__",+ "__builtins__",+ "__class__",+ "__code__",+ "__globals__",+ "__mro__",+ "__subclasses__",+ "__base__",+ "__delattr__",+ "__getattr__",+ "__getattribute__",+ "__init_subclass__",+ "__reduce__",+ "__reduce_ex__",+ "__setattr__",+ }+)+# ``self`` is an ordinary identifier that a module-level script can rebind to any object, so the+# self/super exemption is a name match, not proof of an instance method. Limit it to the parent-call+# dunders real subclasses need; every other dunder falls back to the private-attribute refusal.+ALLOWED_SELF_SUPER_DUNDERS: frozenset[str] = frozenset({"__init__", "__post_init__", "__enter__", "__exit__"})+ALLOWED_SCRIPT_DUNDER_READS: frozenset[str] = frozenset({"__all__", "__doc__", "__file__", "__name__"})+ALLOWED_SCRIPT_DUNDER_WRITES: frozenset[str] = frozenset({"__all__"})+ALLOWED_SCRIPT_NAMEDTUPLE_ATTRS: frozenset[str] = frozenset({"_asdict", "_fields", "_make", "_replace"})+++def _import_roots(node: ast.Import | ast.ImportFrom) -> tuple[str, ...]:+ if isinstance(node, ast.Import):+ return tuple(alias.name.partition(".")[0] for alias in node.names)+ if node.level or node.module is None:+ return ()+ return (node.module.partition(".")[0],)+++def _import_paths(node: ast.Import | ast.ImportFrom) -> tuple[str, ...]:+ if isinstance(node, ast.Import):+ return tuple(alias.name for alias in node.names)+ if node.level or node.module is None:+ return ()+ return (node.module, *(f"{node.module}.{alias.name}" for alias in node.names))+++def _normalized_import_root(module_name: str) -> str:+ return module_name.lstrip("_")+++def _is_self_or_super(node: ast.expr) -> bool:+ return (isinstance(node, ast.Name) and node.id == "self") or (+ isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "super"+ )+++def _format_field_uses_unsafe_traversal(field_name: str) -> bool:+ components = field_name.replace("[", ".").replace("]", ".").split(".")[1:]+ return any(+ component in BLOCKED_SCRIPT_ATTRS+ or component in BLOCKED_SCRIPT_ESCAPE_ATTRS+ or (component.startswith("__") and component.endswith("__"))+ for component in components+ if component+ )+++def _format_string_uses_unsafe_traversal(format_string: str) -> bool:+ pending = [format_string]+ while pending:+ try:+ for _, field_name, format_spec, _ in Formatter().parse(pending.pop()):+ if field_name is not None and _format_field_uses_unsafe_traversal(field_name):+ return True+ if format_spec:+ pending.append(format_spec)+ except ValueError:+ continue+ return False+++def _script_bindings(+ tree: ast.AST,+) -> tuple[dict[str, list[ast.expr]], dict[str, set[str]], Counter[str]]:+ assignment_values: dict[str, list[ast.expr]] = {}+ import_paths: dict[str, set[str]] = {}+ binding_counts: Counter[str] = Counter()++ def add_assignment(name: str, value: ast.expr) -> None:+ assignment_values.setdefault(name, []).append(value)++ def add_import(name: str, path: str) -> None:+ binding_counts[name] += 1+ import_paths.setdefault(name, set()).add(path)++ for node in ast.walk(tree):+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store | ast.Del):+ binding_counts[node.id] += 1+ elif isinstance(node, ast.arg):+ binding_counts[node.arg] += 1+ elif isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):+ binding_counts[node.name] += 1+ elif isinstance(node, ast.ExceptHandler) and node.name:+ binding_counts[node.name] += 1+ elif isinstance(node, ast.MatchAs | ast.MatchStar) and node.name:+ binding_counts[node.name] += 1+ elif isinstance(node, ast.MatchMapping) and node.rest:+ binding_counts[node.rest] += 1++ if isinstance(node, ast.Assign):+ for target in node.targets:+ if isinstance(target, ast.Name):+ add_assignment(target.id, node.value)+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.value is not None:+ add_assignment(node.target.id, node.value)+ elif isinstance(node, ast.NamedExpr) and isinstance(node.target, ast.Name):+ add_assignment(node.target.id, node.value)+ elif isinstance(node, ast.Import):+ for alias in node.names:+ bound_name = alias.asname or alias.name.partition(".")[0]+ add_import(bound_name, alias.name if alias.asname else bound_name)+ elif isinstance(node, ast.ImportFrom):+ for alias in node.names:+ bound_name = alias.asname or alias.name+ if node.level or node.module is None:+ binding_counts[bound_name] += 1+ else:+ add_import(bound_name, f"{node.module}.{alias.name}")++ return assignment_values, import_paths, binding_counts+++def _constant_string(+ node: ast.expr,+ assignment_values: dict[str, list[ast.expr]],+ binding_counts: Counter[str],+ resolving: frozenset[str] = frozenset(),+) -> str | None:+ if isinstance(node, ast.Constant) and isinstance(node.value, str):+ return node.value+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):+ left = _constant_string(node.left, assignment_values, binding_counts, resolving)+ right = _constant_string(node.right, assignment_values, binding_counts, resolving)+ if left is not None and right is not None:+ return left + right+ return None+ if isinstance(node, ast.Name) and node.id not in resolving:+ values = assignment_values.get(node.id, [])+ if binding_counts[node.id] == 1 and len(values) == 1:+ return _constant_string(values[0], assignment_values, binding_counts, resolving | {node.id})+ return None+++def _constant_format_string(+ node: ast.Call,+ assignment_values: dict[str, list[ast.expr]],+ binding_counts: Counter[str],+) -> str | None:+ if not isinstance(node.func, ast.Attribute) or node.func.attr != "format":+ return None+ format_string = _constant_string(node.func.value, assignment_values, binding_counts)+ if format_string is not None:+ return format_string+ if isinstance(node.func.value, ast.Name) and node.func.value.id == "str" and node.args:+ return _constant_string(node.args[0], assignment_values, binding_counts)+ return None+++def _import_paths_for_expression(+ node: ast.expr,+ assignment_values: dict[str, list[ast.expr]],+ import_paths: dict[str, set[str]],+ resolving: frozenset[str] = frozenset(),+) -> set[str]:+ if isinstance(node, ast.Name):+ paths = set(import_paths.get(node.id, set()))+ if node.id not in resolving:+ for value in assignment_values.get(node.id, []):+ paths.update(+ _import_paths_for_expression(value, assignment_values, import_paths, resolving | {node.id})+ )+ return paths+ if isinstance(node, ast.Attribute):+ return {+ f"{path}.{node.attr}"+ for path in _import_paths_for_expression(node.value, assignment_values, import_paths, resolving)+ }+ return set()+++def _numpy_load_enables_pickle(+ node: ast.Call,+ assignment_values: dict[str, list[ast.expr]],+ import_paths: dict[str, set[str]],+) -> bool:+ if not _is_numpy_load_reference(node.func, assignment_values, import_paths):+ return False+ for keyword in node.keywords:+ if keyword.arg is None:+ return True+ if keyword.arg == "allow_pickle":+ return not (isinstance(keyword.value, ast.Constant) and keyword.value.value is False)+ if len(node.args) >= 3:+ return not (isinstance(node.args[2], ast.Constant) and node.args[2].value is False)+ return False+++def _is_numpy_load_reference(+ node: ast.expr,+ assignment_values: dict[str, list[ast.expr]],+ import_paths: dict[str, set[str]],+) -> bool:+ paths = _import_paths_for_expression(node, assignment_values, import_paths)+ return any(path.partition(".")[0] == "numpy" and path.rpartition(".")[2] == "load" for path in paths)+++LOADER_ARGUMENT_YAML_FUNCTIONS: frozenset[str] = frozenset({"load", "load_all", "unsafe_load", "unsafe_load_all"})++SAFE_YAML_LOADER_NAMES: frozenset[str] = frozenset(+ {"BaseLoader", "CBaseLoader", "CSafeLoader", "FullLoader", "CFullLoader", "SafeLoader"}+)+++def _is_yaml_load_reference(+ node: ast.expr,+ assignment_values: dict[str, list[ast.expr]],+ import_paths: dict[str, set[str]],+) -> bool:+ paths = _import_paths_for_expression(node, assignment_values, import_paths)+ return any(+ path.partition(".")[0] == "yaml" and path.rpartition(".")[2] in LOADER_ARGUMENT_YAML_FUNCTIONS for path in paths+ )+++def _is_explicit_safe_yaml_loader(+ node: ast.expr,+ assignment_values: dict[str, list[ast.expr]],+ import_paths: dict[str, set[str]],+) -> bool:+ paths = _import_paths_for_expression(node, assignment_values, import_paths)+ return bool(paths) and all(+ path.partition(".")[0] == "yaml" and path.rpartition(".")[2] in SAFE_YAML_LOADER_NAMES for path in paths+ )+++def _yaml_load_uses_unsafe_loader(+ node: ast.Call,+ assignment_values: dict[str, list[ast.expr]],+ import_paths: dict[str, set[str]],+) -> bool:+ paths = _import_paths_for_expression(node.func, assignment_values, import_paths)+ yaml_load_paths = {+ path+ for path in paths+ if path.partition(".")[0] == "yaml" and path.rpartition(".")[2] in LOADER_ARGUMENT_YAML_FUNCTIONS+ }+ if not yaml_load_paths:+ return False+ if any(path.rpartition(".")[2] in {"unsafe_load", "unsafe_load_all"} for path in yaml_load_paths):+ return True+ for keyword in node.keywords:+ if keyword.arg is None:+ return True+ if keyword.arg == "Loader":+ return not _is_explicit_safe_yaml_loader(keyword.value, assignment_values, import_paths)+ if len(node.args) >= 2:+ return not _is_explicit_safe_yaml_loader(node.args[1], assignment_values, import_paths)+ return True+++def _validate_tree(+ tree: ast.AST,+ *,+ blocked_imports: frozenset[str] | None,+ blocked_import_paths: frozenset[str] = frozenset(),+ blocked_names: frozenset[str],+ error_factory: Callable[[str], Exception],+ blocked_attrs: frozenset[str] = BLOCKED_ATTRS,+ allowed_dunder_reads: frozenset[str] = frozenset(),+ allowed_dunder_writes: frozenset[str] = frozenset(),+ allowed_private_reads: frozenset[str] = frozenset(),+ blocked_private_attrs: frozenset[str] = frozenset(),+ allow_self_super_private_attrs: bool = False,+ check_constant_format_fields: bool = False,+ check_unsafe_loaders: bool = False,+) -> None:+ assignment_values, import_paths, binding_counts = _script_bindings(tree)+ directly_called = {id(node.func) for node in ast.walk(tree) if isinstance(node, ast.Call)}+ for node in ast.walk(tree):+ if isinstance(node, ast.Attribute) and node.attr in blocked_private_attrs:+ raise error_factory(f"Not allowed to access '{node.attr}'")+ if isinstance(node, ast.Attribute) and node.attr.startswith("_"):+ is_allowed_read = isinstance(node.ctx, ast.Load) and (+ node.attr in allowed_dunder_reads or node.attr in allowed_private_reads+ )+ is_dunder = node.attr.startswith("__") and node.attr.endswith("__")+ is_self_super_private = (+ allow_self_super_private_attrs+ and _is_self_or_super(node.value)+ and (not is_dunder or node.attr in ALLOWED_SELF_SUPER_DUNDERS)+ )+ if not is_allowed_read and not is_self_super_private:+ raise error_factory("Not allowed to access private methods or attributes")+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load) and node.id in blocked_names:+ raise error_factory(f"Not allowed to use '{node.id}'")+ if (+ isinstance(node, ast.Subscript)+ and isinstance(node.slice, ast.Constant)+ and isinstance(node.slice.value, str)+ and node.slice.value in blocked_names+ ):+ raise error_factory(f"Not allowed to use '{node.slice.value}'")+ if (+ isinstance(node, ast.Name)+ and node.id.startswith("__")+ and not (+ (isinstance(node.ctx, ast.Load) and node.id in allowed_dunder_reads)+ or (isinstance(node.ctx, ast.Store) and node.id in allowed_dunder_writes)+ )+ ):+ raise error_factory("Not allowed to access private methods or attributes")+ if isinstance(node, ast.Import | ast.ImportFrom):+ if isinstance(node, ast.ImportFrom) and any(alias.name == "*" for alias in node.names):+ raise error_factory("Wildcard imports are not allowed")+ if blocked_imports is None:+ raise error_factory("Not allowed to import modules")+ for module_name in _import_roots(node):+ if _normalized_import_root(module_name) in blocked_imports:+ raise error_factory(f"Not allowed to import module '{module_name}'")+ for module_path in _import_paths(node):+ if module_path in blocked_import_paths:+ raise error_factory(f"Not allowed to import module '{module_path}'")+ if isinstance(node, ast.ImportFrom):+ for alias in node.names:+ if (+ alias.name in blocked_attrs+ or alias.name in blocked_names+ or (+ alias.name.startswith("_")+ and alias.name not in allowed_dunder_reads | allowed_private_reads+ )+ ):+ raise error_factory(f"Not allowed to import '{alias.name}'")+ if (+ blocked_imports is not None+ and isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id in blocked_attrs+ ):+ raise error_factory(f"Not allowed to use '{node.func.id}'")+ if (+ check_constant_format_fields+ and isinstance(node, ast.Attribute)+ and node.attr == "format"+ and id(node) not in directly_called+ ):+ raise error_factory("Format method must be called directly")+ if (+ check_constant_format_fields+ and isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "format"+ ):+ format_string = _constant_format_string(node, assignment_values, binding_counts)+ if format_string is None:+ raise error_factory("Format string must be statically resolvable")+ if _format_string_uses_unsafe_traversal(format_string):+ raise error_factory("Not allowed to traverse attributes or subscripts in a format field")+ if (+ check_unsafe_loaders+ and isinstance(node, ast.Call)+ and _numpy_load_enables_pickle(node, assignment_values, import_paths)+ ):+ raise error_factory("Not allowed to enable pickle loading")+ if (+ check_unsafe_loaders+ and isinstance(node, ast.Name | ast.Attribute)+ and id(node) not in directly_called+ and _is_numpy_load_reference(node, assignment_values, import_paths)+ ):+ raise error_factory("NumPy load must be called directly")+ if (+ check_unsafe_loaders+ and isinstance(node, ast.Call)+ and _yaml_load_uses_unsafe_loader(node, assignment_values, import_paths)+ ):+ raise error_factory("Not allowed to use an unsafe YAML loader")+ if (+ check_unsafe_loaders+ and isinstance(node, ast.Name | ast.Attribute)+ and id(node) not in directly_called+ and _is_yaml_load_reference(node, assignment_values, import_paths)+ ):+ raise error_factory("YAML load must be called directly")+ if isinstance(node, ast.Attribute) and node.attr in blocked_attrs:+ raise error_factory(f"Not allowed to access '{node.attr}'")def is_safe_code(@@ -79,12 +538,27 @@ def is_safe_code() -> None:"""Reject imports, private members, and known escape hatches."""tree = ast.parse(textwrap.dedent(code))- for node in ast.walk(tree):- if hasattr(node, "attr") and str(node.attr).startswith("_"):- raise error_factory("Not allowed to access private methods or attributes")- if isinstance(node, ast.Name) and node.id.startswith("__"):- raise error_factory("Not allowed to access private methods or attributes")- if isinstance(node, ast.Import | ast.ImportFrom):- raise error_factory("Not allowed to import modules")- if hasattr(node, "attr") and node.attr in BLOCKED_ATTRS:- raise error_factory(f"Not allowed to access '{node.attr}'")+ _validate_tree(tree, blocked_imports=None, blocked_names=frozenset(), error_factory=error_factory)+++def is_safe_script_code(+ code: str,+ *,+ error_factory: Callable[[str], Exception] = InsecureCodeDetected,+) -> None:+ tree = ast.parse(code)+ _validate_tree(+ tree,+ blocked_imports=BLOCKED_SCRIPT_IMPORTS,+ blocked_import_paths=BLOCKED_SCRIPT_IMPORT_PATHS,+ blocked_names=BLOCKED_SCRIPT_BUILTINS | BLOCKED_SCRIPT_ESCAPE_ATTRS,+ error_factory=error_factory,+ blocked_attrs=BLOCKED_SCRIPT_ATTRS,+ allowed_dunder_reads=ALLOWED_SCRIPT_DUNDER_READS,+ allowed_dunder_writes=ALLOWED_SCRIPT_DUNDER_WRITES,+ allowed_private_reads=ALLOWED_SCRIPT_NAMEDTUPLE_ATTRS,+ blocked_private_attrs=BLOCKED_SCRIPT_ESCAPE_ATTRS,+ allow_self_super_private_attrs=True,+ check_constant_format_fields=True,+ check_unsafe_loaders=True,+ )diff --git a/skyvern/services/cached_script_deploy_service.py b/skyvern/services/cached_script_deploy_service.pyindex 480d2ce65..5fa1cec62 100644--- a/skyvern/services/cached_script_deploy_service.py+++ b/skyvern/services/cached_script_deploy_service.py@@ -1,6 +1,5 @@from __future__ import annotations-import base64import hashlibfrom dataclasses import dataclass@@ -20,17 +19,15 @@ from skyvern.schemas.scripts import (DeployCachedScriptBlockPlan,DeployCachedScriptRequest,DeployCachedScriptResponse,- FileEncoding,ScriptFileCreate,ScriptStatus,WorkflowScript,)+from skyvern.services import script_servicefrom skyvern.services.workflow_script_service import CacheKeyResolutionError, resolve_cache_key_value-from skyvern.utils.script_file_paths import SCRIPT_FILE_PATH_ERROR, normalize_script_file_path_CODE_VERSION_STATIC = 1_CODE_VERSION_ADAPTIVE = 2-_MAX_SCRIPT_FILE_BYTES = 10 * 1024 * 1024LOG = structlog.get_logger(__name__)@@ -78,41 +75,9 @@ class _CachedScriptDeployUndoState:)-def _decode_script_file_bytes(file: ScriptFileCreate) -> bytes:- if file.encoding == FileEncoding.BASE64:- try:- return base64.b64decode(file.content, validate=True)- except Exception as exc:- raise HTTPException(status_code=400, detail=f"File {file.path!r} is not valid base64") from exc- return file.content.encode("utf-8")---def _validate_script_file_path(file_path: str) -> None:- try:- normalize_script_file_path(file_path)- except ValueError as exc:- raise HTTPException(- status_code=400,- detail=f"File path {file_path!r} is invalid: {SCRIPT_FILE_PATH_ERROR}",- ) from exc--def _validate_script_files(files: list[ScriptFileCreate]) -> list[_ValidatedScriptFile]:- seen_paths: set[str] = set()- validated_files: list[_ValidatedScriptFile] = []- for file in files:- _validate_script_file_path(file.path)- if file.path in seen_paths:- raise HTTPException(status_code=400, detail=f"Duplicate script file path {file.path!r}")- seen_paths.add(file.path)- content_bytes = _decode_script_file_bytes(file)- if len(content_bytes) > _MAX_SCRIPT_FILE_BYTES:- raise HTTPException(- status_code=400,- detail=f"File {file.path!r} exceeds maximum size of {_MAX_SCRIPT_FILE_BYTES} bytes",- )- validated_files.append(_ValidatedScriptFile(file=file, content_bytes=content_bytes))- return validated_files+ file_bytes_by_path = script_service.validate_uploaded_script_files(files)+ return [_ValidatedScriptFile(file=file, content_bytes=file_bytes_by_path[file.path]) for file in files]def _main_py(files: list[_ValidatedScriptFile]) -> str:diff --git a/skyvern/services/script_service.py b/skyvern/services/script_service.pyindex f3d6ec62c..38f713a5b 100644--- a/skyvern/services/script_service.py+++ b/skyvern/services/script_service.py@@ -58,6 +58,7 @@ from skyvern.forge.sdk.models import Step, StepStatusfrom skyvern.forge.sdk.schemas.files import FileInfofrom skyvern.forge.sdk.schemas.tasks import Task, TaskOutput, TaskStatusfrom skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock+from skyvern.forge.sdk.workflow.code_block_safety import is_safe_script_codefrom skyvern.forge.sdk.workflow.context_manager import BlockMetadatafrom skyvern.forge.sdk.workflow.exceptions import FailedToFormatJinjaStyleParameter, MissingJinjaVariablesfrom skyvern.forge.sdk.workflow.loop_download_filter import (@@ -105,6 +106,7 @@ from skyvern.schemas.scripts import (from skyvern.schemas.steps import AgentStepOutputfrom skyvern.schemas.workflows import BlockResult, BlockStatus, BlockType, FileDownloadTarget, FileStorageType, FileTypefrom skyvern.utils.css_selector import build_action_summaries_with_timing+from skyvern.utils.script_file_paths import SCRIPT_FILE_PATH_ERROR, normalize_script_file_pathfrom skyvern.webeye.actions.action_types import ActionTypefrom skyvern.webeye.actions.actions import Action, DecisiveActionfrom skyvern.webeye.cdp_download_interceptor import download_filename_from_suffix@@ -126,6 +128,10 @@ VERIFIER_SWAP_FAILURE_REASON = (# Max wait for any download signal after a cached click; downstream# .crdownload polling handles in-progress completion separately. (SKY-9431)CACHED_DOWNLOAD_NO_FILE_GRACE_SECONDS = 60+_MAX_SCRIPT_FILE_BYTES = 10 * 1024 * 1024+_BLOCKED_SCRIPT_FILE_EXTENSIONS = frozenset(+ {".dylib", ".egg", ".pickle", ".pkl", ".pth", ".pyc", ".pyd", ".pyo", ".so", ".whl", ".zip"}+)class SkyvernLoopItem:@@ -142,6 +148,78 @@ class SkyvernLoopItem:return f"SkyvernLoopItem(current_value={self.current_value}, current_index={self.current_index})"+def _decode_uploaded_script_file(file: ScriptFileCreate) -> bytes:+ if file.encoding == FileEncoding.BASE64:+ try:+ return base64.b64decode(file.content, validate=True)+ except Exception as exc:+ raise HTTPException(status_code=400, detail=f"File {file.path!r} is not valid base64") from exc+ return file.content.encode("utf-8")+++def _validate_python_file(+ file: ScriptFileCreate,+ content_bytes: bytes,+ *,+ allow_invalid_python_syntax: bool = False,+) -> None:+ if Path(file.path).suffix.lower() != ".py":+ return+ try:+ source = content_bytes.decode("utf-8")+ except UnicodeDecodeError as exc:+ raise HTTPException(status_code=400, detail=f"Python file {file.path!r} is not valid UTF-8") from exc++ try:+ is_safe_script_code(source, error_factory=ValueError)+ except SyntaxError as exc:+ if allow_invalid_python_syntax:+ return+ raise HTTPException(status_code=400, detail=f"Python file {file.path!r} does not parse") from exc+ except (MemoryError, RecursionError) as exc:+ raise HTTPException(status_code=400, detail=f"Python file {file.path!r} does not parse") from exc+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=f"Python file {file.path!r} is not allowed: {exc}") from exc+++def _validate_script_files(+ files: list[ScriptFileCreate],+ *,+ allow_invalid_python_syntax: bool = False,+) -> dict[str, bytes]:+ file_bytes_by_path: dict[str, bytes] = {}+ for file in files:+ try:+ normalize_script_file_path(file.path)+ except ValueError as exc:+ raise HTTPException(+ status_code=400,+ detail=f"File path {file.path!r} is invalid: {SCRIPT_FILE_PATH_ERROR}",+ ) from exc+ file_path = Path(file.path)+ file_extension = file_path.suffix.lower() or file_path.name.lower()+ if file_extension in _BLOCKED_SCRIPT_FILE_EXTENSIONS:+ raise HTTPException(+ status_code=400,+ detail=f"File {file.path!r} has prohibited extension {file_extension!r}",+ )+ if file.path in file_bytes_by_path:+ raise HTTPException(status_code=400, detail=f"Duplicate script file path {file.path!r}")+ content_bytes = _decode_uploaded_script_file(file)+ if len(content_bytes) > _MAX_SCRIPT_FILE_BYTES:+ raise HTTPException(+ status_code=400,+ detail=f"File {file.path!r} exceeds maximum size of {_MAX_SCRIPT_FILE_BYTES} bytes",+ )+ _validate_python_file(file, content_bytes, allow_invalid_python_syntax=allow_invalid_python_syntax)+ file_bytes_by_path[file.path] = content_bytes+ return file_bytes_by_path+++def validate_uploaded_script_files(files: list[ScriptFileCreate]) -> dict[str, bytes]:+ return _validate_script_files(files)++async def build_file_tree(files: list[ScriptFileCreate],organization_id: str,@@ -149,13 +227,20 @@ async def build_file_tree(script_version: int,script_revision_id: str,pending: bool = False,+ file_bytes_by_path: dict[str, bytes] | None = None,+ allow_invalid_python_syntax: bool = False,) -> dict[str, FileNode]:"""Build a hierarchical file tree from a list of files and upload the files to s3 with the same tree structure."""file_tree: dict[str, FileNode] = {}+ if file_bytes_by_path is None:+ file_bytes_by_path = _validate_script_files(+ files,+ allow_invalid_python_syntax=allow_invalid_python_syntax,+ )for file in files:# Decode content to calculate size and hash- content_bytes = base64.b64decode(file.content)+ content_bytes = file_bytes_by_path[file.path]content_hash = hashlib.sha256(content_bytes).hexdigest()file_size = len(content_bytes)@@ -302,6 +387,7 @@ async def create_script(if run_id and not await app.DATABASE.tasks.get_run(run_id=run_id, organization_id=organization_id):raise HTTPException(status_code=404, detail=f"Run_id {run_id} not found")+ file_bytes_by_path = validate_uploaded_script_files(files or [])script = await app.DATABASE.scripts.create_script(organization_id=organization_id,run_id=run_id,@@ -316,6 +402,7 @@ async def create_script(script_id=script.script_id,script_version=script.version,script_revision_id=script.script_revision_id,+ file_bytes_by_path=file_bytes_by_path,)file_count = len(files)@@ -327,6 +414,8 @@ async def create_script(created_at=script.created_at,file_tree=file_tree,)+ except HTTPException:+ raiseexcept Exception as e:LOG.error("Failed to create script", error=str(e), exc_info=True)raise HTTPException(status_code=500, detail="Failed to create script")diff --git a/skyvern/services/workflow_script_service.py b/skyvern/services/workflow_script_service.pyindex fdeaef88c..0f6ee23d1 100644--- a/skyvern/services/workflow_script_service.py+++ b/skyvern/services/workflow_script_service.py@@ -48,6 +48,17 @@ _CACHED_DECORATOR_RE = re.compile()+def _validate_main_py(source: str) -> bytes:+ content = base64.b64encode(source.encode("utf-8")).decode("utf-8")+ file = ScriptFileCreate(+ path="main.py",+ content=content,+ encoding=FileEncoding.BASE64,+ mime_type="text/x-python",+ )+ return script_service.validate_uploaded_script_files([file])[file.path]++def _cached_label_from_decorator(decorator: ast.expr) -> str | None:if not isinstance(decorator, ast.Call):return None@@ -998,6 +1009,7 @@ async def generate_workflow_script(script_version=script.version,script_revision_id=script.script_revision_id,pending=pending,+ allow_invalid_python_syntax=True,)# check if an existing draft workflow script exists for this workflow run@@ -1978,7 +1990,7 @@ async def create_script_version_from_review()return new_script- patched_bytes = patched_main.encode("utf-8")+ patched_bytes = _validate_main_py(patched_main)patched_hash = hashlib.sha256(patched_bytes).hexdigest()main_artifact_id = await app.ARTIFACT_MANAGER.create_script_file_artifact(@@ -2163,6 +2175,8 @@ async def create_script_version_from_full_code()return None+ main_bytes = _validate_main_py(full_main_py)+# Compile the full main.py BEFORE creating the new version. A broken# rewrite should not persist any artifacts or DB rows.try:@@ -2208,7 +2222,6 @@ async def create_script_version_from_full_code()# Write the full main.py verbatim.- main_bytes = full_main_py.encode("utf-8")main_hash = hashlib.sha256(main_bytes).hexdigest()main_artifact_id = await app.ARTIFACT_MANAGER.create_script_file_artifact(diff --git a/tests/unit/test_cached_script_deploy_service.py b/tests/unit/test_cached_script_deploy_service.pyindex 9d3a0f0e2..95cf7963d 100644--- a/tests/unit/test_cached_script_deploy_service.py+++ b/tests/unit/test_cached_script_deploy_service.py@@ -5,24 +5,53 @@ from types import SimpleNamespaceimport pytestfrom fastapi import HTTPException+from skyvern.core.script_generations.generate_script import CodeGenResultfrom skyvern.forge.sdk.db.exceptions import NotFoundErrorfrom skyvern.forge.sdk.db.repositories.scripts import WorkflowScriptUpsertStatus+from skyvern.forge.sdk.routes import scripts as scripts_routesfrom skyvern.forge.sdk.workflow.models.workflow import Workflowfrom skyvern.schemas.scripts import (+ CreateScriptRequest,DeployCachedScriptCacheContext,DeployCachedScriptRequest,+ DeployCachedScriptResponse,+ DeployScriptRequest,FileEncoding,ScriptFileCreate,ScriptStatus,WorkflowScript,)-from skyvern.services import cached_script_deploy_service+from skyvern.services import cached_script_deploy_service, script_service, workflow_script_servicedef _b64(text: str) -> str:return base64.b64encode(text.encode("utf-8")).decode("utf-8")+def _script_file(path: str, source: str, *, mime_type: str = "text/x-python") -> ScriptFileCreate:+ return ScriptFileCreate(+ path=path,+ content=_b64(source),+ encoding=FileEncoding.BASE64,+ mime_type=mime_type,+ )+++_REALISTIC_GENERATED_MAIN = """+import skyvern+[email protected](title="t")+async def run(parameters):+ page, context = await skyvern.setup(parameters, dict)+ try:+ await page.wait_for_load_state()+ except TimeoutError:+ pass+ else:+ await skyvern.run_task(prompt="...", label="step_a", cache_key="step_a")+"""++def _workflow(*,cache_key: str | None = "default",@@ -144,6 +173,18 @@ def _request()+async def _deploy_files(files: list[ScriptFileCreate]) -> DeployCachedScriptResponse:+ return await cached_script_deploy_service.deploy_cached_script(+ organization_id="org_test",+ workflow_permanent_id="wpid_test",+ request=_request(_REALISTIC_GENERATED_MAIN, dry_run=False, files=files),+ )+++def _validate_uploaded_source(source: str) -> dict[str, bytes]:+ return script_service.validate_uploaded_script_files([_script_file("main.py", source)])++@pytest.fixture(autouse=True)def _stub_app(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:workflow = _workflow()@@ -201,16 +242,26 @@ def _stub_app(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:async def create_script(self, **kwargs: object) -> SimpleNamespace:state.created_scripts.append(kwargs)return SimpleNamespace(- script_id="s_created",+ script_id=kwargs.get("script_id", "s_created"),script_revision_id="sr_created",- version=1,+ version=kwargs.get("version", 1),run_id=kwargs.get("run_id"),+ created_at=datetime.now(timezone.utc),)async def create_script_file(self, **kwargs: object) -> SimpleNamespace:state.created_files.append(kwargs)return SimpleNamespace(file_id=f"sf_{len(state.created_files)}")+ async def get_latest_script_version(self, **_: object) -> SimpleNamespace:+ return SimpleNamespace(script_id="s_existing", script_revision_id="sr_existing", version=1, run_id=None)++ async def get_script_files(self, **_: object) -> list[object]:+ return []++ async def get_script_blocks_by_script_revision_id(self, **_: object) -> list[object]:+ return []+async def upsert_script_block(self, **kwargs: object) -> SimpleNamespace:state.created_blocks.append(kwargs)return SimpleNamespace(script_block_id=f"sb_{len(state.created_blocks)}")@@ -231,6 +282,10 @@ def _stub_app(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:previous_workflow_script=state.previous_workflow_script,)+ async def create_workflow_script(self, **kwargs: object) -> SimpleNamespace:+ state.workflow_script_upserts.append(kwargs)+ return SimpleNamespace(**kwargs)+async def soft_delete_workflow_script_if_matches(self, **kwargs: object) -> bool:state.soft_deleted_workflow_scripts.append(kwargs["workflow_script"])return state.workflow_script_soft_delete_matches@@ -267,6 +322,15 @@ def _stub_app(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:return state+def _assert_no_persistence_writes(state: SimpleNamespace) -> None:+ assert state.created_scripts == []+ assert state.artifacts == []+ assert state.created_files == []+ assert state.created_blocks == []+ assert state.workflow_script_upserts == []+ assert state.workflow_updates == []++@pytest.mark.asyncioasync def test_dry_run_returns_cache_key_and_block_plan() -> None:source = """@@ -723,6 +787,564 @@ async def run(parameters):assert _stub_app.soft_deleted_script_revisions == ["sr_created"]+ ("module_name", "source"),+ [+ ("runpy", "import runpy\nrunpy.run_module('helper')\n"),+ ("pickle", "import pickle\nvalue = pickle.loads(payload)\n"),+ ("marshal", "import marshal\nvalue = marshal.loads(payload)\n"),+ ("subprocess", "import subprocess\nsubprocess.Popen(['true'])\n"),+ ("ctypes", "import ctypes\n"),+ ("socket", "import socket\n"),+ ("operator", "import operator\noperator.attrgetter('__class__')\n"),+ ("multiprocessing", "import multiprocessing\n"),+ ("importlib", "import importlib\n"),+ ("zipimport", "import zipimport\nz = zipimport.zipimporter('x.zip')\nz.load_module('payload')\n"),+ ("imp", "import imp\nimp.load_source('payload', 'payload.dat')\n"),+ ("pkgutil", "import pkgutil\nloader = pkgutil.get_importer('x.zip')\n"),+ ("zipfile", "import zipfile\nzipfile.ZipFile('x.zip').extractall('payload')\n"),+ ("_pickle", "import _pickle\n"),+ ("_socket", "import _socket\n"),+ ("_posixsubprocess", "import _posixsubprocess\n"),+ ("_ctypes", "import _ctypes\n"),+ ("_multiprocessing", "import _multiprocessing\n"),+ ("_thread", "import _thread\n"),+ ("_socket", "from _socket import socket\n"),+ ("subprocess", "from subprocess import Popen\n"),+ ("nt", "import nt\n"),+ ("posix", "import posix\n"),+ (+ "logging",+ "import logging.config\nlogging.config.dictConfig({'version': 1, 'handler': {'()': 'os.system'}})\n",+ ),+ ],+)+def test_uploaded_python_rejects_module_execution_imports(module_name: str, source: str) -> None:+ with pytest.raises(HTTPException) as exc:+ _validate_uploaded_source(source)++ assert exc.value.status_code == 400+ assert module_name in str(exc.value.detail)++[email protected]("module_name", ["os", "shutil", "nt", "posix"])+def test_uploaded_python_rejects_wildcard_imports(module_name: str) -> None:+ source = f"from {module_name} import *\n"++ with pytest.raises(HTTPException) as exc:+ _validate_uploaded_source(source)++ assert exc.value.status_code == 400+ assert "Wildcard imports" in str(exc.value.detail)+++ ("blocked_name", "source"),+ [+ ("eval", "value = eval('1 + 1')\n"),+ ("exec", "exec('value = 1')\n"),+ ("__import__", "module = __import__('json')\n"),+ ("compile", "code = compile('value = 1', '<string>', 'exec')\n"),+ ("builtins", "import builtins as runtime\nvalue = runtime.eval('1 + 1')\n"),+ ("getattr", "g = getattr\nvalue = g(object, '__subclasses__')\n"),+ ("getattr", "dispatch = {'f': getattr}\nvalue = dispatch['f'](object, '__class__')\n"),+ ("setattr", "setter = setattr\nsetter(object, 'x', 1)\n"),+ ("delattr", "deleter = delattr\n"),+ ("vars", "inspect_vars = vars\n"),+ ("globals", "namespace = globals\n"),+ ],+)+def test_uploaded_python_rejects_dynamic_execution_builtins(blocked_name: str, source: str) -> None:+ with pytest.raises(HTTPException) as exc:+ _validate_uploaded_source(source)++ assert exc.value.status_code == 400+ assert blocked_name in str(exc.value.detail)+++ ("blocked_name", "source"),+ [+ (+ "eval",+ "locals()['__builtins__']['eval'](\"__import__('os').system('id')\")\n",+ ),+ ("locals", "d = locals()\n"),+ ("eval", "d = {}\nx = d['eval']\n"),+ ("builtins", "import builtins\nb = builtins\nb.compile('1', '<s>', 'exec')\n"),+ ("builtins", "import builtins\nb = builtins\nx = b.locals()\n"),+ ("builtins", "import builtins\n"),+ ("builtins", "from builtins import compile as c\n"),+ ],+ ids=[+ "locals-chain",+ "locals-bare",+ "blocked-subscript-key",+ "rebound-builtins-compile",+ "rebound-builtins-locals",+ "import-builtins",+ "from-builtins",+ ],+)+def test_uploaded_python_rejects_locals_and_builtins_module_escapes(blocked_name: str, source: str) -> None:+ with pytest.raises(HTTPException) as exc:+ _validate_uploaded_source(source)++ assert exc.value.status_code == 400+ assert blocked_name in str(exc.value.detail)+++ "source",+ [+ "import os\nvalue = os.getenv('KEY')\nos.makedirs('output', exist_ok=True)\n",+ "from urllib.parse import urlsplit\nupdated = urlsplit('https://example.com')._replace(scheme='http')\n",+ "value = '{}'.format(1)\n",+ "value = '{0} {name}'.format('x', name='y')\n",+ "value = '{0.name}'.format(obj)\n",+ "value = '{d[key]}'.format(d=mapping)\n",+ "__all__ = ['run']\n",+ "import re\nvalue = re.compile('ok')\n",+ "value = __file__\n",+ "if __name__ == '__main__':\n pass\n",+ "value = module.__name__\n",+ "value = module.__all__\n",+ "value = module.__doc__\n",+ "value = page.context\n",+ "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",+ "class C(Base):\n def __init__(self):\n super().__init__()\n",+ ],+)+def test_uploaded_python_accepts_deployed_python_apis(source: str) -> None:+ assert _validate_uploaded_source(source) == {"main.py": source.encode("utf-8")}+++ "snippet",+ [+ "import os\nos.system('true')\n",+ "import os\nos.popen('true')\n",+ "import os\nos.posix_spawn('/bin/true', ['/bin/true'], {})\n",+ "import os\nos.posix_spawnp('true', ['true'], {})\n",+ "import os\nos.spawnv(os.P_WAIT, '/bin/true', ['/bin/true'])\n",+ "import os\nos.spawnve(os.P_WAIT, '/bin/true', ['/bin/true'], {})\n",+ "import os\nos.spawnvp(os.P_WAIT, 'true', ['true'])\n",+ "import os\nos.spawnvpe(os.P_WAIT, 'true', ['true'], {})\n",+ "import os\nos.forkpty()\n",+ "import os\nos.execle('/bin/true', 'true', {})\n",+ "leak = ().__class__\n",+ "leak = f.__globals__\n",+ "leak = ().__class__.__subclasses__()\n",+ "from builtins import __dict__ as namespace\nleak = namespace['eval']\n",+ "import asyncio\nasyncio.get_event_loop().subprocess_shell(proto, 'id')\n",+ "import asyncio\nasyncio.get_event_loop().subprocess_exec(proto, 'id')\n",+ ("import typing\nclass C:\n value: \"__import__('os').system('id')\"\ntyping.get_type_hints(C)\n"),+ (+ "import typing_extensions\nclass C:\n"+ " value: \"__import__('os').system('id')\"\n"+ "typing_extensions.get_type_hints(C)\n"+ ),+ (+ "import os\nfrom string import Formatter\nclass C: pass\n"+ 'run = Formatter().get_field("0.__init__.__globals__[os].system", (C(),), {})[0]\n'+ "run('id')\n"+ ),+ "class C:\n def leak(self):\n return self.__class__\n",+ "class C(Base):\n def leak(self):\n return super().__class__\n",+ ],+)+def test_uploaded_python_rejects_execution_and_escape_attributes(snippet: str) -> None:+ with pytest.raises(HTTPException) as exc:+ _validate_uploaded_source(snippet)++ assert exc.value.status_code == 400+++ "source",+ [+ "class C: pass\nvalue = '{0.__init__.__globals__[__builtins__]}'.format(C())\n",+ "class C: pass\nvalue = str.format('{0.__init__.__globals__[__builtins__]}', C())\n",+ "class C: pass\ntemplate = '{0.__init__.__globals__[__builtins__]}'\nvalue = template.format(C())\n",+ ("class C: pass\ntemplate = '{0.__init__' + '.__globals__[__builtins__]}'\nvalue = template.format(C())\n"),+ "value = '{item[__class__]}'.format(item={})\n",+ "value = '{0:{1.__class__}}'.format('x', object())\n",+ ],+)+def test_uploaded_python_rejects_constant_format_field_traversal(source: str) -> None:+ with pytest.raises(HTTPException) as exc:+ _validate_uploaded_source(source)++ assert exc.value.status_code == 400+ assert "format field" in str(exc.value.detail)+++def test_uploaded_python_rejects_runtime_format_string() -> None:+ source = "def render(template, value):\n return template.format(value)\n"++ with pytest.raises(HTTPException) as exc:+ _validate_uploaded_source(source)++ assert exc.value.status_code == 400+ assert "statically resolvable" in str(exc.value.detail)+++ "attribute",+ [+ "__getattribute__",+ "__getattr__",+ "__setattr__",+ "__delattr__",+ "__reduce__",+ "__reduce_ex__",+ "__dict__",+ "__class__",+ "__init_subclass__",+ ],+)+def test_uploaded_python_rejects_reflection_dunders_on_a_rebound_self(attribute: str) -> None:+ # ``self`` is an ordinary identifier: a module-level script can bind it to any object, so the+ # self/super carve-out is a name match and must not extend to reflection dunders.+ with pytest.raises(HTTPException) as exc:+ _validate_uploaded_source(f'self = ""\nvalue = self.{attribute}\n')++ assert exc.value.status_code == 400+++def test_uploaded_python_rejects_the_rebound_self_subclasses_chain() -> None:+ with pytest.raises(HTTPException) as exc:+ _validate_uploaded_source(+ 'self = ""\n'+ 'self = self.__getattribute__("__class__")\n'+ 'self = self.__getattribute__("__base__")\n'+ 'self = self.__getattribute__("__subclasses__")\n'+ "self = self()\n"+ "value = len(self)\n"+ )++ assert exc.value.status_code == 400+++ "source",+ [+ "class A:\n def f(self):\n return self._value\n",+ "class A:\n def f(self):\n return self._helper()\n",+ "class A(B):\n def __init__(self):\n super().__init__()\n",+ "class A(B):\n def __enter__(self):\n return super().__enter__()\n",+ ],+)+def test_uploaded_python_still_allows_ordinary_self_and_super_use(source: str) -> None:+ _validate_uploaded_source(source)+++def test_uploaded_python_rejects_formatter_vformat() -> None:+ source = "import string\nvalue = string.Formatter().vformat('{0.__globals__[__builtins__]}', [fn], {})\n"++ with pytest.raises(HTTPException) as exc:+ _validate_uploaded_source(source)++ assert exc.value.status_code == 400+ assert "vformat" in str(exc.value.detail)+++ "source",+ [+ ("class C: pass\nmethod = '{0.__init__.__globals__[__builtins__]}'.format\nvalue = method(C())\n"),+ ("class C: pass\nmethod = str.format\nvalue = method('{0.__init__.__globals__[__builtins__]}', C())\n"),+ ],+)+def test_uploaded_python_rejects_format_callable_alias(source: str) -> None:+ with pytest.raises(HTTPException) as exc:+ _validate_uploaded_source(source)++ assert exc.value.status_code == 400+ assert "called directly" in str(exc.value.detail)++[email protected]("file_path", ["main.PY", "main.Py", "helper.PY"])+def test_uploaded_python_rejects_unsafe_uppercase_extension(file_path: str) -> None:+ with pytest.raises(HTTPException) as exc:+ script_service.validate_uploaded_script_files([_script_file(file_path, "import os\nos.system('id')\n")])++ assert exc.value.status_code == 400+ assert "system" in str(exc.value.detail)+++def test_uploaded_python_rejects_unparseable_file() -> None:+ with pytest.raises(HTTPException) as exc:+ _validate_uploaded_source("def broken(:\n pass\n")++ assert exc.value.status_code == 400+ assert "main.py" in str(exc.value.detail)+++def test_uploaded_python_rejects_parser_stack_overflow() -> None:+ with pytest.raises(HTTPException) as exc:+ _validate_uploaded_source("+" * 200_000 + "1")++ assert exc.value.status_code == 400+ assert exc.value.detail == "Python file 'main.py' does not parse"++[email protected]("error_type", [MemoryError, RecursionError])+def test_uploaded_python_handles_parser_resource_errors(+ monkeypatch: pytest.MonkeyPatch, error_type: type[BaseException]+) -> None:+ def raise_parser_error(*_: object, **__: object) -> None:+ raise error_type++ monkeypatch.setattr(script_service, "is_safe_script_code", raise_parser_error)++ with pytest.raises(HTTPException) as exc:+ _validate_uploaded_source("value = 1\n")++ assert exc.value.status_code == 400+ assert exc.value.detail == "Python file 'main.py' does not parse"+++async def test_build_file_tree_validates_when_decoded_bytes_are_omitted(_stub_app: SimpleNamespace) -> None:+ files = [_script_file("main.py", "import os\nos.system('id')\n")]++ with pytest.raises(HTTPException) as exc:+ await script_service.build_file_tree(+ files=files,+ organization_id="org_test",+ script_id="s_test",+ script_version=1,+ script_revision_id="sr_test",+ )++ assert exc.value.status_code == 400+ _assert_no_persistence_writes(_stub_app)+++async def test_generated_script_persists_unparseable_main_for_repair(+ monkeypatch: pytest.MonkeyPatch, _stub_app: SimpleNamespace+) -> None:+ source = "async def broken(:\n pass\n"++ async def transform_workflow_run_to_code_gen_input(**_: object) -> SimpleNamespace:+ return SimpleNamespace(+ file_name="main.py",+ workflow_run={},+ workflow={},+ workflow_blocks=[{"label": "step_a"}],+ actions_by_task={},+ task_v2_child_blocks={},+ )++ async def generate_workflow_script_python_code(**_: object) -> CodeGenResult:+ return CodeGenResult(source_code=source, blocks_created=1, blocks_failed=0)++ async def skip_mint_audit(**_: object) -> None:+ return None++ monkeypatch.setattr(+ workflow_script_service,+ "transform_workflow_run_to_code_gen_input",+ transform_workflow_run_to_code_gen_input,+ )+ monkeypatch.setattr(+ workflow_script_service,+ "generate_workflow_script_python_code",+ generate_workflow_script_python_code,+ )+ monkeypatch.setattr(workflow_script_service, "is_adaptive_caching", lambda *_: False)+ monkeypatch.setattr(workflow_script_service, "_log_mint_audit_findings", skip_mint_audit)++ await workflow_script_service.generate_workflow_script(+ workflow_run=SimpleNamespace(workflow_run_id="wr_test"),+ workflow=SimpleNamespace(+ workflow_id="wf_test",+ workflow_permanent_id="wpid_test",+ organization_id="org_test",+ title="test",+ cache_key="default",+ ),+ script=SimpleNamespace(script_id="s_test", script_revision_id="sr_test", version=1),+ rendered_cache_key_value="default:test",+ )++ assert _stub_app.artifacts[0]["data"] == source.encode("utf-8")+ assert _stub_app.created_files[0]["file_path"] == "main.py"+++async def test_generated_script_tolerance_still_rejects_parseable_policy_violation(+ _stub_app: SimpleNamespace,+) -> None:+ files = [_script_file("main.py", "import os\nos.system('command')\n")]++ with pytest.raises(HTTPException) as exc:+ await script_service.build_file_tree(+ files=files,+ organization_id="org_test",+ script_id="s_test",+ script_version=1,+ script_revision_id="sr_test",+ allow_invalid_python_syntax=True,+ )++ assert exc.value.status_code == 400+ _assert_no_persistence_writes(_stub_app)++[email protected]("file_path", ["data.pkl", "data.pickle"])+def test_uploaded_python_rejects_pickle_file_with_pandas_loader(file_path: str) -> None:+ files = [+ _script_file("main.py", f"import pandas\nvalue = pandas.read_pickle('{file_path}')\n"),+ _script_file(file_path, "serialized payload", mime_type="application/octet-stream"),+ ]++ with pytest.raises(HTTPException) as exc:+ script_service.validate_uploaded_script_files(files)++ assert exc.value.status_code == 400+++ "source",+ [+ "import pandas\nvalue = pandas.read_pickle('data.bin')\n",+ "from pandas import read_pickle\nvalue = read_pickle('data.bin')\n",+ "import numpy as np\nvalue = np.load('data.npy', allow_pickle=True)\n",+ "from numpy import load\nvalue = load('data.npy', None, True)\n",+ "import numpy as np\noptions = {}\nvalue = np.load('data.npy', **options)\n",+ "import numpy as np\n(loader,) = (np.load,)\nvalue = loader('data.npy', allow_pickle=True)\n",+ "import numpy as np\nloader = [np.load][0]\nvalue = loader('data.npy', allow_pickle=True)\n",+ ("import numpy as np\ndef run(loader=np.load):\n return loader('data.npy', allow_pickle=True)\n"),+ ],+)+def test_uploaded_python_rejects_pickle_backed_dependency_loaders(source: str) -> None:+ with pytest.raises(HTTPException) as exc:+ _validate_uploaded_source(source)++ assert exc.value.status_code == 400+++ "source",+ [+ "import numpy as np\nvalue = np.load('data.npy')\n",+ "import numpy as np\nvalue = np.load('data.npy', allow_pickle=False)\n",+ ],+)+def test_uploaded_python_allows_numpy_load_without_pickle(source: str) -> None:+ _validate_uploaded_source(source)+++ "source",+ [+ "import yaml\nvalue = yaml.unsafe_load(payload)\n",+ "from yaml import unsafe_load as load\nvalue = load(payload)\n",+ "import yaml\nvalue = yaml.load(payload, Loader=yaml.UnsafeLoader)\n",+ "import yaml\nvalue = yaml.load(payload, yaml.UnsafeLoader)\n",+ "import yaml\nvalue = yaml.load(payload, Loader=loader_type)\n",+ "import yaml\noptions = {'Loader': yaml.SafeLoader}\nvalue = yaml.load(payload, **options)\n",+ "import yaml\nload = yaml.load\nvalue = load(payload, Loader=yaml.UnsafeLoader)\n",+ "import yaml\nvalue = yaml.unsafe_load_all(payload)\n",+ "import yaml\nvalue = yaml.load_all(payload, Loader=yaml.Loader)\n",+ "import yaml\nvalue = yaml.load_all(payload)\n",+ "import yaml\nvalue = yaml.load_all(payload, yaml.CLoader)\n",+ "from yaml import unsafe_load_all as load_stream\nvalue = load_stream(payload)\n",+ ],+)+def test_uploaded_python_rejects_unsafe_yaml_loaders(source: str) -> None:+ with pytest.raises(HTTPException) as exc:+ _validate_uploaded_source(source)++ assert exc.value.status_code == 400+ assert "YAML" in str(exc.value.detail)+++ "source",+ [+ "import yaml\nvalue = yaml.safe_load(payload)\n",+ "import yaml\nvalue = yaml.load(payload, Loader=yaml.SafeLoader)\n",+ "import yaml\nvalue = yaml.load(payload, yaml.SafeLoader)\n",+ "from yaml import SafeLoader, load\nvalue = load(payload, Loader=SafeLoader)\n",+ "import yaml\nvalue = yaml.safe_load_all(payload)\n",+ "import yaml\nvalue = yaml.full_load_all(payload)\n",+ "import yaml\nvalue = yaml.load_all(payload, Loader=yaml.SafeLoader)\n",+ ],+)+def test_uploaded_python_allows_safe_yaml_loaders(source: str) -> None:+ _validate_uploaded_source(source)+++async def test_create_script_route_rejects_eval_upload(_stub_app: SimpleNamespace) -> None:+ request = CreateScriptRequest(files=[_script_file("main.py", "value = eval('1 + 1')\n")])++ with pytest.raises(HTTPException) as exc:+ await scripts_routes.create_script(request, SimpleNamespace(organization_id="org_test"))++ assert exc.value.status_code == 400+ _assert_no_persistence_writes(_stub_app)+++async def test_deploy_script_route_rejects_eval_upload(_stub_app: SimpleNamespace) -> None:+ request = DeployScriptRequest(files=[_script_file("main.py", "value = eval('1 + 1')\n")])++ with pytest.raises(HTTPException) as exc:+ await scripts_routes.deploy_script(request, "s_existing", SimpleNamespace(organization_id="org_test"))++ assert exc.value.status_code == 400+ _assert_no_persistence_writes(_stub_app)+++async def test_commit_mode_accepts_blocked_names_as_parameter_field_declarations(+ _stub_app: SimpleNamespace,+) -> None:+ source = (+ """from pydantic import BaseModel+++class WorkflowParameters(BaseModel):+ format: str+ system: str+ os: str+ stdout: str+"""+ + _REALISTIC_GENERATED_MAIN+ )++ response = await _deploy_files([_script_file("main.py", source)])++ assert response.script_was_created is True+ assert _stub_app.created_files[0]["file_path"] == "main.py"+++async def test_commit_mode_leaves_non_python_files_unaffected(_stub_app: SimpleNamespace) -> None:+ non_python_content = "import os\nexec('value = 1')\ndef broken(\n"+ files = [+ _script_file("main.py", _REALISTIC_GENERATED_MAIN),+ _script_file("notes.txt", non_python_content, mime_type="text/plain"),+ ]++ response = await _deploy_files(files)++ assert response.script_was_created is True+ assert [file["file_path"] for file in _stub_app.created_files] == ["main.py", "notes.txt"]+ assert _stub_app.artifacts[1]["data"] == non_python_content.encode("utf-8")++@pytest.mark.asyncio@pytest.mark.parametrize("file_path",@@ -841,7 +1463,7 @@ async def run(parameters):@pytest.mark.asyncioasync def test_dry_run_rejects_oversized_file(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr(cached_script_deploy_service, "_MAX_SCRIPT_FILE_BYTES", 4)+ monkeypatch.setattr(script_service, "_MAX_SCRIPT_FILE_BYTES", 4)source = """import skyvern@@ -1009,3 +1631,49 @@ async def run(parameters):assert exc.value.status_code == 409assert "became stale" in str(exc.value.detail)+++ "source",+ [+ "import logging.config\n",+ "from logging.config import dictConfig\ndictConfig({'version': 1})\n",+ "from logging import config\nconfig.dictConfig({'version': 1})\n",+ "import logging.config as c\nc.dictConfig({'version': 1})\n",+ "import logging\nlogging.config.dictConfig({'version': 1})\n",+ "import logging\nlogging.config.fileConfig('logging.ini')\n",+ "import logging\nlogging.config.BaseConfigurator({}).resolve('os.system')\n",+ "import logging\nlogging.config.BaseConfigurator({}).convert('ext://os.system')\n",+ "import logging\nlogging.config.dictConfigClass({}).configure()\n",+ "import logging\nlogging.config.listen(9999)\n",+ ],+ ids=[+ "import-submodule",+ "from-submodule",+ "from-parent",+ "aliased",+ "dict-config",+ "file-config",+ "base-configurator-resolve",+ "base-configurator-convert",+ "dict-config-class",+ "listen",+ ],+)+def test_uploaded_python_rejects_logging_config_callable_resolution(source: str) -> None:+ with pytest.raises(HTTPException) as exc:+ _validate_uploaded_source(source)++ assert exc.value.status_code == 400+++ "source",+ [+ "import logging\nlog = logging.getLogger(__name__)\nlog.info('ready')\n",+ "from logging import getLogger\nlog = getLogger('run')\n",+ ],+ ids=["module", "from-import"],+)+def test_uploaded_python_allows_ordinary_logging(source: str) -> None:+ _validate_uploaded_source(source)