-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor.py
More file actions
60 lines (48 loc) · 1.82 KB
/
executor.py
File metadata and controls
60 lines (48 loc) · 1.82 KB
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
import json
import subprocess
import tempfile
import os
import ast
def contains_main_function(code: str) -> bool:
try:
tree = ast.parse(code)
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef) and node.name == "main":
return True
except SyntaxError:
return False
return False
def execute_script(user_code):
if not contains_main_function(user_code):
raise Exception("Script must define a function named main()")
# Patch script to serialize main() return
wrapped_code = f"{user_code.strip()}\nimport json\nprint(json.dumps(main()))"
with tempfile.NamedTemporaryFile(delete=False, dir='/app', suffix='.py') as f:
f.write(wrapped_code.encode())
f.flush()
os.chmod(f.name, 0o444) # make it read-only
command = [
"nsjail",
"--config", "nsjail.cfg",
"--",
"/usr/bin/python", f.name
]
process = subprocess.run(
command, capture_output=True, text=True, timeout=10
)
stdout = process.stdout.strip()
stderr = process.stderr.strip()
if process.returncode != 0:
raise Exception(f"Script execution failed: {stderr}")
lines = stdout.splitlines()
for line in reversed(lines):
try:
result_json = json.loads(line)
if result_json is None:
raise Exception("main() did not return a value")
if not isinstance(result_json, dict):
raise Exception("main() must return a JSON object (e.g., a Python dict)")
return result_json, "\n".join(lines[:-1])
except json.JSONDecodeError:
continue
raise Exception("Script did not return valid JSON from main()")