File size: 2,502 Bytes
49aa045 | 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 | """Stateless Python tool worker. Never receives a scenario or reference values."""
import json
import os
import signal
import subprocess
import sys
import tempfile
import threading
from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
lock = threading.Lock()
class Execution(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
code: str
@app.get("/health")
def health():
return {"ok": True}
@app.post("/execute")
def execute(request: Execution):
if len(request.code.encode()) > 65536:
return {"stdout": "Error: code exceeds 64 KiB limit"}
with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory:
os.chown(directory, 65534, 65534)
with tempfile.TemporaryFile() as output:
process = subprocess.Popen(
[sys.executable, "-I", "/app/child.py"],
stdin=subprocess.PIPE,
stdout=output,
stderr=subprocess.DEVNULL,
cwd=directory,
user=65534,
group=65534,
extra_groups=[],
start_new_session=True,
env={"PATH": "/usr/local/bin:/usr/bin:/bin"},
)
try:
process.communicate(
json.dumps({"code": request.code}).encode(), timeout=5
)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
return {"stdout": "Error: Python execution timed out"}
finally:
# Also remove children still in the process group after normal exit.
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
output.seek(0)
value = output.read(65537)
if len(value) > 65536 or process.returncode != 0:
return {
"stdout": "Error: Python execution exceeded a resource limit or failed"
}
try:
result = json.loads(value)
if not isinstance(result.get("stdout"), str):
raise ValueError("Invalid worker response")
return result
except (ValueError, AttributeError):
return {"stdout": "Error: Python execution returned invalid output"}
|