Create codex/sandbox.py
Browse files- codex/sandbox.py +18 -0
codex/sandbox.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ast
|
| 2 |
+
|
| 3 |
+
SAFE_NODES = (
|
| 4 |
+
ast.Module, ast.Assign, ast.Expr, ast.Call, ast.Name, ast.Load,
|
| 5 |
+
ast.Constant, ast.BinOp, ast.Add, ast.Sub, ast.Mult, ast.Div,
|
| 6 |
+
ast.If, ast.Compare, ast.Return, ast.FunctionDef, ast.arguments
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
def safe_execute(code):
|
| 10 |
+
tree = ast.parse(code)
|
| 11 |
+
|
| 12 |
+
for node in ast.walk(tree):
|
| 13 |
+
if not isinstance(node, SAFE_NODES):
|
| 14 |
+
raise ValueError("Unsafe code detected")
|
| 15 |
+
|
| 16 |
+
local_env = {}
|
| 17 |
+
exec(compile(tree, "<sandbox>", "exec"), {"__builtins__": {}}, local_env)
|
| 18 |
+
return local_env
|