"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(sandbox): close the by-name, by-graph and by-pathlib routes out of the sandbox
Haozhe Wu6c44732818ea
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.pyindex 371d01da0..a24894803 100644--- a/agent/backtest/runner.py+++ b/agent/backtest/runner.py@@ -288,9 +288,20 @@ def _validate_class_body(node: ast.ClassDef) -> None:# imports file-wide would reject strategies generated from ~12 shipped skills, so# we block the dangerous *use* along the executed path instead of a harmless# unused top-level import. Direct ``getattr``/``setattr``/``delattr`` indirection-# onto ``os`` / forbidden modules is now rejected (see _reject_forbidden_getattr);-# exotic reach via ``builtins.getattr`` or aliasing remains a documented residual-# (VT-001) — this is defense-in-depth, not a kernel-level guarantee.+# onto ``os`` / forbidden modules is now rejected (see _reject_forbidden_getattr),+# and a renamed binding no longer hides the root (see+# _module_level_forbidden_aliases). This is defense-in-depth, not a kernel-level+# guarantee: an AST denylist cannot be complete.+#+# MEASURED RESIDUAL, so it is not left implied. After the lists below, these+# still reach the executed path: ``inspect``, ``operator``, ``threading``,+# ``codeop``, ``tempfile``, and ``os.makedirs``. None of them reaches a broker+# on its own — ``inspect``/``operator`` need an object you already hold,+# ``threading`` runs code that is still in this file and gets scanned if it is+# reachable, ``codeop`` yields a code object that needs the already-blocked+# ``eval``/``exec`` to run, and the last two are filesystem, not the red line.+# They are named here so the next person extends this list from evidence rather+# than from a fresh survey._FORBIDDEN_IMPORT_MODULES = frozenset({"socket",@@ -308,6 +319,31 @@ _FORBIDDEN_IMPORT_MODULES = frozenset("telnetlib","multiprocessing","ctypes",+ # Modules that resolve or execute a module BY NAME. Blocking the+ # ``src.trading`` prefix is worth nothing while any of these can fetch+ # the same module from a string, and every one of them was measured+ # ACCEPTED against the live scanner:+ # importlib.import_module("src.trading.service")+ # builtins.__import__("src.trading.service")+ # sys.modules["src.trading.service"]+ # pkgutil.resolve_name("src.trading.service:place_order")+ # runpy.run_module("src.trading.service")+ # ``pickle``/``marshal`` belong here for the same reason: a crafted+ # payload imports and calls through ``__reduce__`` without naming the+ # module in the source at all. None has a use in a signal engine, which+ # receives a data_map and returns signals.+ "importlib",+ "builtins",+ "sys",+ "pkgutil",+ "runpy",+ "pickle",+ "marshal",+ # Process spawn and filesystem reach, alongside the subprocess entry+ # already above.+ "shutil",+ "webbrowser",+ "gc",})# Project-internal subtrees that reach a broker. The red line is that no@@ -364,6 +400,51 @@ _FORBIDDEN_OS_ATTRS = frozenset("environ","environb","startfile",+ # Filesystem mutation, alongside the open()/pathlib write guards. A+ # signal engine returns signals; deleting or renaming files is not part+ # of that contract, and os.remove was measured ACCEPTED.+ "remove",+ "unlink",+ "rmdir",+ "removedirs",+ "rename",+ "renames",+ "replace",+ "truncate",+ "chmod",+ "chown",+ "symlink",+ "link",+ }+)+# The object graph is the last structural route to a module the import checks+# refuse: ``().__class__.__mro__[1].__subclasses__()`` reaches every loaded+# class without naming one, and ``(lambda: 0).__globals__['__builtins__']``+# hands back the builtins mapping that ``_FORBIDDEN_BUILTINS`` exists to gate.+# Both were measured ACCEPTED.+#+# Only the traversal attributes are listed, not every dunder: a signal engine+# has no reason to walk ``__mro__`` or read ``__globals__``, but banning dunders+# wholesale would reject ordinary code. This does not make the sandbox complete+# — see the residual note on _FORBIDDEN_IMPORT_MODULES.+_FORBIDDEN_DUNDER_ATTRS = frozenset(+ {+ "__class__",+ "__bases__",+ "__base__",+ "__mro__",+ "__subclasses__",+ "__globals__",+ "__builtins__",+ "__code__",+ "__closure__",+ "__func__",+ "__self__",+ "__reduce__",+ "__reduce_ex__",+ "__getattribute__",+ "__init_subclass__",+ "__subclasshook__",})_FORBIDDEN_BUILTINS = frozenset(@@ -448,6 +529,50 @@ def _reject_forbidden_open(node: ast.Call) -> None:raise ValueError(f"open() with a non-relative path {path!r} {_SCRUB_MSG}")+def _reject_forbidden_pathlib_write(node: ast.Call) -> None:+ """Reject the pathlib spellings of a file write that ``open()`` already bars.++ ``_reject_forbidden_open`` refuses ``open(path, "w")``, but the identical+ write reaches disk through ``Path(p).write_text()``, ``.write_bytes()`` and+ ``Path(p).open("w")``, none of which that check can see — it only matches a+ bare ``open`` or ``io``/``os.open``. The guard therefore did not do the one+ thing it says it does. Measured against the live scanner,+ ``Path('/tmp/x').write_text('x')`` was ACCEPTED.++ Matching is on the method name rather than on proving the receiver is a+ ``Path``: the receiver is usually a call expression, and a signal engine+ that defines its own ``write_text`` is not a pattern worth preserving. A+ strategy is handed a data_map and returns signals; it writes nothing.++ Args:+ node: Call node on the executed path.++ Raises:+ ValueError: If the call writes to the filesystem.+ """+ func = node.func+ if not isinstance(func, ast.Attribute):+ return+ if func.attr in {"write_text", "write_bytes"}:+ raise ValueError(f"Writing files via .{func.attr}() {_SCRUB_MSG}")+ if func.attr != "open":+ return+ if isinstance(func.value, ast.Name) and func.value.id in {"io", "os"}:+ return # module-level open(path, mode) — _reject_forbidden_open owns it+ # A BOUND ``.open()`` takes the mode first: the receiver is not an argument,+ # so the index is 0 here where the module-level form uses 1.+ mode_node: ast.AST | None = node.args[0] if node.args else None+ for kw in node.keywords:+ if kw.arg == "mode":+ mode_node = kw.value+ if mode_node is None:+ return+ if not (isinstance(mode_node, ast.Constant) and isinstance(mode_node.value, str)):+ raise ValueError(f".open() with a non-literal mode {_SCRUB_MSG}")+ if any(ch in _OPEN_WRITE_MODE_CHARS for ch in mode_node.value):+ raise ValueError(f"Writing files via .open(mode={mode_node.value!r}) {_SCRUB_MSG}")++def _reject_forbidden_getattr(node: ast.Call) -> None:"""Reject getattr/setattr/delattr indirection onto ``os`` / forbidden modules.@@ -504,11 +629,14 @@ def _reject_forbidden_node(node: ast.AST) -> None:raise ValueError(f"Use of {dotted} {_SCRUB_MSG}")if root == "os" and _is_forbidden_os_attr(node.attr):raise ValueError(f"Use of os.{node.attr} {_SCRUB_MSG}")+ if node.attr in _FORBIDDEN_DUNDER_ATTRS:+ raise ValueError(f"Object-graph traversal via .{node.attr} {_SCRUB_MSG}")elif isinstance(node, ast.Name):if node.id in _FORBIDDEN_BUILTINS:raise ValueError(f"Use of {node.id!r} {_SCRUB_MSG}")elif isinstance(node, ast.Call):_reject_forbidden_open(node)+ _reject_forbidden_pathlib_write(node)_reject_forbidden_getattr(node)diff --git a/agent/tests/test_backtest_runner_security.py b/agent/tests/test_backtest_runner_security.pyindex 2ecd96691..a88479ebe 100644--- a/agent/tests/test_backtest_runner_security.py+++ b/agent/tests/test_backtest_runner_security.py@@ -299,6 +299,224 @@ def test_signal_engine_alias_check_leaves_legitimate_imports_alone(_load_module_from_file(signal_file, _module_name())+# Blocking the ``src.trading`` prefix buys nothing while a module can be fetched+# by NAME instead of named in an import statement. Every case below was measured+# ACCEPTED against the live scanner before this list existed — the red line was+# one string away from being reachable in each of them.+_DYNAMIC_MODULE_REACH = [+ ("importlib_import_module", "import importlib", " return importlib.import_module('src.trading.service')"),+ ("importlib_alias", "import importlib as il", " return il.import_module('src.trading.service')"),+ (+ "importlib_from_alias",+ "from importlib import import_module as imp",+ " return imp('src.trading.service')",+ ),+ ("importlib_util", "import importlib.util", " return importlib.util.spec_from_file_location('x', 'y.py')"),+ (+ "importlib_inside_method",+ "import pandas as pd",+ " import importlib\n return importlib.import_module('src.trading.service')",+ ),+ ("builtins_dunder_import", "import builtins", " return builtins.__import__('src.trading.service')"),+ ("builtins_eval", "import builtins", " return builtins.eval('1+1')"),+ ("builtins_alias", "import builtins as b", " return b.__import__('src.trading.service')"),+ (+ "builtins_from_alias",+ "from builtins import __import__ as bi",+ " return bi('src.trading.service')",+ ),+ ("sys_modules", "import sys", " return sys.modules['src.trading.service']"),+ ("sys_path_injection", "import sys", " sys.path.insert(0, '/tmp/evil')\n return []"),+ ("pkgutil_resolve_name", "import pkgutil", " return pkgutil.resolve_name('src.trading.service:place_order')"),+ ("runpy_run_module", "import runpy", " return runpy.run_module('src.trading.service')"),+ # pickle/marshal never name the module in the source at all.+ ("pickle_loads", "import pickle", " return pickle.loads(b'payload')"),+ ("marshal_loads", "import marshal", " return marshal.loads(b'payload')"),+ ("shutil_copy", "import shutil", " return shutil.copy('/etc/passwd', '/tmp/x')"),+ ("webbrowser_open", "import webbrowser", " return webbrowser.open('http://x')"),+ ("gc_get_objects", "import gc", " return gc.get_objects()"),+]+++ "case_id,import_line,body",+ _DYNAMIC_MODULE_REACH,+ ids=[c[0] for c in _DYNAMIC_MODULE_REACH],+)+def test_signal_engine_rejects_module_reached_by_name(+ tmp_path, case_id, import_line, body,+) -> None:+ signal_file = tmp_path / "signal_engine.py"+ signal_file.write_text(+ "\n".join(+ [+ '"""Generated signal engine."""',+ import_line,+ "class SignalEngine:",+ " def generate(self, *args, **kwargs):",+ body,+ ]+ ),+ encoding="utf-8",+ )++ with pytest.raises(ValueError, match="not allowed inside generated strategy code"):+ _load_module_from_file(signal_file, _module_name())+++# ``open(path, "w")`` is refused, but the same write reached disk through the+# pathlib spellings, which the bare-open check cannot see. Measured ACCEPTED+# before this guard.+_PATHLIB_WRITES = [+ ("write_text", " Path('evil.txt').write_text('x')\n return []"),+ ("write_bytes", " Path('evil.bin').write_bytes(b'x')\n return []"),+ ("open_positional_mode", " Path('evil.txt').open('w')\n return []"),+ ("open_append_mode", " Path('evil.txt').open('a+')\n return []"),+ ("open_keyword_mode", " Path('evil.txt').open(mode='w')\n return []"),+]++[email protected]("case_id,body", _PATHLIB_WRITES, ids=[c[0] for c in _PATHLIB_WRITES])+def test_signal_engine_rejects_pathlib_file_writes(tmp_path, case_id, body) -> None:+ signal_file = tmp_path / "signal_engine.py"+ signal_file.write_text(+ "\n".join(+ [+ '"""Generated signal engine."""',+ "from pathlib import Path",+ "class SignalEngine:",+ " def generate(self, *args, **kwargs):",+ body,+ ]+ ),+ encoding="utf-8",+ )++ with pytest.raises(ValueError, match="not allowed inside generated strategy code"):+ _load_module_from_file(signal_file, _module_name())+++ "body",+ [+ # Reading a relative file is what a strategy legitimately does.+ " fh = Path('data.csv').open()\n return []",+ " fh = Path('data.csv').open('r')\n return []",+ " return [] if Path('data.csv').exists() else []",+ ],+ ids=["open_no_mode", "open_read_mode", "exists"],+)+def test_pathlib_write_guard_leaves_reads_alone(tmp_path, body) -> None:+ """The write guard must not cost a strategy its read path."""+ signal_file = tmp_path / "signal_engine.py"+ signal_file.write_text(+ "\n".join(+ [+ '"""Generated signal engine."""',+ "from pathlib import Path",+ "class SignalEngine:",+ " def generate(self, *args, **kwargs):",+ body,+ ]+ ),+ encoding="utf-8",+ )++ _load_module_from_file(signal_file, _module_name())+++# The object graph is the last structural route to a module the import checks+# refuse: it reaches every loaded class without naming one. Both were measured+# ACCEPTED before _FORBIDDEN_DUNDER_ATTRS existed.+_OBJECT_GRAPH_REACH = [+ ("mro_subclasses", " return ().__class__.__mro__[1].__subclasses__()"),+ ("globals_builtins", " return (lambda: 0).__globals__['__builtins__']"),+ ("class_base", " return data_map.__class__.__base__"),+ ("reduce", " return data_map.__reduce__()"),+ ("code_object", " return (lambda: 0).__code__"),+]++[email protected]("case_id,body", _OBJECT_GRAPH_REACH, ids=[c[0] for c in _OBJECT_GRAPH_REACH])+def test_signal_engine_rejects_object_graph_traversal(tmp_path, case_id, body) -> None:+ signal_file = tmp_path / "signal_engine.py"+ signal_file.write_text(+ "\n".join(+ [+ '"""Generated signal engine."""',+ "class SignalEngine:",+ " def generate(self, *args, **kwargs):",+ body,+ ]+ ),+ encoding="utf-8",+ )++ with pytest.raises(ValueError, match="not allowed inside generated strategy code"):+ _load_module_from_file(signal_file, _module_name())+++_OS_FILESYSTEM_MUTATION = [+ ("remove", " os.remove('x')\n return []"),+ ("unlink", " os.unlink('x')\n return []"),+ ("rename", " os.rename('a', 'b')\n return []"),+ ("chmod", " os.chmod('a', 511)\n return []"),+]+++ "case_id,body", _OS_FILESYSTEM_MUTATION, ids=[c[0] for c in _OS_FILESYSTEM_MUTATION]+)+def test_signal_engine_rejects_os_filesystem_mutation(tmp_path, case_id, body) -> None:+ signal_file = tmp_path / "signal_engine.py"+ signal_file.write_text(+ "\n".join(+ [+ '"""Generated signal engine."""',+ "import os",+ "class SignalEngine:",+ " def generate(self, *args, **kwargs):",+ body,+ ]+ ),+ encoding="utf-8",+ )++ with pytest.raises(ValueError, match="not allowed inside generated strategy code"):+ _load_module_from_file(signal_file, _module_name())+++ "body",+ [+ # Ordinary strategy code must survive all of the guards above.+ " return data_map['X'].close.rolling(20).mean()",+ " return data_map['X'].open.iloc[-1] + data_map['X'].high.max()",+ " return os.path.join('a', 'b')",+ " return self.lookback if hasattr(self, 'lookback') else 20",+ ],+ ids=["rolling_mean", "ohlc_columns", "os_path_join", "self_attr"],+)+def test_hardening_leaves_ordinary_strategy_code_alone(tmp_path, body) -> None:+ signal_file = tmp_path / "signal_engine.py"+ signal_file.write_text(+ "\n".join(+ [+ '"""Generated signal engine."""',+ "import os",+ "import pandas as pd",+ "class SignalEngine:",+ " lookback = 20",+ " def generate(self, *args, **kwargs):",+ body,+ ]+ ),+ encoding="utf-8",+ )++ _load_module_from_file(signal_file, _module_name())++def test_signal_engine_rejects_forbidden_op_in_transitively_called_helper(tmp_path) -> None:# Payload hidden in a module-level helper that generate() calls — the# reachability walk must follow the call and reject it.