|
| 1 | +import unittest |
| 2 | +from src.tools.executor.local_python_executor import evaluate_python_code, InterpreterError, BASE_PYTHON_TOOLS, BASE_BUILTIN_MODULES, DEFAULT_MAX_LEN_OUTPUT |
| 3 | + |
| 4 | +# It's good practice to define a small, fixed list for default authorized_imports in tests |
| 5 | +# unless a test specifically needs to modify it. |
| 6 | +TEST_DEFAULT_AUTHORIZED_IMPORTS = ["math"] # Example, can be empty if preferred for stricter tests |
| 7 | + |
| 8 | +class TestPythonInterpreterSandbox(unittest.TestCase): |
| 9 | + |
| 10 | + def setUp(self): |
| 11 | + # These are defaults for the tools/state available during evaluation. |
| 12 | + # Tests can override state or custom_tools if needed. |
| 13 | + self.static_tools = BASE_PYTHON_TOOLS.copy() |
| 14 | + self.custom_tools = {} |
| 15 | + # self.state is not defined here, as evaluate_python_code takes state as an argument |
| 16 | + # and it's better to pass a fresh state for each test call to avoid interference. |
| 17 | + |
| 18 | + def _evaluate(self, code, authorized_imports=None, state=None): |
| 19 | + if authorized_imports is None: |
| 20 | + authorized_imports = list(TEST_DEFAULT_AUTHORIZED_IMPORTS) # Use a copy |
| 21 | + |
| 22 | + current_state = state if state is not None else {} |
| 23 | + |
| 24 | + # evaluate_python_code returns (result, is_final_answer) |
| 25 | + return evaluate_python_code( |
| 26 | + code, |
| 27 | + static_tools=self.static_tools, |
| 28 | + custom_tools=self.custom_tools, # Pass along self.custom_tools |
| 29 | + state=current_state, # Pass along current_state |
| 30 | + authorized_imports=authorized_imports, |
| 31 | + max_print_outputs_length=DEFAULT_MAX_LEN_OUTPUT |
| 32 | + ) |
| 33 | + |
| 34 | + # === Import Tests === |
| 35 | + def test_import_disallowed_module_direct(self): |
| 36 | + with self.assertRaisesRegex(InterpreterError, "Import of os is not allowed"): |
| 37 | + self._evaluate("import os", authorized_imports=[]) |
| 38 | + |
| 39 | + def test_import_disallowed_module_from(self): |
| 40 | + with self.assertRaisesRegex(InterpreterError, "Import from os is not allowed"): |
| 41 | + self._evaluate("from os import path", authorized_imports=[]) |
| 42 | + |
| 43 | + def test_import_allowed_module(self): |
| 44 | + result, _ = self._evaluate("import math; x = math.sqrt(4)", authorized_imports=["math"]) |
| 45 | + self.assertEqual(result, 2.0) |
| 46 | + |
| 47 | + def test_import_submodule_allowed_implicitly(self): |
| 48 | + # If 'collections' is allowed, 'collections.abc' should be usable via attribute access. |
| 49 | + # The get_safe_module ensures submodules are also checked if they were explicitly imported. |
| 50 | + # This test checks if 'collections.abc' can be accessed if 'collections' is authorized. |
| 51 | + # The updated get_safe_module will try to check 'collections.abc' when 'collections' is processed. |
| 52 | + # So, 'collections.abc' must also be in authorized_imports or match a wildcard like 'collections.*' |
| 53 | + # For this test, let's authorize both specifically. |
| 54 | + result, _ = self._evaluate("import collections; c = collections.abc.Callable", authorized_imports=["collections", "collections.abc"]) |
| 55 | + # Check that 'c' is indeed the Callable type from collections.abc |
| 56 | + import collections.abc as abc_module |
| 57 | + self.assertIs(result, abc_module.Callable) |
| 58 | + |
| 59 | + |
| 60 | + def test_import_only_specific_submodule_denies_parent_access(self): |
| 61 | + # Allow "os.path" but try to use "os.listdir()" -> should fail on "os" not being fully allowed for that. |
| 62 | + # This tests the precision of check_import_authorized. |
| 63 | + # If only "os.path" is authorized, "import os" should fail. |
| 64 | + with self.assertRaisesRegex(InterpreterError, "Import of os is not allowed"): |
| 65 | + self._evaluate("import os; os.listdir('.')", authorized_imports=["os.path"]) |
| 66 | + |
| 67 | + def test_import_authorized_submodule_directly(self): |
| 68 | + result, _ = self._evaluate("import os.path; x = os.path.basename('/a/b')", authorized_imports=["os.path"]) |
| 69 | + self.assertEqual(result, "b") |
| 70 | + |
| 71 | + def test_import_from_authorized_submodule(self): |
| 72 | + result, _ = self._evaluate("from os.path import basename; x = basename('/a/b')", authorized_imports=["os.path"]) |
| 73 | + self.assertEqual(result, "b") |
| 74 | + |
| 75 | + # === Dangerous Function Call Tests === |
| 76 | + def test_call_dangerous_builtin_function_eval(self): |
| 77 | + with self.assertRaisesRegex(InterpreterError, "Forbidden access to function: eval"): |
| 78 | + self._evaluate("eval('1+1')") |
| 79 | + |
| 80 | + def test_call_dangerous_builtin_function_exec(self): |
| 81 | + with self.assertRaisesRegex(InterpreterError, "Forbidden access to function: exec"): |
| 82 | + self._evaluate("exec('a=1')") |
| 83 | + |
| 84 | + def test_call_dangerous_os_function_system_via_import(self): |
| 85 | + # This relies on 'os' module itself being blocked from import. |
| 86 | + with self.assertRaisesRegex(InterpreterError, "Import of os is not allowed"): |
| 87 | + self._evaluate("import os; os.system('echo hello')") |
| 88 | + |
| 89 | + def test_call_dangerous_function_if_module_was_somehow_allowed(self): |
| 90 | + # If 'os' was authorized, safer_eval should still block 'os.system' if it's in DANGEROUS_FUNCTIONS |
| 91 | + # This tests the defense in depth of safer_eval. |
| 92 | + with self.assertRaisesRegex(InterpreterError, "Forbidden access to function: system"): |
| 93 | + self._evaluate("import os; os.system('echo hello')", authorized_imports=["os"]) |
| 94 | + |
| 95 | + |
| 96 | + def test_call_allowed_builtin_function(self): |
| 97 | + result, _ = self._evaluate("len([1,2,3])") |
| 98 | + self.assertEqual(result, 3) |
| 99 | + |
| 100 | + def test_call_function_returned_by_tool_if_dangerous(self): |
| 101 | + # Mocking state to contain a dangerous function |
| 102 | + current_state = {"my_dangerous_func": eval} |
| 103 | + with self.assertRaisesRegex(InterpreterError, "Forbidden access to function: eval"): |
| 104 | + self._evaluate("my_dangerous_func('1+1')", state=current_state, authorized_imports=[]) |
| 105 | + |
| 106 | + |
| 107 | + # === Dunder Attribute Access Tests === |
| 108 | + def test_access_disallowed_dunder_directly_on_dict(self): |
| 109 | + with self.assertRaisesRegex(InterpreterError, "Forbidden access to dunder attribute: __dict__"): |
| 110 | + self._evaluate("x = {}; x.__dict__") |
| 111 | + |
| 112 | + def test_access_disallowed_dunder_directly_on_module(self): |
| 113 | + # math.__loader__ is an example. |
| 114 | + with self.assertRaisesRegex(InterpreterError, "Forbidden access to dunder attribute: __loader__"): |
| 115 | + self._evaluate("import math; math.__loader__", authorized_imports=["math"]) |
| 116 | + |
| 117 | + |
| 118 | + def test_access_disallowed_dunder_via_getattr(self): |
| 119 | + # getattr is nodunder_getattr in BASE_PYTHON_TOOLS |
| 120 | + with self.assertRaisesRegex(InterpreterError, "Forbidden access to dunder attribute: __subclasses__"): |
| 121 | + self._evaluate("x = type(0); getattr(x, '__subclasses__')") |
| 122 | + |
| 123 | + def test_allowed_dunder_method_indirectly_len(self): |
| 124 | + result, _ = self._evaluate("x = [1,2]; len(x)") |
| 125 | + self.assertEqual(result, 2) |
| 126 | + |
| 127 | + def test_allowed_dunder_method_indirectly_getitem(self): |
| 128 | + result, _ = self._evaluate("x = [10,20]; x[1]") |
| 129 | + self.assertEqual(result, 20) |
| 130 | + |
| 131 | + # === AST Node Behavior Tests === |
| 132 | + def test_assign_to_static_tool_name_blocked(self): |
| 133 | + with self.assertRaisesRegex(InterpreterError, "Cannot assign to name 'len'"): |
| 134 | + self._evaluate("len = lambda x: x") |
| 135 | + |
| 136 | + def test_lambda_executes_in_sandbox_blocks_import(self): |
| 137 | + with self.assertRaisesRegex(InterpreterError, "Import of sys is not allowed"): |
| 138 | + self._evaluate("f = lambda: __import__('sys'); f()", authorized_imports=[]) |
| 139 | + |
| 140 | + def test_def_function_executes_in_sandbox_blocks_import(self): |
| 141 | + code = """ |
| 142 | +def my_func(): |
| 143 | + import shutil # Disallowed |
| 144 | + return shutil.disk_usage('.') |
| 145 | +my_func() |
| 146 | +""" |
| 147 | + with self.assertRaisesRegex(InterpreterError, "Import of shutil is not allowed"): |
| 148 | + self._evaluate(code, authorized_imports=[]) |
| 149 | + |
| 150 | + def test_class_def_executes_in_sandbox_blocks_import_in_init(self): |
| 151 | + code = """ |
| 152 | +class MyClass: |
| 153 | + def __init__(self): |
| 154 | + import subprocess # Disallowed |
| 155 | + self.name = subprocess.call('echo') |
| 156 | + def get_name(self): |
| 157 | + return self.name |
| 158 | +x = MyClass() |
| 159 | +x.get_name() |
| 160 | +""" |
| 161 | + with self.assertRaisesRegex(InterpreterError, "Import of subprocess is not allowed"): |
| 162 | + self._evaluate(code, authorized_imports=[]) |
| 163 | + |
| 164 | + def test_class_def_executes_in_sandbox_blocks_import_in_method(self): |
| 165 | + code = """ |
| 166 | +class MyClassMethod: |
| 167 | + def do_bad_stuff(self): |
| 168 | + import _thread # Disallowed |
| 169 | + return _thread.get_ident() |
| 170 | +x = MyClassMethod() |
| 171 | +x.do_bad_stuff() |
| 172 | +""" |
| 173 | + with self.assertRaisesRegex(InterpreterError, "Import of _thread is not allowed"): |
| 174 | + self._evaluate(code, authorized_imports=[]) |
| 175 | + |
| 176 | + def test_unsupported_ast_node_global_keyword(self): |
| 177 | + code = """ |
| 178 | +x = 0 |
| 179 | +def f(): |
| 180 | + global x # ast.Global node |
| 181 | + x = 1 |
| 182 | +""" |
| 183 | + with self.assertRaisesRegex(InterpreterError, "Global is not supported"): |
| 184 | + self._evaluate(code) |
| 185 | + |
| 186 | + def test_unsupported_ast_node_nonlocal_keyword(self): |
| 187 | + code = """ |
| 188 | +def f(): |
| 189 | + x = 1 |
| 190 | + def g(): |
| 191 | + nonlocal x # ast.Nonlocal node |
| 192 | + x = 2 |
| 193 | + g() |
| 194 | +""" |
| 195 | + with self.assertRaisesRegex(InterpreterError, "Nonlocal is not supported"): |
| 196 | + self._evaluate(code) |
| 197 | + |
| 198 | + def test_comprehension_sandbox_import(self): |
| 199 | + with self.assertRaisesRegex(InterpreterError, "Import of os is not allowed"): |
| 200 | + self._evaluate("[__import__('os') for i in range(1)]", authorized_imports=[]) |
| 201 | + |
| 202 | + def test_try_except_sandbox_import(self): |
| 203 | + code = """ |
| 204 | +try: |
| 205 | + x = 1 |
| 206 | +except Exception: |
| 207 | + import os |
| 208 | +else: |
| 209 | + import sys |
| 210 | +finally: |
| 211 | + import subprocess |
| 212 | +""" |
| 213 | + # The first import attempt (os) should be caught. |
| 214 | + with self.assertRaisesRegex(InterpreterError, "Import of os is not allowed"): |
| 215 | + self._evaluate(code, authorized_imports=[]) |
| 216 | + |
| 217 | + |
| 218 | +if __name__ == "__main__": |
| 219 | + unittest.main() |
0 commit comments