Files
ai-chess/apps/server/python/sandbox.py
T

107 lines
3.7 KiB
Python

"""
Tiny python sandbox for chess agents.
stdin: JSON {"code": str, "start_fen": str, "moves": [uci...], "history": [...], "analysis": {...}|null}
stdout: captured stdout/stderr of the user code (truncated by the caller).
Preloaded names: chess, chess.pgn, board (current position, with move stack), game (chess.pgn.Game),
moves (list of UCI strings), history (list of dicts: ply, side, san, uci, phrase),
analysis (only in post-game interviews: engine verdicts per ply).
Hardening (best effort, plus the container itself is the real boundary):
- CPU/memory/file-size rlimits, no child processes, no sockets, no writes outside /tmp.
"""
import io
import json
import resource
import sys
import contextlib
import traceback
def _set(kind, value):
try:
_soft, hard = resource.getrlimit(kind)
v = value if hard == resource.RLIM_INFINITY else min(value, hard)
resource.setrlimit(kind, (v, v))
except (ValueError, OSError):
pass # e.g. RLIMIT_AS is not supported on macOS
def limit():
_set(resource.RLIMIT_CPU, 10)
_set(resource.RLIMIT_AS, 768 * 1024 * 1024)
_set(resource.RLIMIT_FSIZE, 1024 * 1024)
_set(resource.RLIMIT_NPROC, 0)
BLOCKED_PREFIXES = ("subprocess.", "os.system", "os.exec", "os.spawn", "os.fork", "os.posix_spawn", "socket.", "pty.", "ctypes.", "os.kill")
def audit(event, args):
if event.startswith(BLOCKED_PREFIXES) or event in ("os.fork", "os.forkpty"):
raise PermissionError(f"заблокировано в песочнице: {event}")
if event == "open":
path, mode = args[0], args[1] if len(args) > 1 else "r"
if isinstance(mode, str) and any(c in mode for c in "wax+") and isinstance(path, str) and not path.startswith("/tmp/"):
raise PermissionError("запись файлов запрещена (кроме /tmp)")
def main():
payload = json.loads(sys.stdin.read())
import chess
import chess.pgn
board = chess.Board(payload.get("start_fen") or chess.STARTING_FEN)
game = chess.pgn.Game()
game.setup(board)
node = game
moves = list(payload.get("moves") or [])
for u in moves:
mv = chess.Move.from_uci(u)
if mv not in board.legal_moves:
# cheating-mode relocation: rebuild position from fen if provided
break
node = node.add_variation(mv)
board.push(mv)
if payload.get("fen") and board.fen() != payload["fen"]:
board = chess.Board(payload["fen"])
env = {
"__name__": "__sandbox__",
"chess": chess,
"board": board,
"game": game,
"moves": moves,
"history": payload.get("history") or [],
"analysis": payload.get("analysis"),
}
limit()
sys.addaudithook(audit)
out = io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(out):
try:
code = payload["code"]
try:
# REPL-ish: if the last statement is an expression, print it
import ast
tree = ast.parse(code, mode="exec")
if tree.body and isinstance(tree.body[-1], ast.Expr):
last = ast.Expression(tree.body.pop().value)
exec(compile(tree, "<agent>", "exec"), env)
val = eval(compile(last, "<agent>", "eval"), env)
if val is not None:
print(repr(val))
else:
exec(compile(tree, "<agent>", "exec"), env)
except SyntaxError:
raise
except BaseException: # noqa: BLE001
traceback.print_exc(limit=3)
sys.stdout.write(out.getvalue())
if __name__ == "__main__":
main()