File size: 7,142 Bytes
a7d7463
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
"""Code Execution Engine"""

import subprocess
import sys
import ast
import re
from typing import Dict, Optional, Any
from dataclasses import dataclass


@dataclass
class ExecutionResult:
    """Code execution result container"""

    success: bool
    output: str
    error: Optional[str] = None
    execution_time: float = 0.0


class CodeExecutor:
    """Execute code in various programming languages"""

    SUPPORTED_LANGUAGES = ["python", "javascript", "typescript", "sql", "bash"]

    def __init__(self, timeout: int = 30, sandbox: bool = True):
        self.timeout = timeout
        self.sandbox = sandbox
        self.execution_count = 0

    def execute(self, code: str, language: str = "python") -> ExecutionResult:
        """Execute code and return result"""
        if language not in self.SUPPORTED_LANGUAGES:
            return ExecutionResult(
                success=False,
                output="",
                error=f"Unsupported language: {language}",
            )

        if self._contains_malicious_code(code):
            return ExecutionResult(
                success=False,
                output="",
                error="Potentially malicious code detected",
            )

        self.execution_count += 1

        if language == "python":
            return self._execute_python(code)
        elif language == "javascript":
            return self._execute_javascript(code)
        elif language == "sql":
            return self._execute_sql(code)
        elif language == "bash":
            return self._execute_bash(code)

        return ExecutionResult(success=False, output="", error="Execution failed")

    def _contains_malicious_code(self, code: str) -> bool:
        """Check for potentially malicious patterns"""
        dangerous_patterns = [
            r"__import__\s*\(",
            r"exec\s*\(",
            r"eval\s*\(",
            r"subprocess\s*\(.*shell\s*=\s*True",
            r"os\.system\s*\(",
            r"shutil\.rmtree",
            r"open\s*\([^)]*['\"][wr]",
        ]

        for pattern in dangerous_patterns:
            if re.search(pattern, code):
                return True

        return False

    def _execute_python(self, code: str) -> ExecutionResult:
        """Execute Python code"""
        import time

        start_time = time.time()

        try:
            tree = ast.parse(code)
            namespace: Dict[str, Any] = {}
            exec(compile(tree, "<string>", "exec"), namespace)

            output = self._capture_output(namespace)
            execution_time = time.time() - start_time

            return ExecutionResult(
                success=True, output=output, execution_time=execution_time
            )

        except SyntaxError as e:
            return ExecutionResult(
                success=False,
                output="",
                error=f"Syntax Error: {e}",
                execution_time=time.time() - start_time,
            )
        except Exception as e:
            return ExecutionResult(
                success=False,
                output="",
                error=f"Runtime Error: {e}",
                execution_time=time.time() - start_time,
            )

    def _capture_output(self, namespace: Dict[str, Any]) -> str:
        """Capture relevant output from namespace"""
        output_lines = []

        if "result" in namespace:
            output_lines.append(str(namespace["result"]))

        for key, value in namespace.items():
            if key.startswith("output_"):
                output_lines.append(f"{key}: {value}")

        return "\n".join(output_lines) if output_lines else "Code executed successfully"

    def _execute_javascript(self, code: str) -> ExecutionResult:
        """Execute JavaScript code using Node.js"""
        import tempfile
        import time

        start_time = time.time()

        with tempfile.NamedTemporaryFile(
            mode="w", suffix=".js", delete=False
        ) as f:
            f.write(code)
            temp_file = f.name

        try:
            result = subprocess.run(
                ["node", temp_file],
                capture_output=True,
                text=True,
                timeout=self.timeout,
            )

            if result.returncode == 0:
                return ExecutionResult(
                    success=True,
                    output=result.stdout,
                    execution_time=time.time() - start_time,
                )
            else:
                return ExecutionResult(
                    success=False,
                    output="",
                    error=result.stderr,
                    execution_time=time.time() - start_time,
                )

        except subprocess.TimeoutExpired:
            return ExecutionResult(
                success=False,
                output="",
                error=f"Execution timed out after {self.timeout}s",
                execution_time=time.time() - start_time,
            )
        except FileNotFoundError:
            return ExecutionResult(
                success=False,
                output="",
                error="Node.js not found. Please install Node.js to execute JavaScript.",
                execution_time=time.time() - start_time,
            )
        finally:
            import os

            os.unlink(temp_file)

    def _execute_sql(self, code: str) -> ExecutionResult:
        """Execute SQL query"""
        import time

        start_time = time.time()

        return ExecutionResult(
            success=True,
            output=f"SQL query would be executed:\n{code}",
            execution_time=time.time() - start_time,
        )

    def _execute_bash(self, code: str) -> ExecutionResult:
        """Execute bash command"""
        import time

        start_time = time.time()

        if self.sandbox:
            return ExecutionResult(
                success=False,
                output="",
                error="Bash execution is disabled in sandbox mode",
                execution_time=time.time() - start_time,
            )

        try:
            result = subprocess.run(
                code, shell=True, capture_output=True, text=True, timeout=self.timeout
            )

            return ExecutionResult(
                success=result.returncode == 0,
                output=result.stdout,
                error=result.stderr if result.returncode != 0 else None,
                execution_time=time.time() - start_time,
            )

        except subprocess.TimeoutExpired:
            return ExecutionResult(
                success=False,
                output="",
                error=f"Command timed out after {self.timeout}s",
                execution_time=time.time() - start_time,
            )

    def validate_syntax(self, code: str, language: str) -> tuple[bool, Optional[str]]:
        """Validate code syntax without execution"""
        if language == "python":
            try:
                ast.parse(code)
                return True, None
            except SyntaxError as e:
                return False, str(e)

        return True, None