codeshield-runtime 0.1.2__py3-none-any.whl → 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codeshield/__init__.py +48 -17
- codeshield/analyzer.py +286 -20
- codeshield/classifier.py +7 -2
- codeshield/cli.py +24 -6
- codeshield/environment.py +80 -10
- codeshield/loop.py +55 -30
- codeshield/runner.py +195 -40
- codeshield/schemas.py +215 -120
- codeshield/tools.py +31 -10
- {codeshield_runtime-0.1.2.dist-info → codeshield_runtime-0.2.0.dist-info}/METADATA +105 -29
- codeshield_runtime-0.2.0.dist-info/RECORD +15 -0
- {codeshield_runtime-0.1.2.dist-info → codeshield_runtime-0.2.0.dist-info}/WHEEL +1 -1
- codeshield_runtime-0.2.0.dist-info/entry_points.txt +2 -0
- {codeshield_runtime-0.1.2.dist-info → codeshield_runtime-0.2.0.dist-info}/licenses/LICENSE +1 -1
- codeshield_runtime-0.1.2.dist-info/RECORD +0 -14
codeshield/__init__.py
CHANGED
|
@@ -1,17 +1,48 @@
|
|
|
1
|
-
"""CodeShield.
|
|
2
|
-
|
|
3
|
-
A secure, isolated, and self-healing Python code execution engine.
|
|
4
|
-
"""
|
|
5
|
-
|
|
6
|
-
__version__ = "0.
|
|
7
|
-
|
|
8
|
-
from codeshield.
|
|
9
|
-
from codeshield.
|
|
10
|
-
from codeshield.
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
1
|
+
"""CodeShield.
|
|
2
|
+
|
|
3
|
+
A secure, isolated, and self-healing Python code execution engine.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
__version__ = "0.2.0"
|
|
7
|
+
|
|
8
|
+
from codeshield.analyzer import validate_syntax_and_safety
|
|
9
|
+
from codeshield.classifier import TracebackClassifier
|
|
10
|
+
from codeshield.environment import SandboxError, SandboxManager
|
|
11
|
+
from codeshield.loop import (
|
|
12
|
+
DEFAULT_GEMINI_MODEL,
|
|
13
|
+
ASTSecurityError,
|
|
14
|
+
GeminiPatchGenerator,
|
|
15
|
+
LLMPatchError,
|
|
16
|
+
SelfHealingEngine,
|
|
17
|
+
SelfHealingError,
|
|
18
|
+
)
|
|
19
|
+
from codeshield.runner import SubprocessRunner, SubprocessRunnerError
|
|
20
|
+
from codeshield.schemas import (
|
|
21
|
+
CodeExecutionRequest,
|
|
22
|
+
ErrorDiagnosis,
|
|
23
|
+
ExecutionResult,
|
|
24
|
+
PatchProposal,
|
|
25
|
+
ValidationReport,
|
|
26
|
+
)
|
|
27
|
+
from codeshield.tools import create_code_execution_tool
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"ASTSecurityError",
|
|
31
|
+
"CodeExecutionRequest",
|
|
32
|
+
"DEFAULT_GEMINI_MODEL",
|
|
33
|
+
"ErrorDiagnosis",
|
|
34
|
+
"ExecutionResult",
|
|
35
|
+
"GeminiPatchGenerator",
|
|
36
|
+
"LLMPatchError",
|
|
37
|
+
"PatchProposal",
|
|
38
|
+
"SandboxError",
|
|
39
|
+
"SandboxManager",
|
|
40
|
+
"SelfHealingEngine",
|
|
41
|
+
"SelfHealingError",
|
|
42
|
+
"SubprocessRunner",
|
|
43
|
+
"SubprocessRunnerError",
|
|
44
|
+
"TracebackClassifier",
|
|
45
|
+
"ValidationReport",
|
|
46
|
+
"create_code_execution_tool",
|
|
47
|
+
"validate_syntax_and_safety",
|
|
48
|
+
]
|
codeshield/analyzer.py
CHANGED
|
@@ -16,11 +16,128 @@ _DANGEROUS_NAMES: frozenset[str] = frozenset({
|
|
|
16
16
|
"eval",
|
|
17
17
|
"exec",
|
|
18
18
|
"compile",
|
|
19
|
+
"__import__",
|
|
20
|
+
"breakpoint",
|
|
21
|
+
"globals",
|
|
22
|
+
"locals",
|
|
23
|
+
"vars",
|
|
24
|
+
"getattr",
|
|
25
|
+
"setattr",
|
|
26
|
+
"delattr",
|
|
19
27
|
"os.system",
|
|
20
28
|
"subprocess.call",
|
|
21
29
|
"subprocess.run",
|
|
22
30
|
"subprocess.Popen",
|
|
23
31
|
})
|
|
32
|
+
_BLOCKED_MODULES: frozenset[str] = frozenset({
|
|
33
|
+
"subprocess",
|
|
34
|
+
"_posixsubprocess",
|
|
35
|
+
"pty",
|
|
36
|
+
"commands",
|
|
37
|
+
"popen2",
|
|
38
|
+
"posix",
|
|
39
|
+
"nt",
|
|
40
|
+
"_winapi",
|
|
41
|
+
"ctypes",
|
|
42
|
+
"_ctypes",
|
|
43
|
+
"cffi",
|
|
44
|
+
"builtins",
|
|
45
|
+
"__builtin__",
|
|
46
|
+
"importlib",
|
|
47
|
+
"runpy",
|
|
48
|
+
"code",
|
|
49
|
+
"codeop",
|
|
50
|
+
"marshal",
|
|
51
|
+
"pickle",
|
|
52
|
+
"_pickle",
|
|
53
|
+
"shelve",
|
|
54
|
+
"shutil",
|
|
55
|
+
"signal",
|
|
56
|
+
"socket",
|
|
57
|
+
"multiprocessing",
|
|
58
|
+
"webbrowser",
|
|
59
|
+
"pdb",
|
|
60
|
+
"bdb",
|
|
61
|
+
})
|
|
62
|
+
_BLOCKED_OS_ATTRS: frozenset[str] = frozenset({
|
|
63
|
+
"system",
|
|
64
|
+
"popen",
|
|
65
|
+
"fork",
|
|
66
|
+
"forkpty",
|
|
67
|
+
"kill",
|
|
68
|
+
"killpg",
|
|
69
|
+
"execv",
|
|
70
|
+
"execl",
|
|
71
|
+
"execve",
|
|
72
|
+
"execvp",
|
|
73
|
+
"execvpe",
|
|
74
|
+
"execlp",
|
|
75
|
+
"execle",
|
|
76
|
+
"execlpe",
|
|
77
|
+
"spawnl",
|
|
78
|
+
"spawnle",
|
|
79
|
+
"spawnlp",
|
|
80
|
+
"spawnlpe",
|
|
81
|
+
"spawnv",
|
|
82
|
+
"spawnve",
|
|
83
|
+
"spawnvp",
|
|
84
|
+
"spawnvpe",
|
|
85
|
+
"posix_spawn",
|
|
86
|
+
"posix_spawnp",
|
|
87
|
+
"startfile",
|
|
88
|
+
"remove",
|
|
89
|
+
"unlink",
|
|
90
|
+
"rmdir",
|
|
91
|
+
"removedirs",
|
|
92
|
+
"rename",
|
|
93
|
+
"replace",
|
|
94
|
+
"chmod",
|
|
95
|
+
"chown",
|
|
96
|
+
"symlink",
|
|
97
|
+
"link",
|
|
98
|
+
"putenv",
|
|
99
|
+
"unsetenv",
|
|
100
|
+
"getenv",
|
|
101
|
+
"getenvb",
|
|
102
|
+
"environ",
|
|
103
|
+
"environb",
|
|
104
|
+
})
|
|
105
|
+
_BLOCKED_SYS_ATTRS: frozenset[str] = frozenset({
|
|
106
|
+
"modules",
|
|
107
|
+
"_getframe",
|
|
108
|
+
"settrace",
|
|
109
|
+
"setprofile",
|
|
110
|
+
"addaudithook",
|
|
111
|
+
})
|
|
112
|
+
_BLOCKED_BUILTINS: frozenset[str] = frozenset({
|
|
113
|
+
"eval",
|
|
114
|
+
"exec",
|
|
115
|
+
"compile",
|
|
116
|
+
"__import__",
|
|
117
|
+
"breakpoint",
|
|
118
|
+
"globals",
|
|
119
|
+
"locals",
|
|
120
|
+
"vars",
|
|
121
|
+
"getattr",
|
|
122
|
+
"setattr",
|
|
123
|
+
"delattr",
|
|
124
|
+
})
|
|
125
|
+
_BLOCKED_DUNDER_ATTRS: frozenset[str] = frozenset({
|
|
126
|
+
"__builtins__",
|
|
127
|
+
"__import__",
|
|
128
|
+
"__globals__",
|
|
129
|
+
"__locals__",
|
|
130
|
+
"__code__",
|
|
131
|
+
"__closure__",
|
|
132
|
+
"__subclasses__",
|
|
133
|
+
"__bases__",
|
|
134
|
+
"__mro__",
|
|
135
|
+
"__class__",
|
|
136
|
+
"__dict__",
|
|
137
|
+
"__getattribute__",
|
|
138
|
+
"__reduce__",
|
|
139
|
+
"__reduce_ex__",
|
|
140
|
+
})
|
|
24
141
|
_GENERIC_EXCEPTIONS: frozenset[str] = frozenset({"Exception", "BaseException"})
|
|
25
142
|
|
|
26
143
|
|
|
@@ -32,17 +149,99 @@ class _SafetyContext:
|
|
|
32
149
|
line_numbers: dict[int, str] = field(default_factory=dict)
|
|
33
150
|
|
|
34
151
|
def add_violation(self, message: str, *, line: int | None = None) -> None:
|
|
35
|
-
"""Append a violation with an optional source line hint."""
|
|
152
|
+
"""Append a unique violation with an optional source line hint."""
|
|
36
153
|
if line is not None:
|
|
37
154
|
message = f"Line {line}: {message}"
|
|
38
|
-
self.violations
|
|
155
|
+
if message not in self.violations:
|
|
156
|
+
self.violations.append(message)
|
|
39
157
|
|
|
40
158
|
|
|
41
159
|
class _SafetyVisitor(ast.NodeVisitor):
|
|
42
|
-
"""AST visitor that flags generic exception handlers and dangerous calls."""
|
|
160
|
+
"""AST visitor that flags generic exception handlers, unsafe imports and dangerous calls."""
|
|
43
161
|
|
|
44
162
|
def __init__(self, context: _SafetyContext) -> None:
|
|
45
163
|
self._context = context
|
|
164
|
+
self._module_aliases: dict[str, str] = {}
|
|
165
|
+
self._symbol_aliases: dict[str, str] = {}
|
|
166
|
+
self._call_func_ids: set[int] = set()
|
|
167
|
+
|
|
168
|
+
def visit_Import(self, node: ast.Import) -> None: # noqa: N802
|
|
169
|
+
"""Detect imports of blocked modules and record aliases."""
|
|
170
|
+
for alias in node.names:
|
|
171
|
+
root_mod = alias.name.split(".")[0]
|
|
172
|
+
if alias.name in _BLOCKED_MODULES or root_mod in _BLOCKED_MODULES:
|
|
173
|
+
self._context.add_violation(
|
|
174
|
+
f"Importing blocked module ``{alias.name}`` is not allowed",
|
|
175
|
+
line=node.lineno,
|
|
176
|
+
)
|
|
177
|
+
local_name = alias.asname or root_mod
|
|
178
|
+
mapped_target = alias.name if alias.asname else root_mod
|
|
179
|
+
self._module_aliases[local_name] = mapped_target
|
|
180
|
+
self.generic_visit(node)
|
|
181
|
+
|
|
182
|
+
def visit_ImportFrom(self, node: ast.ImportFrom) -> None: # noqa: N802
|
|
183
|
+
"""Detect unsafe ``from ... import ...`` statements and record aliases."""
|
|
184
|
+
mod = node.module or ""
|
|
185
|
+
root_mod = mod.split(".")[0]
|
|
186
|
+
if mod in _BLOCKED_MODULES or root_mod in _BLOCKED_MODULES:
|
|
187
|
+
self._context.add_violation(
|
|
188
|
+
f"Importing from blocked module ``{mod}`` is not allowed",
|
|
189
|
+
line=node.lineno,
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
for alias in node.names:
|
|
193
|
+
if alias.name == "*":
|
|
194
|
+
if root_mod in {"os", "sys", "builtins"} or root_mod in _BLOCKED_MODULES:
|
|
195
|
+
self._context.add_violation(
|
|
196
|
+
f"Wildcard import from ``{mod}`` is not allowed",
|
|
197
|
+
line=node.lineno,
|
|
198
|
+
)
|
|
199
|
+
continue
|
|
200
|
+
|
|
201
|
+
if root_mod == "os" and alias.name in _BLOCKED_OS_ATTRS:
|
|
202
|
+
self._context.add_violation(
|
|
203
|
+
f"Importing dangerous ``os.{alias.name}`` is not allowed",
|
|
204
|
+
line=node.lineno,
|
|
205
|
+
)
|
|
206
|
+
elif root_mod == "sys" and alias.name in _BLOCKED_SYS_ATTRS:
|
|
207
|
+
self._context.add_violation(
|
|
208
|
+
f"Importing restricted ``sys.{alias.name}`` is not allowed",
|
|
209
|
+
line=node.lineno,
|
|
210
|
+
)
|
|
211
|
+
elif mod in {"builtins", "__builtins__"} and alias.name in _BLOCKED_BUILTINS:
|
|
212
|
+
self._context.add_violation(
|
|
213
|
+
f"Importing dangerous builtin ``{alias.name}`` is not allowed",
|
|
214
|
+
line=node.lineno,
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
local_name = alias.asname or alias.name
|
|
218
|
+
self._symbol_aliases[local_name] = f"{mod}.{alias.name}" if mod else alias.name
|
|
219
|
+
|
|
220
|
+
self.generic_visit(node)
|
|
221
|
+
|
|
222
|
+
def visit_Assign(self, node: ast.Assign) -> None: # noqa: N802
|
|
223
|
+
"""Track simple variable aliasing of dangerous symbols or modules."""
|
|
224
|
+
self._record_assignment_alias(node.targets, node.value)
|
|
225
|
+
self.generic_visit(node)
|
|
226
|
+
|
|
227
|
+
def visit_AnnAssign(self, node: ast.AnnAssign) -> None: # noqa: N802
|
|
228
|
+
"""Track annotated variable aliasing of dangerous symbols or modules."""
|
|
229
|
+
if node.value is not None:
|
|
230
|
+
self._record_assignment_alias([node.target], node.value)
|
|
231
|
+
self.generic_visit(node)
|
|
232
|
+
|
|
233
|
+
def _record_assignment_alias(self, targets: list[ast.expr], value: ast.expr) -> None:
|
|
234
|
+
resolved = self._resolve_name(value)
|
|
235
|
+
if not resolved:
|
|
236
|
+
return
|
|
237
|
+
if (
|
|
238
|
+
self._is_dangerous_call_name(resolved)
|
|
239
|
+
or self._is_restricted_reference(resolved)
|
|
240
|
+
or resolved in {"os", "sys", "builtins"}
|
|
241
|
+
):
|
|
242
|
+
for target in targets:
|
|
243
|
+
if isinstance(target, ast.Name):
|
|
244
|
+
self._symbol_aliases[target.id] = resolved
|
|
46
245
|
|
|
47
246
|
def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None: # noqa: N802
|
|
48
247
|
"""Detect overly broad exception handlers."""
|
|
@@ -50,10 +249,38 @@ class _SafetyVisitor(ast.NodeVisitor):
|
|
|
50
249
|
self.generic_visit(node)
|
|
51
250
|
|
|
52
251
|
def visit_Call(self, node: ast.Call) -> None: # noqa: N802
|
|
53
|
-
"""Detect dangerous parametrizable function calls."""
|
|
252
|
+
"""Detect dangerous parametrizable or aliased function calls."""
|
|
253
|
+
self._call_func_ids.add(id(node.func))
|
|
54
254
|
self._check_dangerous_call(node)
|
|
55
255
|
self.generic_visit(node)
|
|
56
256
|
|
|
257
|
+
def visit_Attribute(self, node: ast.Attribute) -> None: # noqa: N802
|
|
258
|
+
"""Detect dangerous dunder reflection and restricted module attributes."""
|
|
259
|
+
if node.attr in _BLOCKED_DUNDER_ATTRS:
|
|
260
|
+
self._context.add_violation(
|
|
261
|
+
f"Access to restricted attribute ``{node.attr}`` is not allowed",
|
|
262
|
+
line=node.lineno,
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
if id(node) not in self._call_func_ids:
|
|
266
|
+
resolved = self._resolve_name(node)
|
|
267
|
+
if self._is_restricted_reference(resolved):
|
|
268
|
+
self._context.add_violation(
|
|
269
|
+
f"Access to restricted attribute ``{resolved}`` is not allowed",
|
|
270
|
+
line=node.lineno,
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
self.generic_visit(node)
|
|
274
|
+
|
|
275
|
+
def visit_Name(self, node: ast.Name) -> None: # noqa: N802
|
|
276
|
+
"""Detect direct references to blocked reflection dunders."""
|
|
277
|
+
if node.id in _BLOCKED_DUNDER_ATTRS:
|
|
278
|
+
self._context.add_violation(
|
|
279
|
+
f"Access to restricted name ``{node.id}`` is not allowed",
|
|
280
|
+
line=node.lineno,
|
|
281
|
+
)
|
|
282
|
+
self.generic_visit(node)
|
|
283
|
+
|
|
57
284
|
def _check_generic_except(self, node: ast.ExceptHandler) -> None:
|
|
58
285
|
"""Flag ``except:``, ``except Exception:`` and ``except BaseException:``."""
|
|
59
286
|
if node.type is None:
|
|
@@ -63,22 +290,63 @@ class _SafetyVisitor(ast.NodeVisitor):
|
|
|
63
290
|
)
|
|
64
291
|
return
|
|
65
292
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
self.
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
293
|
+
candidates = node.type.elts if isinstance(node.type, ast.Tuple) else [node.type]
|
|
294
|
+
for candidate in candidates:
|
|
295
|
+
name = self._resolve_name(candidate)
|
|
296
|
+
if name in _GENERIC_EXCEPTIONS or name.removeprefix("builtins.") in _GENERIC_EXCEPTIONS:
|
|
297
|
+
self._context.add_violation(
|
|
298
|
+
f"Overly generic exception handler ``except {name}:`` is not allowed",
|
|
299
|
+
line=node.lineno,
|
|
300
|
+
)
|
|
72
301
|
|
|
73
302
|
def _check_dangerous_call(self, node: ast.Call) -> None:
|
|
74
|
-
"""Flag direct calls to
|
|
75
|
-
name = self.
|
|
76
|
-
if name
|
|
303
|
+
"""Flag direct or aliased calls to dangerous functions."""
|
|
304
|
+
name = self._resolve_name(node.func)
|
|
305
|
+
if self._is_dangerous_call_name(name):
|
|
77
306
|
self._context.add_violation(
|
|
78
307
|
f"Dangerous parametrizable function call ``{name}()`` is not allowed",
|
|
79
308
|
line=node.lineno,
|
|
80
309
|
)
|
|
81
310
|
|
|
311
|
+
@staticmethod
|
|
312
|
+
def _is_dangerous_call_name(name: str) -> bool:
|
|
313
|
+
if not name:
|
|
314
|
+
return False
|
|
315
|
+
if name in _DANGEROUS_NAMES or name in _BLOCKED_BUILTINS:
|
|
316
|
+
return True
|
|
317
|
+
if name.startswith("builtins.") and name.removeprefix("builtins.") in _BLOCKED_BUILTINS:
|
|
318
|
+
return True
|
|
319
|
+
if name.startswith("os.") and name.split(".", 1)[1] in _BLOCKED_OS_ATTRS:
|
|
320
|
+
return True
|
|
321
|
+
if name.startswith("sys.") and name.split(".", 1)[1] in _BLOCKED_SYS_ATTRS:
|
|
322
|
+
return True
|
|
323
|
+
return name.split(".")[0] in _BLOCKED_MODULES
|
|
324
|
+
|
|
325
|
+
@staticmethod
|
|
326
|
+
def _is_restricted_reference(name: str) -> bool:
|
|
327
|
+
if not name:
|
|
328
|
+
return False
|
|
329
|
+
if name.startswith("sys.") and name.split(".", 1)[1].split(".")[0] in _BLOCKED_SYS_ATTRS:
|
|
330
|
+
return True
|
|
331
|
+
if name.startswith("os.") and name.split(".", 1)[1] in _BLOCKED_OS_ATTRS:
|
|
332
|
+
return True
|
|
333
|
+
if name.startswith("builtins.") and name.removeprefix("builtins.") in _BLOCKED_BUILTINS:
|
|
334
|
+
return True
|
|
335
|
+
return name.split(".")[0] in _BLOCKED_MODULES
|
|
336
|
+
|
|
337
|
+
def _resolve_name(self, node: ast.AST | None) -> str:
|
|
338
|
+
"""Resolve a dotted AST name while expanding module and symbol aliases."""
|
|
339
|
+
raw = self._name_from_node(node)
|
|
340
|
+
if not raw:
|
|
341
|
+
return ""
|
|
342
|
+
parts = raw.split(".")
|
|
343
|
+
head = parts[0]
|
|
344
|
+
if head in self._symbol_aliases:
|
|
345
|
+
parts[0] = self._symbol_aliases[head]
|
|
346
|
+
elif head in self._module_aliases:
|
|
347
|
+
parts[0] = self._module_aliases[head]
|
|
348
|
+
return ".".join(parts)
|
|
349
|
+
|
|
82
350
|
@staticmethod
|
|
83
351
|
def _name_from_node(node: ast.AST | None) -> str:
|
|
84
352
|
"""Return a best-effort dotted name for an AST node."""
|
|
@@ -87,7 +355,8 @@ class _SafetyVisitor(ast.NodeVisitor):
|
|
|
87
355
|
if isinstance(node, ast.Name):
|
|
88
356
|
return node.id
|
|
89
357
|
if isinstance(node, ast.Attribute):
|
|
90
|
-
|
|
358
|
+
parent = _SafetyVisitor._name_from_node(node.value)
|
|
359
|
+
return f"{parent}.{node.attr}" if parent else node.attr
|
|
91
360
|
if isinstance(node, ast.Subscript):
|
|
92
361
|
return _SafetyVisitor._name_from_node(node.value)
|
|
93
362
|
return ""
|
|
@@ -98,18 +367,15 @@ def _lines_from_source(code: str) -> dict[int, str]:
|
|
|
98
367
|
return {idx + 1: line for idx, line in enumerate(code.splitlines())}
|
|
99
368
|
|
|
100
369
|
|
|
101
|
-
def _split_first_line(code: str) -> tuple[str, ...]:
|
|
102
|
-
"""Return source lines as a tuple to keep them hashable when needed."""
|
|
103
|
-
return tuple(code.splitlines())
|
|
104
|
-
|
|
105
|
-
|
|
106
370
|
def validate_syntax_and_safety(code: str) -> ValidationReport:
|
|
107
371
|
"""Validate ``code`` using the standard ``ast`` module.
|
|
108
372
|
|
|
109
373
|
The validation detects:
|
|
110
374
|
- Syntax errors raised by ``ast.parse``.
|
|
111
375
|
- Bare ``except:`` clauses and handlers using ``Exception``/``BaseException``.
|
|
112
|
-
-
|
|
376
|
+
- Imports of blocked system/FFI/serialization/reflection modules.
|
|
377
|
+
- Direct, aliased, or assigned calls to dangerous builtins and ``os``/``sys`` APIs.
|
|
378
|
+
- Access to reflection dunder attributes (e.g. ``__builtins__``, ``__subclasses__``).
|
|
113
379
|
|
|
114
380
|
Args:
|
|
115
381
|
code: Python source code to validate.
|
codeshield/classifier.py
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import keyword
|
|
5
6
|
import logging
|
|
6
7
|
import re
|
|
7
8
|
|
|
@@ -147,7 +148,9 @@ class TracebackClassifier:
|
|
|
147
148
|
return None
|
|
148
149
|
match = re.search(r"name '([^']+)' is not defined", diagnosis.message)
|
|
149
150
|
if match:
|
|
150
|
-
|
|
151
|
+
candidate = match.group(1)
|
|
152
|
+
if candidate.isidentifier() and not keyword.iskeyword(candidate):
|
|
153
|
+
return candidate
|
|
151
154
|
return None
|
|
152
155
|
|
|
153
156
|
def extract_missing_module(self, diagnosis: ErrorDiagnosis) -> str | None:
|
|
@@ -156,7 +159,9 @@ class TracebackClassifier:
|
|
|
156
159
|
return None
|
|
157
160
|
match = re.search(r"No module named '([^']+)'", diagnosis.message)
|
|
158
161
|
if match:
|
|
159
|
-
|
|
162
|
+
candidate = match.group(1)
|
|
163
|
+
if candidate and all(part.isidentifier() for part in candidate.split(".")):
|
|
164
|
+
return candidate
|
|
160
165
|
return None
|
|
161
166
|
|
|
162
167
|
|
codeshield/cli.py
CHANGED
|
@@ -7,7 +7,9 @@ import logging
|
|
|
7
7
|
import sys
|
|
8
8
|
from pathlib import Path
|
|
9
9
|
|
|
10
|
-
from codeshield.
|
|
10
|
+
from codeshield.environment import SandboxError
|
|
11
|
+
from codeshield.loop import SelfHealingEngine, SelfHealingError
|
|
12
|
+
from codeshield.runner import SubprocessRunnerError
|
|
11
13
|
|
|
12
14
|
logger = logging.getLogger(__name__)
|
|
13
15
|
|
|
@@ -70,16 +72,24 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
70
72
|
parser.print_help()
|
|
71
73
|
return 2
|
|
72
74
|
|
|
73
|
-
if not args.file.
|
|
75
|
+
if not args.file.is_file():
|
|
74
76
|
logger.error("File not found: %s", args.file)
|
|
75
77
|
return 1
|
|
76
78
|
|
|
79
|
+
if args.timeout <= 0 or args.timeout > 3600:
|
|
80
|
+
logger.error("Timeout must be between 0 and 3600 seconds.")
|
|
81
|
+
return 1
|
|
82
|
+
|
|
77
83
|
code = _read_file(args.file)
|
|
78
84
|
use_llm = not args.no_llm if args.no_llm else args.llm
|
|
79
85
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
86
|
+
try:
|
|
87
|
+
engine = SelfHealingEngine(use_llm=use_llm)
|
|
88
|
+
with engine:
|
|
89
|
+
result, diagnosis = engine.run(code, timeout=args.timeout)
|
|
90
|
+
except (SelfHealingError, SandboxError, SubprocessRunnerError, ValueError) as exc:
|
|
91
|
+
logger.error("Execution failed: %s", exc)
|
|
92
|
+
return 1
|
|
83
93
|
|
|
84
94
|
print("--- STDOUT ---")
|
|
85
95
|
print(result.stdout)
|
|
@@ -91,10 +101,18 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
91
101
|
print("Execution timed out")
|
|
92
102
|
if result.silent_failure_detected:
|
|
93
103
|
print("Silent failure detected")
|
|
104
|
+
if result.output_truncated:
|
|
105
|
+
print("Output was truncated due to size limit")
|
|
94
106
|
if diagnosis:
|
|
95
107
|
print(f"Diagnosis: {diagnosis.error_type} - {diagnosis.message}")
|
|
96
108
|
|
|
97
|
-
return
|
|
109
|
+
return (
|
|
110
|
+
0
|
|
111
|
+
if result.exit_code == 0
|
|
112
|
+
and not result.silent_failure_detected
|
|
113
|
+
and not result.timed_out
|
|
114
|
+
else 1
|
|
115
|
+
)
|
|
98
116
|
|
|
99
117
|
|
|
100
118
|
if __name__ == "__main__":
|