334 lines
13 KiB
Python
334 lines
13 KiB
Python
#!/usr/bin/env python3
|
|
"""iishko exec broker - E2B code sandboxes.
|
|
|
|
Real code execution for iishko users on E2B hosted infra (e2b.dev).
|
|
Runs under the native Python311 (needs `e2b` package; hermes venv does not have it).
|
|
|
|
Guarantees:
|
|
* zero VPS involvement - code runs on E2B machines, broker only calls api.e2b.dev
|
|
* network egress OFF - allow_internet_access=False: DNS fails, no data leak
|
|
* no secrets in sandbox - credential-shaped strings in code are refused
|
|
* output sanitisation - key/token/password patterns redacted before return
|
|
* hard caps - code size, run timeout, daily jobs + cpu-seconds per user
|
|
* per-key concurrency - semaphore, sandbox killed right after the run
|
|
* audit without payloads - sha256 of code, never the code itself
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import re
|
|
import threading
|
|
import time
|
|
import urllib.parse
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
CFG = json.load(open(os.path.join(HERE, "config.json"), encoding="utf-8"))
|
|
EXEC = CFG.get("exec", {})
|
|
LISTEN = EXEC.get("listen", "127.0.0.1")
|
|
PORT = int(EXEC.get("port", 48971))
|
|
CODE_MAX = int(EXEC.get("code_max_bytes", 16000))
|
|
TIMEOUT_MAX = int(EXEC.get("timeout_max_s", 120))
|
|
TIMEOUT_DEFAULT = int(EXEC.get("timeout_default_s", 60))
|
|
OUT_MAX = int(EXEC.get("output_max_bytes", 16384))
|
|
DAILY_JOBS = int(EXEC.get("daily_jobs_per_user", 200))
|
|
DAILY_CPU_S = int(EXEC.get("daily_cpu_seconds_per_user", 600))
|
|
POOL_CONCURRENCY = int(EXEC.get("pool_concurrency", 2))
|
|
TEMPLATE = EXEC.get("template", "base")
|
|
|
|
REDACT = [
|
|
(re.compile(r"(?i)\b(password|passwd|secret|token|api[_-]?key|authorization)\b(\s*[:=]\s*)[^\s,;\"'}]+"), r"\1\2<redacted>"),
|
|
(re.compile(r"\b(e2b_[A-Za-z0-9]{20,}|offense_sk_[A-Za-z0-9]+|sk-[A-Za-z0-9._-]{16,}|ck_[A-Za-z0-9]{10,}|nfp_[A-Za-z0-9]+)\b"), "<key>"),
|
|
]
|
|
|
|
FORBIDDEN_CODE = [
|
|
re.compile(r"\b(e2b_[A-Za-z0-9]{20,}|offense_sk_[A-Za-z0-9]+|sk-[A-Za-z0-9]{16,}|ck_[A-Za-z0-9]{10,}|nfp_[A-Za-z0-9]+)\b"),
|
|
re.compile(r"(?i)\b(password|passwd|api[_-]?key|secret|credential)s?\b\s*[:=]\s*['\"][^'\"]{6,}['\"]"),
|
|
]
|
|
|
|
STATE_DIR = os.path.join(HERE, "state")
|
|
os.makedirs(STATE_DIR, exist_ok=True)
|
|
AUDIT = os.path.join(STATE_DIR, "audit_exec.jsonl")
|
|
|
|
|
|
def audit(rec: dict):
|
|
rec["ts"] = int(time.time())
|
|
with open(AUDIT, "a", encoding="utf-8") as f:
|
|
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
|
|
|
|
|
def sanitize(s: str, limit: int = OUT_MAX) -> str:
|
|
if not s:
|
|
return ""
|
|
for rx, repl in REDACT:
|
|
s = rx.sub(repl, s)
|
|
if len(s) > limit:
|
|
s = s[:limit] + "\n<truncated>"
|
|
return s
|
|
|
|
|
|
def load_user_keys():
|
|
path = os.path.join(HERE, "keys.json")
|
|
if not os.path.exists(path):
|
|
return {}
|
|
data = json.load(open(path, encoding="utf-8"))
|
|
keys = {}
|
|
for item in data if isinstance(data, list) else data.get("keys", []):
|
|
tok = item.get("token") or ""
|
|
if tok:
|
|
keys[hashlib.sha256(tok.encode()).hexdigest()] = {
|
|
"name": item.get("name") or "user",
|
|
"enabled": bool(item.get("enabled", True)),
|
|
}
|
|
return keys
|
|
|
|
|
|
USER_KEYS = load_user_keys()
|
|
|
|
# ---- E2B key pool -----------------------------------------------------------
|
|
POOL_PATH = os.path.join(HERE, "e2b_pool.json")
|
|
|
|
|
|
class E2BPool:
|
|
def __init__(self, path):
|
|
self.keys = []
|
|
if os.path.exists(path):
|
|
data = json.load(open(path, encoding="utf-8"))
|
|
raw = data.get("keys") if isinstance(data, dict) else data
|
|
self.keys = [k for k in (raw or []) if isinstance(k, str) and k.strip()]
|
|
self.dead = set()
|
|
self.idx = 0
|
|
self.lock = threading.Lock()
|
|
self.sems = {k: threading.Semaphore(POOL_CONCURRENCY) for k in self.keys}
|
|
self.stats = {k: {"jobs": 0, "errors": 0} for k in self.keys}
|
|
|
|
def live(self):
|
|
with self.lock:
|
|
return [k for k in self.keys if k not in self.dead]
|
|
|
|
def acquire(self):
|
|
"""Return (key, semaphore) of the next live key, or (None, None)."""
|
|
live = self.live()
|
|
if not live:
|
|
return None, None
|
|
for _ in range(len(live)):
|
|
with self.lock:
|
|
k = live[self.idx % len(live)]
|
|
self.idx += 1
|
|
if k in self.dead:
|
|
continue
|
|
return k, self.sems.get(k)
|
|
return None, None
|
|
|
|
def mark_dead(self, key):
|
|
with self.lock:
|
|
if key not in self.dead:
|
|
self.dead.add(key)
|
|
self.keys = [k for k in self.keys if k != key]
|
|
self.sems.pop(key, None)
|
|
json.dump({"keys": self.keys}, open(POOL_PATH, "w", encoding="utf-8"), indent=1)
|
|
|
|
def info(self):
|
|
with self.lock:
|
|
return {"keys": len(self.keys), "dead_total_removed": len(self.dead),
|
|
"stats": [{"jobs": s["jobs"], "errors": s["errors"]} for s in self.stats.values()]}
|
|
|
|
|
|
POOL = E2BPool(POOL_PATH)
|
|
|
|
# ---- per-user daily counters ------------------------------------------------
|
|
USAGE = {} # key_id -> {day, jobs, cpu_s}
|
|
USAGE_LOCK = threading.Lock()
|
|
|
|
|
|
def usage_today(uid):
|
|
day = time.strftime("%Y-%m-%d")
|
|
with USAGE_LOCK:
|
|
u = USAGE.get(uid)
|
|
if not u or u["day"] != day:
|
|
USAGE[uid] = {"day": day, "jobs": 0, "cpu_s": 0.0}
|
|
u = USAGE[uid]
|
|
return u
|
|
|
|
|
|
def run_on_e2b(code: str, timeout: int):
|
|
"""Create a no-egress sandbox, run code, kill it. Returns a response dict."""
|
|
from e2b import Sandbox
|
|
|
|
last_err = None
|
|
for attempt in range(3):
|
|
key, sem = POOL.acquire()
|
|
if not key:
|
|
return {"error": "pool_empty", "detail": last_err}
|
|
with sem:
|
|
sb = None
|
|
t0 = time.time()
|
|
try:
|
|
sb = Sandbox.create(api_key=key, timeout=timeout + 45,
|
|
allow_internet_access=False,
|
|
metadata={"project": "iishko-exec"})
|
|
sb.files.write("/tmp/main.py", code)
|
|
res = sb.commands.run("python /tmp/main.py", timeout=timeout)
|
|
elapsed = time.time() - t0
|
|
with POOL.lock:
|
|
POOL.stats[key]["jobs"] += 1
|
|
return {
|
|
"ok": True,
|
|
"sandbox_id": sb.sandbox_id,
|
|
"exit_code": res.exit_code,
|
|
"stdout": sanitize(res.stdout or ""),
|
|
"stderr": sanitize(res.stderr or ""),
|
|
"elapsed_s": round(elapsed, 2),
|
|
"timeout_s": timeout,
|
|
}
|
|
except Exception as e:
|
|
last_err = "%s: %s" % (type(e).__name__, str(e)[:200])
|
|
if type(e).__name__ == "TimeoutException" or "timed out" in str(e).lower():
|
|
# user-side run timeout: clean answer, no retry burn
|
|
return {
|
|
"ok": True,
|
|
"timeout": True,
|
|
"exit_code": None,
|
|
"stdout": "",
|
|
"stderr": "execution timed out after %ss (sandbox killed)" % timeout,
|
|
"elapsed_s": round(time.time() - t0, 2),
|
|
"timeout_s": timeout,
|
|
}
|
|
with POOL.lock:
|
|
POOL.stats[key]["errors"] += 1
|
|
msg = str(e)
|
|
if "401" in msg or "Unauthorized" in msg or "Invalid" in msg and "key" in msg.lower():
|
|
POOL.mark_dead(key)
|
|
if sb is not None:
|
|
try:
|
|
sb.kill()
|
|
except Exception:
|
|
pass
|
|
continue # retry on another key
|
|
finally:
|
|
if sb is not None:
|
|
try:
|
|
sb.kill()
|
|
except Exception:
|
|
pass
|
|
return {"error": "execution_failed", "detail": last_err}
|
|
|
|
|
|
class Handler(BaseHTTPRequestHandler):
|
|
server_version = "iishko-exec/1.0"
|
|
|
|
def log_message(self, fmt, *args):
|
|
pass
|
|
|
|
def send_json(self, code: int, payload: dict):
|
|
body = json.dumps(payload, ensure_ascii=False).encode()
|
|
self.send_response(code)
|
|
self.send_header("content-type", "application/json; charset=utf-8")
|
|
self.send_header("content-length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
def auth(self):
|
|
tok = (self.headers.get("x-sandbox-key") or "").strip()
|
|
if not tok:
|
|
h = self.headers.get("authorization") or ""
|
|
if h.lower().startswith("bearer "):
|
|
tok = h[7:].strip()
|
|
if not tok:
|
|
return None, "missing_key"
|
|
rec = USER_KEYS.get(hashlib.sha256(tok.encode()).hexdigest())
|
|
if not rec:
|
|
return None, "invalid_key"
|
|
if not rec["enabled"]:
|
|
return None, "disabled"
|
|
return (hashlib.sha256(tok.encode()).hexdigest(), rec), None
|
|
|
|
def body(self):
|
|
n = int(self.headers.get("content-length") or 0)
|
|
if n <= 0 or n > 256 * 1024:
|
|
return None
|
|
try:
|
|
return json.loads(self.rfile.read(n).decode("utf-8"))
|
|
except Exception:
|
|
return None
|
|
|
|
def do_GET(self):
|
|
p = urllib.parse.urlparse(self.path).path
|
|
if p == "/healthz":
|
|
return self.send_json(200, {"ok": True, "pool": POOL.info(),
|
|
"users": len(USER_KEYS), "template": TEMPLATE})
|
|
key_id, why = self.auth()
|
|
if not key_id:
|
|
return self.send_json(401, {"error": why})
|
|
uid, urec = key_id
|
|
if p == "/v1/limits":
|
|
u = usage_today(uid)
|
|
return self.send_json(200, {"name": urec["name"], "jobs_today": u["jobs"],
|
|
"cpu_seconds_today": round(u["cpu_s"], 1),
|
|
"daily_jobs": DAILY_JOBS, "daily_cpu_seconds": DAILY_CPU_S,
|
|
"code_max_bytes": CODE_MAX, "timeout_max_s": TIMEOUT_MAX})
|
|
return self.send_json(404, {"error": "not_found"})
|
|
|
|
def do_POST(self):
|
|
p = urllib.parse.urlparse(self.path).path
|
|
key_id, why = self.auth()
|
|
if not key_id:
|
|
return self.send_json(401, {"error": why})
|
|
uid, urec = key_id
|
|
if p != "/v1/exec":
|
|
return self.send_json(404, {"error": "not_found"})
|
|
body = self.body()
|
|
if not body:
|
|
return self.send_json(400, {"error": "bad_json"})
|
|
code = body.get("code")
|
|
if not isinstance(code, str) or not code.strip():
|
|
return self.send_json(400, {"error": "code_required"})
|
|
if len(code.encode("utf-8")) > CODE_MAX:
|
|
return self.send_json(400, {"error": "code_too_large", "max_bytes": CODE_MAX})
|
|
for rx in FORBIDDEN_CODE:
|
|
if rx.search(code):
|
|
audit({"ev": "deny_code", "user": urec["name"],
|
|
"code_sha256": hashlib.sha256(code.encode()).hexdigest()})
|
|
return self.send_json(403, {"error": "code_refused",
|
|
"reason": "credential_material_in_code"})
|
|
try:
|
|
timeout = int(body.get("timeout_s") or TIMEOUT_DEFAULT)
|
|
except Exception:
|
|
timeout = TIMEOUT_DEFAULT
|
|
timeout = max(5, min(timeout, TIMEOUT_MAX))
|
|
|
|
u = usage_today(uid)
|
|
if u["jobs"] >= DAILY_JOBS:
|
|
return self.send_json(429, {"error": "daily_jobs", "used": u["jobs"], "limit": DAILY_JOBS})
|
|
if u["cpu_s"] >= DAILY_CPU_S:
|
|
return self.send_json(429, {"error": "daily_cpu_seconds", "used": round(u["cpu_s"], 1),
|
|
"limit": DAILY_CPU_S})
|
|
|
|
code_sha = hashlib.sha256(code.encode()).hexdigest()
|
|
audit({"ev": "exec", "user": urec["name"], "code_sha256": code_sha, "timeout": timeout})
|
|
t0 = time.time()
|
|
result = run_on_e2b(code, timeout)
|
|
elapsed = time.time() - t0
|
|
u["jobs"] += 1
|
|
u["cpu_s"] += min(elapsed, timeout)
|
|
audit({"ev": "done", "user": urec["name"], "code_sha256": code_sha,
|
|
"elapsed": round(elapsed, 2), "ok": bool(result.get("ok")),
|
|
"error": (result.get("error") or "")[:80]})
|
|
status = 200 if result.get("ok") else 502
|
|
result["elapsed_broker_s"] = round(elapsed, 2)
|
|
return self.send_json(status, result)
|
|
|
|
|
|
def main():
|
|
if not USER_KEYS:
|
|
print("WARNING: keys.json missing/empty - every request gets 401", flush=True)
|
|
print("exec broker on http://%s:%s e2b_keys=%d users=%d" % (LISTEN, PORT, len(POOL.keys), len(USER_KEYS)), flush=True)
|
|
srv = ThreadingHTTPServer((LISTEN, PORT), Handler)
|
|
srv.serve_forever()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|