Merge branch 'dev'
Browse filesFiles changed (4)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192"""ALLI Sandboxed Custom Python Script Node Executor.Implements AST static safety inspection, allowlisted safe builtins,dynamic port binding, and local execution for code.python nodes."""
import astimport datetime as _dtimport inspectimport json as _jsonimport math as _mathimport random as _randimport re as _refrom typing import Any, Dict, List, Optional
try: from language_core.codegen_contracts import ( DANGEROUS_ATTRIBUTES, DANGEROUS_CALLABLES, DANGEROUS_IMPORTS, DANGEROUS_SPECIAL_ATTRS, RESTRICTED_HOST_MODULES, )except ImportError: DANGEROUS_CALLABLES = {"eval", "exec", "compile", "__import__", "globals", "locals", "vars", "dir", "breakpoint"} DANGEROUS_SPECIAL_ATTRS = { "__builtins__", "__globals__", "__subclasses__", "__bases__", "__class__", "__dict__", "__code__", "__closure__", "__mro__", "__qualname__", } DANGEROUS_ATTRIBUTES = { ("os", "system"), ("os", "popen"), ("os", "spawn"), ("os", "spawnl"), ("subprocess", "Popen"), ("subprocess", "call"), ("subprocess", "run"), ("subprocess", "check_output"), ("subprocess", "check_call"), ("shutil", "rmtree"), ("posix", "system"), ("pty", "spawn"), } RESTRICTED_HOST_MODULES = { "os", "sys", "subprocess", "socket", "shutil", "importlib", "builtins", "ctypes", "pickle", "marshal", "pty", "pathlib", "posix", } DANGEROUS_IMPORTS = RESTRICTED_HOST_MODULES | { "sqlite3", "inspect", "multiprocessing", "threading", "asyncio", "webbrowser", "signal", }try: from language_core.executor.state_and_errors import WorkflowExecutionErrorexcept ImportError: class WorkflowExecutionError(Exception): # type: ignore[no-redef] def __init__(self, node_id: str, node_type: str, message: str, original_exception: Optional[Exception] = None): super().__init__(f"[{node_id}:{node_type}] {message}") self.node_id = node_id self.node_type = node_type self.message = message self.original_exception = original_exception
SAFE_BUILTINS: Dict[str, Any] = { "abs": abs, "all": all, "any": any, "ascii": ascii, "bin": bin, "bool": bool, "chr": chr, "complex": complex, "dict": dict, "divmod": divmod, "enumerate": enumerate, "filter": filter, "float": float, "format": format, "frozenset": frozenset, "hex": hex, "int": int, "isinstance": isinstance, "issubclass": issubclass, "iter": iter, "len": len, "list": list, "map": map, "max": max, "min": min, "next": next, "oct": oct, "ord": ord, "pow": pow, "print": lambda *args, **kw: None, "range": range, "repr": repr, "reversed": reversed, "round": round, "set": set, "slice": slice, "sorted": sorted, "str": str, "sum": sum, "tuple": tuple, "type": type, "zip": zip, "True": True, "False": False, "None": None,}
def inspect_script_ast_safety(code: str, node_id: str, label: str) -> None: """Statically parse and inspect script AST to block dangerous callables, imports, and attributes.""" try: tree = ast.parse(code) except SyntaxError as exc: raise WorkflowExecutionError( node_id=node_id, node_type="code.python", message=f"[ERR-SYNTAX] Custom Python script on '{label}' has syntax error: {exc.msg} (line {exc.lineno})", original_exception=exc, )
for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: root_pkg = alias.name.split(".")[0].lower() if root_pkg in DANGEROUS_IMPORTS or root_pkg in RESTRICTED_HOST_MODULES: raise WorkflowExecutionError( node_id=node_id, node_type="code.python", message=f"[ERR-SECURITY-UNSAFE-IMPORT] Importing restricted module '{alias.name}' is prohibited.", ) elif isinstance(node, ast.ImportFrom): mod = (node.module or "").split(".")[0].lower() if mod in DANGEROUS_IMPORTS or mod in RESTRICTED_HOST_MODULES: raise WorkflowExecutionError( node_id=node_id, node_type="code.python", message=f"[ERR-SECURITY-UNSAFE-IMPORT] Importing from restricted module '{node.module}' is prohibited.", ) elif isinstance(node, ast.Call): if isinstance(node.func, ast.Name) and node.func.id in DANGEROUS_CALLABLES: raise WorkflowExecutionError( node_id=node_id, node_type="code.python", message=f"[ERR-SECURITY-DANGEROUS-CALL] Call to dangerous function '{node.func.id}()' is prohibited.", ) elif isinstance(node, ast.Attribute): if node.attr in DANGEROUS_SPECIAL_ATTRS: raise WorkflowExecutionError( node_id=node_id, node_type="code.python", message=f"[ERR-SECURITY-FORBIDDEN-ATTR] Access to dunder attribute '{node.attr}' is prohibited.", ) if isinstance(node.value, ast.Name) and (node.value.id, node.attr) in DANGEROUS_ATTRIBUTES: raise WorkflowExecutionError( node_id=node_id, node_type="code.python", message=f"[ERR-SECURITY-DANGEROUS-ATTR] Access to '{node.value.id}.{node.attr}' is prohibited.", )
def execute_custom_script_node( node_inputs: Dict[str, Any], params: Dict[str, Any], node_id: str, label: str = "Custom Script",) -> Dict[str, Any]: """Execute allowlisted user script in sandboxed namespace with dynamic port binding.""" raw_code = params.get("code") or node_inputs.get("code") or params.get("script") or "" if not isinstance(raw_code, str) or not raw_code.strip(): return {"result": None, "out": None}
inspect_script_ast_safety(raw_code, node_id, label)
safe_globals: Dict[str, Any] = { "__builtins__": SAFE_BUILTINS, "math": _math, "random": _rand, "json": _json, "re": _re, "datetime": _dt, } local_scope: Dict[str, Any] = dict(node_inputs) local_scope["inputs"] = dict(node_inputs)
try: compiled = compile(raw_code, f"<custom_script_{node_id}>", "exec") exec(compiled, safe_globals, local_scope) except Exception as exc: raise WorkflowExecutionError( node_id=node_id, node_type="code.python", message=f"[ERR-SCRIPT-RUNTIME] Custom Python script on '{label}' failed at runtime: {exc}", original_exception=exc, )
# Check for entrypoint functions: run(...) or main(...) entrypoint_name = params.get("entrypoint") candidate_fns = [entrypoint_name] if entrypoint_name else ["run", "main"] fn = next((local_scope[name] for name in candidate_fns if callable(local_scope.get(name))), None)
if fn is not None: try: sig = inspect.signature(fn) matched_kwargs = {k: v for k, v in node_inputs.items() if k in sig.parameters} if not matched_kwargs and len(sig.parameters) == 1: p_name = next(iter(sig.parameters.keys())) first_val = next(iter(node_inputs.values()), None) res = fn(**{p_name: first_val}) else: res = fn(**matched_kwargs) except Exception as exc: raise WorkflowExecutionError( node_id=node_id, node_type="code.python", message=f"[ERR-ENTRYPOINT-EXECUTION] Error invoking entrypoint on '{label}': {exc}", original_exception=exc, ) elif "result" in local_scope: res = local_scope["result"] elif "out" in local_scope: res = local_scope["out"] else: res = next((v for k, v in local_scope.items() if k not in node_inputs and k != "inputs" and not k.startswith("_")), None)
if isinstance(res, dict): out_dict = dict(res) if "out" not in out_dict and "result" in out_dict: out_dict["out"] = out_dict["result"] if "result" not in out_dict and "out" in out_dict: out_dict["result"] = out_dict["out"] return out_dict
return {"result": res, "out": res}12 unmodified lines13141516171819202160 unmodified lines8283848586878893 unmodified lines18218318418518618742 unmodified lines23023123223323423523612 unmodified linesfrom urllib.parse import urlparsefrom language_core.executor.inline_handlers import (_execute_binary_op_node, _execute_compare_node, _execute_constant_node,_execute_if_else_node, _execute_loop_node, _execute_math_sqrt_node,_execute_print_node, _execute_variable_node,)from language_core.executor.legacy_cat_handlers import execute_legacy_cat_nodefrom language_core.executor.single_node_io import prepare_registry_params60 unmodified linesdef _exec_allowlisted_import(node_inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]:from library_inspector.safe_executor import exec_allowlisted_importreturn exec_allowlisted_import(node_inputs, params)93 unmodified linesif "rule" in ntype or "logic.rule" in ntype:from language_core.nodes.nodes_logic import _exec_logic_rulereturn _exec_logic_rule(node_inputs, params)if "module_input" in ntype or "module_output" in ntype:val = node_inputs.get("in_val") if "in_val" in node_inputs else node_inputs.get("in", params.get("value"))return {"out_val": val, "out": val, "result": val}42 unmodified linesreturn _exec_allowlisted_import(node_inputs, params)from library_inspector.safe_executor import exec_python_library_presetpreset_res = exec_python_library_preset(ntype, d, node_inputs, params)if preset_res is not None:return preset_res12 unmodified lines131415161718192060 unmodified lines81828384858693 unmodified lines18018118218318418518618718842 unmodified lines23123223323423523612 unmodified linesfrom urllib.parse import urlparsefrom language_core.executor.inline_handlers import (_execute_binary_op_node, _execute_compare_node, _execute_constant_node, _execute_if_else_node,_execute_loop_node, _execute_math_sqrt_node, _execute_print_node, _execute_variable_node,)from language_core.executor.legacy_cat_handlers import execute_legacy_cat_nodefrom language_core.executor.single_node_io import prepare_registry_params60 unmodified linesdef _exec_allowlisted_import(node_inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]:from library_inspector.safe_executor import exec_allowlisted_importreturn exec_allowlisted_import(node_inputs, params)93 unmodified linesif "rule" in ntype or "logic.rule" in ntype:from language_core.nodes.nodes_logic import _exec_logic_rulereturn _exec_logic_rule(node_inputs, params)if "script" in ntype or ntype in ("code.python", "custom.python") or "code.python" in ntype:from language_core.executor.custom_script_executor import execute_custom_script_nodereturn execute_custom_script_node(node_inputs, params, node_id, label)if "module_input" in ntype or "module_output" in ntype:val = node_inputs.get("in_val") if "in_val" in node_inputs else node_inputs.get("in", params.get("value"))return {"out_val": val, "out": val, "result": val}42 unmodified linesreturn _exec_allowlisted_import(node_inputs, params)from library_inspector.safe_executor import exec_python_library_presetpreset_res = exec_python_library_preset(ntype, d, node_inputs, params)if preset_res is not None:return preset_res
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""Unit tests for custom script sandbox executor (Task 3).Verifies AST static safety inspection, allowlisted execution, entrypoints, and error handling."""
import sysimport unittestfrom pathlib import Path
# Add backend directory to sys.pathbackend_dir = Path(__file__).resolve().parent.parentif str(backend_dir) not in sys.path: sys.path.insert(0, str(backend_dir))
from language_core.executor.custom_script_executor import ( WorkflowExecutionError, execute_custom_script_node,)
class TestCustomScriptExecutor(unittest.TestCase):
def test_basic_expression_execution(self): res = execute_custom_script_node( node_inputs={"x": 21}, params={"code": "result = x * 2"}, node_id="node_custom_1", label="Multiplier", ) self.assertEqual(res["result"], 42) self.assertEqual(res["out"], 42)
def test_entrypoint_function_execution(self): code = """def run(a, b): return {"sum": a + b, "diff": a - b}""" res = execute_custom_script_node( node_inputs={"a": 10, "b": 3}, params={"code": code}, node_id="node_custom_2", label="Adder", ) self.assertEqual(res["sum"], 13) self.assertEqual(res["diff"], 7)
def test_blocks_os_import(self): with self.assertRaises(WorkflowExecutionError) as ctx: execute_custom_script_node( node_inputs={}, params={"code": "import os\nos.system('ls')"}, node_id="node_bad_1", ) self.assertIn("[ERR-SECURITY-UNSAFE-IMPORT]", str(ctx.exception))
def test_blocks_eval_call(self): with self.assertRaises(WorkflowExecutionError) as ctx: execute_custom_script_node( node_inputs={}, params={"code": "result = eval('1 + 1')"}, node_id="node_bad_2", ) self.assertIn("[ERR-SECURITY-DANGEROUS-CALL]", str(ctx.exception))
def test_blocks_dunder_inspection(self): with self.assertRaises(WorkflowExecutionError) as ctx: execute_custom_script_node( node_inputs={}, params={"code": "x = ().__class__.__bases__"}, node_id="node_bad_3", ) self.assertIn("[ERR-SECURITY-FORBIDDEN-ATTR]", str(ctx.exception))
def test_syntax_error_reported(self): with self.assertRaises(WorkflowExecutionError) as ctx: execute_custom_script_node( node_inputs={}, params={"code": "def broken(:"}, node_id="node_bad_4", ) self.assertIn("[ERR-SYNTAX]", str(ctx.exception))
if __name__ == "__main__": unittest.main()language_core/core_nodes_generated.py
language_core/executor/custom_script_executor.pyAdded+192
language_core/executor/node_dispatch.py+5-5
tests/test_custom_script_executor.pyAdded+85