import re
from typing import Dict, Any
class SecureAICodeInterpreter:
def __init__(self, api_key: str):
self.api_key = api_key
self.sandbox = None
self.max_code_length = 100000 # 100KB limit
self.blocked_patterns = [
r'import\s+os\.system',
r'import\s+subprocess',
r'eval\s*\(',
r'exec\s*\(',
r'__import__',
r'open\s*\([^)]*[\'"]/etc',
]
def validate_code(self, code: str) -> Dict[str, Any]:
"""Validate code before execution"""
# Check length
if len(code) > self.max_code_length:
return {
"valid": False,
"error": f"Code exceeds maximum length of {self.max_code_length} characters"
}
# Check for blocked patterns
for pattern in self.blocked_patterns:
if re.search(pattern, code, re.IGNORECASE):
return {
"valid": False,
"error": f"Code contains blocked pattern: {pattern}"
}
return {"valid": True}
def execute_safely(self, code: str, timeout: int = 30):
"""Execute code with validation and error handling"""
# Validate code
validation = self.validate_code(code)
if not validation["valid"]:
return {
"success": False,
"error": validation["error"],
"validation_failed": True
}
try:
if not self.sandbox:
self.sandbox = Sandbox.create(
template="code-interpreter",
api_key=self.api_key,
timeout_seconds=600
)
# Execute with timeout
result = self.sandbox.run_code(code, timeout=timeout)
# Check for suspicious output
if result.stderr and any(keyword in result.stderr.lower()
for keyword in ['permission denied', 'access denied', 'unauthorized']):
return {
"success": False,
"error": "Security violation detected in execution",
"stderr": result.stderr
}
return {
"success": result.success,
"stdout": result.stdout,
"stderr": result.stderr,
"exit_code": result.exit_code
}
except Exception as e:
return {
"success": False,
"error": f"Execution error: {str(e)}"
}
def cleanup(self):
if self.sandbox:
self.sandbox.kill()
self.sandbox = None
# Usage
interpreter = SecureAICodeInterpreter(api_key=os.getenv("HOPX_API_KEY"))
# This will be blocked
result = interpreter.execute_safely("import subprocess; subprocess.call(['rm', '-rf', '/'])")
print(result) # {"success": False, "error": "Code contains blocked pattern...", "validation_failed": True}
# This will execute
result = interpreter.execute_safely("print('Hello, safe code!')")
print(result)
interpreter.cleanup()