File size: 7,206 Bytes
bb88361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Shell Execution Tool - Safe command execution for the Agent
"""
import asyncio
import subprocess
import json
import os
import shlex
from typing import Dict, Any, List, Optional
from pathlib import Path

class ShellExecutionTool:
    """Safe shell execution with security restrictions"""
    
    # Commands that are NEVER allowed
    BLOCKED_COMMANDS = {
        'rm -rf /', 'rm -rf /*', 'format c:', 'del /f /s /q',
        'shutdown', 'reboot', 'init 0', 'halt', 'poweroff',
        'dd if=/dev/zero', 'mkfs', 'fdisk', 'parted',
        ':(){ :|:& };:', 'fork bomb'
    }
    
    # Command patterns that need confirmation
    DANGEROUS_PATTERNS = [
        r'rm\s+-rf',
        r'sudo\s+',
        r'chmod\s+777',
        r'chown\s+',
        r'>\s*/etc/',
        r'curl\s+.*\|\s*(ba)?sh',
        r'wget\s+.*\|\s*(ba)?sh',
        r'pip\s+install\s+--index-url',
    ]
    
    # Allowed command prefixes (whitelist)
    ALLOWED_PREFIXES = {
        'ls', 'dir', 'cd', 'pwd', 'cat', 'type', 'head', 'tail',
        'grep', 'find', 'rg', 'awk', 'sed', 'sort', 'uniq',
        'python', 'python3', 'pip', 'pip3', 'node', 'npm', 'npx',
        'git', 'docker', 'docker-compose', 'make', 'cargo',
        'pytest', 'jest', 'mocha', 'vitest', 'unittest',
        'curl', 'wget', 'echo', 'printf', 'date', 'whoami',
        'mkdir', 'touch', 'cp', 'mv', 'tree', 'wc', 'diff',
        'tar', 'zip', 'unzip', 'gzip', 'gunzip',
        'black', 'flake8', 'pylint', 'mypy', 'ruff',
        'prettier', 'eslint', 'tsc',
    }
    
    def __init__(self, workspace_root: str = "./workspace"):
        self.workspace_root = Path(workspace_root).resolve()
        self.timeout = 30  # seconds
        self.max_output_size = 10000  # characters
    
    def _validate_command(self, command: str) -> Dict[str, Any]:
        """Validate command for security"""
        command_lower = command.lower().strip()
        
        # Check blocked commands
        for blocked in self.BLOCKED_COMMANDS:
            if blocked in command_lower:
                return {"safe": False, "reason": f"Blocked command: {blocked}"}
        
        # Check dangerous patterns
        import re
        for pattern in self.DANGEROUS_PATTERNS:
            if re.search(pattern, command_lower):
                return {"safe": False, "reason": f"Dangerous pattern: {pattern}"}
        
        # Check if command starts with allowed prefix
        first_word = command_lower.split()[0] if command_lower else ""
        if first_word not in self.ALLOWED_PREFIXES:
            return {"safe": False, "reason": f"Command not in whitelist: {first_word}"}
        
        return {"safe": True, "reason": "OK"}
    
    async def execute(self, command: str, cwd: Optional[str] = None, timeout: Optional[int] = None) -> Dict[str, Any]:
        """Execute a shell command safely"""
        # Validate command
        validation = self._validate_command(command)
        if not validation["safe"]:
            return {
                "success": False,
                "error": f"Security check failed: {validation['reason']}",
                "command": command
            }
        
        # Set working directory
        work_dir = cwd or str(self.workspace_root)
        work_path = Path(work_dir).resolve()
        
        # Ensure we're within workspace
        try:
            work_path.relative_to(self.workspace_root)
        except ValueError:
            return {"success": False, "error": "Working directory outside workspace"}
        
        timeout = timeout or self.timeout
        
        try:
            # Execute command
            process = await asyncio.create_subprocess_shell(
                command,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
                cwd=str(work_path),
                env={**os.environ, "PYTHONUNBUFFERED": "1"}
            )
            
            try:
                stdout, stderr = await asyncio.wait_for(
                    process.communicate(),
                    timeout=timeout
                )
            except asyncio.TimeoutError:
                process.kill()
                return {
                    "success": False,
                    "error": f"Command timed out after {timeout}s",
                    "command": command
                }
            
            # Decode output
            stdout_str = stdout.decode('utf-8', errors='replace')[:self.max_output_size]
            stderr_str = stderr.decode('utf-8', errors='replace')[:self.max_output_size]
            
            return {
                "success": process.returncode == 0,
                "exit_code": process.returncode,
                "stdout": stdout_str,
                "stderr": stderr_str,
                "command": command,
                "working_directory": str(work_path)
            }
        
        except Exception as e:
            return {
                "success": False,
                "error": f"Execution failed: {str(e)}",
                "command": command
            }
    
    async def run_python(self, code: str, timeout: int = 30) -> Dict[str, Any]:
        """Execute Python code directly"""
        import tempfile
        
        # Write code to temporary file
        with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False, dir=self.workspace_root) as f:
            f.write(code)
            temp_file = f.name
        
        try:
            result = await self.execute(f"python {temp_file}", timeout=timeout)
            return result
        finally:
            # Cleanup
            try:
                os.unlink(temp_file)
            except:
                pass
    
    async def run_tests(self, framework: str = "pytest", pattern: str = "test_*.py") -> Dict[str, Any]:
        """Run test suite"""
        commands = {
            "pytest": f"pytest {pattern} -v --tb=short",
            "jest": f"npx jest {pattern}",
            "vitest": f"npx vitest run {pattern}",
            "mocha": f"npx mocha {pattern}",
            "unittest": f"python -m unittest discover -p '{pattern}'",
        }
        
        command = commands.get(framework)
        if not command:
            return {"success": False, "error": f"Unknown framework: {framework}"}
        
        return await self.execute(command, timeout=120)
    
    async def install_package(self, package: str, package_manager: str = "pip") -> Dict[str, Any]:
        """Install a package"""
        # Validate package name (prevent injection)
        import re
        if not re.match(r'^[a-zA-Z0-9\-_\.]+$', package):
            return {"success": False, "error": "Invalid package name"}
        
        commands = {
            "pip": f"pip install {package}",
            "npm": f"npm install {package}",
            "yarn": f"yarn add {package}",
            "cargo": f"cargo add {package}",
            "gem": f"gem install {package}",
        }
        
        command = commands.get(package_manager)
        if not command:
            return {"success": False, "error": f"Unknown package manager: {package_manager}"}
        
        return await self.execute(command, timeout=300)