iishko-sandbox: E2B exec broker + tunnel supervisor + bot run_code tool
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
keys.json
|
||||
agent_token.txt
|
||||
e2b_pool.json
|
||||
*.log
|
||||
state/
|
||||
__pycache__/
|
||||
@@ -0,0 +1,79 @@
|
||||
# iishko-sandbox — песочница исполнения кода для агента iishko
|
||||
|
||||
Два брокера, один формат ключей (`keys.json`, токены юзеров):
|
||||
|
||||
1. `broker.py` — offense.sh backend (сканер-API). Не исполняет код: у их free-раннера
|
||||
задача висит `running` при нулевом usage. Оставлен как reference.
|
||||
2. `exec_broker.py` — **рабочий** бэкенд на E2B: реальное исполнение Python 3.11,
|
||||
сеть внутри песочницы выключена, каждому запуску — новая одноразовая VM.
|
||||
|
||||
## exec_broker.py (E2B) — то, что в проде
|
||||
|
||||
```sh
|
||||
env -u PYTHONPATH /c/Users/User/AppData/Local/Programs/Python/Python311/python.exe exec_broker.py
|
||||
# слушает 127.0.0.1:48971
|
||||
```
|
||||
|
||||
Пул ключей E2B — `e2b_pool.json` (не в репе, кладётся рядом; каждый ключ ~$100 кредита).
|
||||
Лимиты — `config.json` → секция `exec`.
|
||||
|
||||
Гарантии (`prove_exec.py` — 12/12 PASS):
|
||||
|
||||
- код исполняется на машинах E2B, не локально;
|
||||
- `allow_internet_access=False`: DNS не резолвится, HTTP наружу падает — утечка данных невозможна;
|
||||
- код с ключ-подобными строками (`sk-…`, `e2b_…`, `ck_…`, `password=…`) → 403 до создания песочницы;
|
||||
- вывод санитизируется (`<redacted>`), режется на 16 КБ;
|
||||
- каждый запуск — новая песочница, `kill()` сразу после прогона;
|
||||
- таймаут убивает песочницу (sleep 90 при timeout 10 → 200 `timeout:true` за 12 с);
|
||||
- капы на юзера: 200 задач/день, 600 CPU-сек/день, код ≤16 КБ, таймаут ≤120 с;
|
||||
- аудит хранит только sha256 кода, не сам код.
|
||||
|
||||
## API
|
||||
|
||||
```
|
||||
GET /healthz — пул ключей, юзеры, шаблон
|
||||
GET /v1/limits — лимиты и расход юзера
|
||||
POST /v1/exec {"code": "...", "timeout_s": 60}
|
||||
-> {"ok":true,"exit_code":0,"stdout":"...","stderr":"...","elapsed_s":2.1,
|
||||
"timeout_s":60,"sandbox_id":"i..."}
|
||||
таймаут: {"ok":true,"timeout":true,...}
|
||||
ошибка: 502 {"error":"execution_failed","detail":"..."}
|
||||
```
|
||||
|
||||
Заголовок авторизации: `X-Sandbox-Key: <токен из keys.json>`.
|
||||
|
||||
## Как это подключено к боту (VPS → дом)
|
||||
|
||||
Исполнение остаётся на E2B, VPS не несёт нагрузки и не видит данных:
|
||||
|
||||
```
|
||||
Telegram юзер -> бот (VPS) -> tool run_code -> 127.0.0.1:48979 (VPS)
|
||||
-> ssh reverse-туннель -> дом:48971 (exec_broker) -> E2B VM -> ответ
|
||||
```
|
||||
|
||||
- `sandbox_sup.py` — супервизор: держит живыми локальный брокер и reverse-туннель
|
||||
(`ssh -N -R 48979:127.0.0.1:48971`), запускается кроном каждые 2 минуты.
|
||||
- `patch_sbx_v2.py` — патч бота: добавляет в `BOT_TOOLS` инструмент `run_code`
|
||||
и ветку в `_bot_tool_exec` (POST на `127.0.0.1:48979/v1/exec`).
|
||||
Токен брокера на проде: `/opt/grok-bot/sb_token.txt` (chmod 600).
|
||||
|
||||
## Питфолы (проверено, стоило времени)
|
||||
|
||||
- Нативный Python → `ssh.exe` напрямую: rc 255 и **пустой** stderr. Работает только
|
||||
через `cmd.exe /c "ssh …"`; в remote-команде нельзя `%{http_code}` (cmd.exe ест `%`)
|
||||
и вложенные кавычки (remote-bash отваливается).
|
||||
- `e2b` SDK живёт только на нативном Python311 (`env -u PYTHONPATH`), в hermes-venv — нет.
|
||||
- Рабочий API E2B на пине 2.11.10: `from e2b import Sandbox; Sandbox.create(api_key=…,
|
||||
timeout=…, allow_internet_access=False)` — конструктор `e2b_code_interpreter.Sandbox(api_key=…)`
|
||||
ключ не принимает.
|
||||
- Патч чужого кода — только по точным якорям с проверкой `count == 1`: regex-замена по
|
||||
префиксу файла вставила код в шапку `legacy.py` и уронила сервис (восстановлено из бэкапа).
|
||||
|
||||
## Файлы
|
||||
|
||||
- `exec_broker.py` — E2B-брокер (порт 48971)
|
||||
- `sandbox_sup.py` — супервизор брокера + туннеля
|
||||
- `prove_exec.py` — приёмка (12/12)
|
||||
- `patch_sbx_v2.py` — патч бота (инструмент `run_code`)
|
||||
- `config.json` — лимиты и порт
|
||||
- `broker.py`, `prove.py` — offense.sh-вариант (reference, не исполняет код)
|
||||
@@ -0,0 +1,462 @@
|
||||
#!/usr/bin/env python3
|
||||
"""iishko sandbox broker.
|
||||
|
||||
Routes iishko user jobs into disposable Offense sandboxes (offense.sh hosted infra).
|
||||
Nothing runs on the iishko VPS: the broker only makes outbound HTTPS calls to
|
||||
https://app.offense.sh and never executes user code itself.
|
||||
|
||||
Guarantees:
|
||||
* no local execution - only JSON goes out, findings come back
|
||||
* no repo/file upload - /api/v1/scans (gzip upload) is never called
|
||||
* target deny-list - our own hosts and private IPs are refused
|
||||
* instruction screening - credentials-looking strings are refused
|
||||
* hard budget caps - per job and per key per day
|
||||
* balance floor - refuses work when workspace credit is low
|
||||
* response sanitisation - cookies/tokens/passwords are redacted
|
||||
* audit log without payloads - sha256 of instruction, never the text
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
CFG_PATH = os.path.join(HERE, "config.json")
|
||||
STATE_DIR = os.path.join(HERE, "state")
|
||||
os.makedirs(STATE_DIR, exist_ok=True)
|
||||
|
||||
CFG = json.load(open(CFG_PATH, encoding="utf-8"))
|
||||
|
||||
REDACT = [
|
||||
(re.compile(r"(?i)(set-cookie\s*:\s*)[^\r\n]+"), r"\1<redacted>"),
|
||||
(re.compile(r"(?i)\b(password|passwd|secret|token|api[_-]?key)\b(\s*[:=]\s*)[^\s,;\"'}]+"), r"\1\2<redacted>"),
|
||||
(re.compile(r"(offense_sk_[A-Za-z0-9]+)"), "<offense-key>"),
|
||||
(re.compile(r"\b(sk-[A-Za-z0-9._-]{16,}|ck_[A-Za-z0-9]{10,}|nfp_[A-Za-z0-9]+)\b"), "<key>"),
|
||||
]
|
||||
|
||||
PRIVATE_HOST = re.compile(
|
||||
r"^(localhost|127\.|0\.0\.0\.0|10\.|192\.168\.|169\.254\.|172\.(1[6-9]|2\d|3[01])\.|\[?::1\]?$)"
|
||||
)
|
||||
|
||||
|
||||
class Offense:
|
||||
def __init__(self, base_url: str, key: str):
|
||||
self.base = base_url.rstrip("/")
|
||||
self.key = key
|
||||
|
||||
def call(self, path: str, method: str = "GET", body=None, headers=None, timeout=90):
|
||||
hdrs = {
|
||||
"authorization": "Bearer " + self.key,
|
||||
"accept": "application/json",
|
||||
"user-agent": "iishko-sandbox-broker/1.0",
|
||||
}
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
hdrs["content-type"] = "application/json"
|
||||
if headers:
|
||||
hdrs.update(headers)
|
||||
req = urllib.request.Request(self.base + path, data=data, headers=hdrs, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
raw = r.read().decode("utf-8", "replace")
|
||||
return r.status, (json.loads(raw) if raw.strip() else {})
|
||||
except urllib.error.HTTPError as e:
|
||||
raw = e.read().decode("utf-8", "replace")
|
||||
try:
|
||||
parsed = json.loads(raw) if raw.strip() else {}
|
||||
except Exception:
|
||||
parsed = {"raw": raw[:400]}
|
||||
return e.code, parsed
|
||||
except Exception as e: # network
|
||||
return 0, {"error": "network", "message": type(e).__name__}
|
||||
|
||||
# --- workspace state -------------------------------------------------
|
||||
def whoami(self):
|
||||
return self.call("/api/v1/whoami", timeout=30)
|
||||
|
||||
def target(self):
|
||||
return self.call("/api/v1/targets", timeout=30)
|
||||
|
||||
def register_target(self, target_url: str, project: str):
|
||||
return self.call("/api/v1/targets", "POST", {"target": target_url, "project": project})
|
||||
|
||||
def verify_target(self, target_id: str):
|
||||
return self.call("/api/v1/targets/%s/verify" % urllib.parse.quote(target_id), "POST", {}, timeout=120)
|
||||
|
||||
def launch(self, budget: int, instruction: str, model: str, idem: str):
|
||||
return self.call(
|
||||
"/api/v1/assessments",
|
||||
"POST",
|
||||
{"budgetMicros": int(budget), "instruction": instruction[:2000], "model": model},
|
||||
headers={"idempotency-key": idem},
|
||||
)
|
||||
|
||||
def assessment(self, aid: str):
|
||||
return self.call("/api/v1/assessments/" + urllib.parse.quote(aid), timeout=40)
|
||||
|
||||
def findings(self, aid: str):
|
||||
return self.call("/api/v1/assessments/%s/findings" % urllib.parse.quote(aid), timeout=60)
|
||||
|
||||
def usage(self, aid: str):
|
||||
return self.call("/api/v1/assessments/%s/usage" % urllib.parse.quote(aid), timeout=60)
|
||||
|
||||
def cancel(self, aid: str):
|
||||
return self.call("/api/v1/assessments/%s/cancel" % urllib.parse.quote(aid), "POST", {}, timeout=60)
|
||||
|
||||
|
||||
def load_pools():
|
||||
"""Workspace pool. One Offense workspace holds one target, so per-user isolation
|
||||
means one workspace (key) per user/slot; jobs are serialised inside a slot."""
|
||||
path = os.path.join(HERE, "pools.json")
|
||||
if os.path.exists(path):
|
||||
pools = json.load(open(path, encoding="utf-8"))
|
||||
out = []
|
||||
for i, p in enumerate(pools):
|
||||
key = p.get("key") or ""
|
||||
if not key and p.get("key_file"):
|
||||
kf = p["key_file"]
|
||||
if not os.path.isabs(kf):
|
||||
kf = os.path.join(HERE, kf)
|
||||
key = open(kf, encoding="utf-8").read().strip()
|
||||
if key:
|
||||
out.append({"name": p.get("name") or "pool%d" % i, "key": key, "lock": threading.Lock()})
|
||||
return out
|
||||
kf = CFG.get("key_file", "offense_key.txt")
|
||||
if not os.path.isabs(kf):
|
||||
kf = os.path.join(HERE, kf)
|
||||
return [{"name": "default", "key": open(kf, encoding="utf-8").read().strip(), "lock": threading.Lock()}]
|
||||
|
||||
|
||||
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",
|
||||
"daily_micros": int(item.get("daily_micros") or CFG["default_budget_micros"] * 10),
|
||||
"pool": item.get("pool") or "default",
|
||||
"enabled": bool(item.get("enabled", True)),
|
||||
}
|
||||
return keys
|
||||
|
||||
|
||||
POOLS = load_pools()
|
||||
POOL_BY_NAME = {p["name"]: p for p in POOLS}
|
||||
USER_KEYS = load_user_keys()
|
||||
JOBS = {} # id -> job dict
|
||||
JOBS_LOCK = threading.Lock()
|
||||
AUDIT = os.path.join(STATE_DIR, "audit.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 today_spend(key_id: str) -> int:
|
||||
day = time.strftime("%Y-%m-%d")
|
||||
total = 0
|
||||
with JOBS_LOCK:
|
||||
for j in JOBS.values():
|
||||
if j["key_id"] == key_id and j["day"] == day:
|
||||
total += int(j.get("spent_micros") or 0)
|
||||
return total
|
||||
|
||||
|
||||
def sanitize(obj):
|
||||
if isinstance(obj, str):
|
||||
s = obj
|
||||
for rx, repl in REDACT:
|
||||
s = rx.sub(repl, s)
|
||||
return s
|
||||
if isinstance(obj, list):
|
||||
return [sanitize(x) for x in obj]
|
||||
if isinstance(obj, dict):
|
||||
out = {}
|
||||
for k, v in obj.items():
|
||||
if k.lower() in ("password", "passwd", "secret", "cookie", "authorization", "set-cookie", "session"):
|
||||
out[k] = "<redacted>"
|
||||
else:
|
||||
out[k] = sanitize(v)
|
||||
return out
|
||||
return obj
|
||||
|
||||
|
||||
def target_reject_reason(url: str):
|
||||
try:
|
||||
u = urllib.parse.urlparse(url)
|
||||
except Exception:
|
||||
return "bad_url"
|
||||
if u.scheme != "https":
|
||||
return "https_only"
|
||||
host = (u.hostname or "").lower()
|
||||
if not host or PRIVATE_HOST.match(host) or "." not in host:
|
||||
return "private_or_local_host"
|
||||
for d in CFG.get("deny_target_hosts", []):
|
||||
if host == d or host.endswith("." + d):
|
||||
return "denied_host"
|
||||
return None
|
||||
|
||||
|
||||
def instruction_reject_reason(text: str):
|
||||
for pat in CFG.get("forbidden_instruction_patterns", []):
|
||||
if re.search(pat, text, re.I):
|
||||
return "credential_material_in_instruction"
|
||||
return None
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "iishko-sandbox/1.0"
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
pass
|
||||
|
||||
# -- helpers ----------------------------------------------------------
|
||||
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 > 64 * 1024:
|
||||
return None
|
||||
try:
|
||||
return json.loads(self.rfile.read(n).decode("utf-8"))
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
# -- routes -----------------------------------------------------------
|
||||
def do_GET(self):
|
||||
p = urllib.parse.urlparse(self.path).path
|
||||
if p == "/healthz":
|
||||
info = []
|
||||
for pool in POOLS:
|
||||
st, js = Offense(CFG["base_url"], pool["key"]).whoami()
|
||||
bal = (js.get("workspace") or {}).get("balanceMicros")
|
||||
info.append({"pool": pool["name"], "http": st, "balance_micros": bal})
|
||||
return self.send_json(200, {"ok": True, "pools": info, "jobs": len(JOBS)})
|
||||
key_id, why = self.auth()
|
||||
if not key_id:
|
||||
return self.send_json(401, {"error": why})
|
||||
uid, urec = key_id
|
||||
if p.startswith("/v1/jobs/"):
|
||||
jid = p.rsplit("/", 1)[-1]
|
||||
with JOBS_LOCK:
|
||||
job = JOBS.get(jid)
|
||||
if not job or job["key_id"] != uid:
|
||||
return self.send_json(404, {"error": "not_found"})
|
||||
return self.send_json(200, public_job(job))
|
||||
if p == "/v1/jobs":
|
||||
with JOBS_LOCK:
|
||||
mine = [public_job(j) for j in JOBS.values() if j["key_id"] == uid]
|
||||
return self.send_json(200, {"jobs": mine[-50:]})
|
||||
if p == "/v1/limits":
|
||||
return self.send_json(
|
||||
200,
|
||||
{
|
||||
"name": urec["name"],
|
||||
"daily_micros": urec["daily_micros"],
|
||||
"used_today_micros": today_spend(uid),
|
||||
"pool": urec["pool"],
|
||||
},
|
||||
)
|
||||
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/jobs":
|
||||
return self.create_job(uid, urec)
|
||||
if p.startswith("/v1/jobs/") and p.endswith("/cancel"):
|
||||
jid = p.split("/")[3]
|
||||
with JOBS_LOCK:
|
||||
job = JOBS.get(jid)
|
||||
if not job or job["key_id"] != uid:
|
||||
return self.send_json(404, {"error": "not_found"})
|
||||
pool = POOL_BY_NAME.get(job["pool"]) or POOLS[0]
|
||||
st, js = Offense(CFG["base_url"], pool["key"]).cancel(job["offense_id"])
|
||||
job["status"] = "cancelled"
|
||||
audit({"ev": "cancel", "job": jid, "http": st})
|
||||
return self.send_json(200, public_job(job))
|
||||
return self.send_json(404, {"error": "not_found"})
|
||||
|
||||
def create_job(self, uid, urec):
|
||||
body = self.body()
|
||||
if not body:
|
||||
return self.send_json(400, {"error": "bad_json"})
|
||||
target = (body.get("target") or "").strip()
|
||||
instruction = (body.get("instruction") or "").strip()
|
||||
if not target or not instruction:
|
||||
return self.send_json(400, {"error": "target_and_instruction_required"})
|
||||
if len(instruction) > 1800:
|
||||
return self.send_json(400, {"error": "instruction_too_long", "max": 1800})
|
||||
reason = target_reject_reason(target)
|
||||
if reason:
|
||||
audit({"ev": "deny_target", "reason": reason, "host": urllib.parse.urlparse(target).hostname})
|
||||
return self.send_json(403, {"error": "target_refused", "reason": reason})
|
||||
reason = instruction_reject_reason(instruction)
|
||||
if reason:
|
||||
audit({"ev": "deny_instruction", "reason": reason})
|
||||
return self.send_json(403, {"error": "instruction_refused", "reason": reason})
|
||||
budget = int(body.get("budget_micros") or CFG["default_budget_micros"])
|
||||
budget = max(50_000, min(budget, CFG["max_budget_micros"]))
|
||||
|
||||
used = today_spend(uid)
|
||||
if used + budget > urec["daily_micros"]:
|
||||
return self.send_json(429, {"error": "daily_quota", "used": used, "limit": urec["daily_micros"]})
|
||||
with JOBS_LOCK:
|
||||
running = [j for j in JOBS.values() if j["key_id"] == uid and j["status"] in ("queued", "running")]
|
||||
if len(running) >= CFG["max_concurrent_per_key"]:
|
||||
return self.send_json(429, {"error": "busy", "running": len(running)})
|
||||
|
||||
pool = POOL_BY_NAME.get(urec["pool"]) or POOLS[0]
|
||||
api = Offense(CFG["base_url"], pool["key"])
|
||||
|
||||
st, js = api.whoami()
|
||||
bal = (js.get("workspace") or {}).get("balanceMicros")
|
||||
if st != 200 or bal is None:
|
||||
return self.send_json(503, {"error": "pool_unavailable", "http": st})
|
||||
floor = int(CFG["min_balance_micros"])
|
||||
if int(bal) < max(floor, budget):
|
||||
return self.send_json(503, {"error": "credit_low", "balance_micros": bal, "need": max(floor, budget)})
|
||||
|
||||
with pool["lock"]: # one target per workspace
|
||||
st, js = api.target()
|
||||
tgt = ((js.get("targets") or [{}])[0] or {})
|
||||
cur = (tgt.get("target") or "").rstrip("/")
|
||||
if cur != target.rstrip("/") or not tgt.get("verified"):
|
||||
st, js = api.register_target(target, "iishko-user")
|
||||
if st not in (200, 201):
|
||||
return self.send_json(502, {"error": "target_register_failed", "http": st,
|
||||
"detail": sanitize(js).get("message")})
|
||||
tid = ((js.get("target") or {}).get("id")) or ""
|
||||
if not tid:
|
||||
return self.send_json(502, {"error": "target_register_empty"})
|
||||
st, js = api.verify_target(tid)
|
||||
if st != 200 or not (js.get("target") or {}).get("verified"):
|
||||
return self.send_json(409, {
|
||||
"error": "target_not_verified",
|
||||
"reason": (js.get("reason") or js.get("error") or "verification_failed"),
|
||||
"how": "Serve the token at <target>/.well-known/offense-verify.txt, then retry.",
|
||||
"token": ((tgt.get("verification") or {}).get("token")),
|
||||
})
|
||||
idem = "iishko-" + hashlib.sha256((uid + target + instruction + str(time.time())).encode()).hexdigest()[:40]
|
||||
st, js = api.launch(budget, instruction, (body.get("model") or "").strip(), idem)
|
||||
if st not in (200, 201):
|
||||
audit({"ev": "launch_fail", "http": st, "err": (sanitize(js).get("error") or "")[:80]})
|
||||
return self.send_json(502, {"error": "launch_failed", "http": st,
|
||||
"detail": sanitize(js).get("message") or sanitize(js).get("error")})
|
||||
a = js.get("assessment") or js
|
||||
jid = "job_" + hashlib.sha256(idem.encode()).hexdigest()[:16]
|
||||
job = {
|
||||
"id": jid,
|
||||
"key_id": uid,
|
||||
"user": urec["name"],
|
||||
"pool": pool["name"],
|
||||
"offense_id": a.get("id"),
|
||||
"target": target,
|
||||
"instruction_sha256": hashlib.sha256(instruction.encode()).hexdigest(),
|
||||
"budget_micros": budget,
|
||||
"spent_micros": 0,
|
||||
"status": a.get("status") or "queued",
|
||||
"created": int(time.time()),
|
||||
"day": time.strftime("%Y-%m-%d"),
|
||||
"error": None,
|
||||
}
|
||||
with JOBS_LOCK:
|
||||
JOBS[jid] = job
|
||||
audit({"ev": "launch", "job": jid, "user": urec["name"], "budget": budget,
|
||||
"target_host": urllib.parse.urlparse(target).hostname,
|
||||
"instruction_sha256": job["instruction_sha256"]})
|
||||
threading.Thread(target=poll_job, args=(jid,), daemon=True).start()
|
||||
return self.send_json(202, public_job(job))
|
||||
|
||||
|
||||
TERMINAL = ("completed", "failed", "cancelled", "canceled", "error")
|
||||
|
||||
|
||||
def poll_job(jid: str):
|
||||
job = JOBS.get(jid)
|
||||
if not job:
|
||||
return
|
||||
pool = POOL_BY_NAME.get(job["pool"]) or POOLS[0]
|
||||
api = Offense(CFG["base_url"], pool["key"])
|
||||
deadline = time.time() + 45 * 60
|
||||
while time.time() < deadline:
|
||||
time.sleep(10)
|
||||
st, js = api.assessment(job["offense_id"])
|
||||
if st != 200:
|
||||
continue
|
||||
a = js.get("assessment") or js
|
||||
job["status"] = a.get("status") or job["status"]
|
||||
job["spent_micros"] = int(a.get("spentMicros") or 0)
|
||||
if str(job["status"]).lower() in TERMINAL:
|
||||
break
|
||||
try:
|
||||
st, f = api.findings(job["offense_id"])
|
||||
job["findings"] = sanitize(f) if st == 200 else {"error": "findings_unavailable", "http": st}
|
||||
st, u = api.usage(job["offense_id"])
|
||||
job["usage"] = sanitize(u) if st == 200 else None
|
||||
except Exception:
|
||||
pass
|
||||
job["finished"] = int(time.time())
|
||||
audit({"ev": "finish", "job": jid, "status": job["status"], "spent": job["spent_micros"]})
|
||||
|
||||
|
||||
def public_job(job: dict) -> dict:
|
||||
out = {k: job.get(k) for k in ("id", "user", "status", "target", "budget_micros",
|
||||
"spent_micros", "created", "finished", "error")}
|
||||
if job.get("findings"):
|
||||
out["findings"] = job["findings"]
|
||||
if job.get("usage"):
|
||||
out["usage"] = job["usage"]
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
if not USER_KEYS:
|
||||
print("WARNING: keys.json missing/empty - every request will get 401", flush=True)
|
||||
srv = ThreadingHTTPServer((CFG["listen"], int(CFG["port"])), Handler)
|
||||
print("broker on http://%s:%s pools=%d keys=%d" % (CFG["listen"], CFG["port"], len(POOLS), len(USER_KEYS)), flush=True)
|
||||
srv.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"base_url": "https://app.offense.sh",
|
||||
"key_file": "offense_key.txt",
|
||||
"listen": "127.0.0.1",
|
||||
"port": 48970,
|
||||
"default_budget_micros": 200000,
|
||||
"max_budget_micros": 500000,
|
||||
"min_balance_micros": 300000,
|
||||
"max_concurrent_per_key": 1,
|
||||
"deny_target_hosts": [
|
||||
"reformboss.com",
|
||||
"api.reformboss.com",
|
||||
"iishko.dpdns.org",
|
||||
"2.27.98.196",
|
||||
"13.143.162.135",
|
||||
"144.31.34.147",
|
||||
"144.31.34.148",
|
||||
"144.31.34.149",
|
||||
"144.31.34.150",
|
||||
"93.88.206.29"
|
||||
],
|
||||
"forbidden_instruction_patterns": [
|
||||
"offense_sk_",
|
||||
"sk-[A-Za-z0-9]{20,}",
|
||||
"ck_[A-Za-z0-9]{10,}",
|
||||
"password",
|
||||
"api[_-]?key",
|
||||
"secret",
|
||||
"token"
|
||||
],
|
||||
"models": [
|
||||
""
|
||||
],
|
||||
"exec": {
|
||||
"listen": "127.0.0.1",
|
||||
"port": 48971,
|
||||
"code_max_bytes": 16000,
|
||||
"timeout_max_s": 120,
|
||||
"timeout_default_s": 60,
|
||||
"output_max_bytes": 16384,
|
||||
"daily_jobs_per_user": 200,
|
||||
"daily_cpu_seconds_per_user": 600,
|
||||
"pool_concurrency": 2,
|
||||
"template": "base"
|
||||
}
|
||||
}
|
||||
+333
@@ -0,0 +1,333 @@
|
||||
#!/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()
|
||||
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Self-test of the iishko sandbox broker (guard rails + optional live job).
|
||||
|
||||
python prove.py # guard-rail tests only (no credits burned)
|
||||
python prove.py --live URL # + real sandbox job against URL
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
BASE = "http://127.0.0.1:48970"
|
||||
KEY = open("keys_test.txt", encoding="utf-8").read().strip()
|
||||
|
||||
|
||||
def call(path, method="GET", body=None, key=KEY):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
req = urllib.request.Request(BASE + path, data=data, method=method, headers={
|
||||
"x-sandbox-key": key, "content-type": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=120) as r:
|
||||
return r.status, json.loads(r.read().decode() or "{}")
|
||||
except urllib.error.HTTPError as e:
|
||||
raw = e.read().decode()
|
||||
try:
|
||||
return e.code, json.loads(raw or "{}")
|
||||
except Exception:
|
||||
return e.code, {"raw": raw[:200]}
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
print(("PASS " if cond else "FAIL ") + name + (" | " + str(detail) if detail else ""))
|
||||
return cond
|
||||
|
||||
|
||||
ok = True
|
||||
st, js = call("/healthz", key="")
|
||||
ok &= check("healthz", st == 200 and js.get("ok") is True, js.get("pools"))
|
||||
st, js = call("/v1/limits", key="wrong-key")
|
||||
ok &= check("reject bad key", st == 401, js)
|
||||
st, js = call("/v1/jobs", "POST", {"target": "http://example.com", "instruction": "x"})
|
||||
ok &= check("reject http target", st == 403 and js.get("reason") == "https_only", js)
|
||||
st, js = call("/v1/jobs", "POST", {"target": "https://127.0.0.1/x", "instruction": "x"})
|
||||
ok &= check("reject local host", st == 403 and js.get("reason") in ("private_or_local_host", "https_only"), js)
|
||||
st, js = call("/v1/jobs", "POST", {"target": "https://api.reformboss.com", "instruction": "x"})
|
||||
ok &= check("reject our host", st == 403 and js.get("reason") == "denied_host", js)
|
||||
st, js = call("/v1/jobs", "POST", {"target": "https://example.com",
|
||||
"instruction": "use key sk-abcdefghijklmnopqrstuvwxyz123456"})
|
||||
ok &= check("reject secret in instruction", st == 403 and js.get("reason") == "credential_material_in_instruction", js)
|
||||
st, js = call("/v1/limits")
|
||||
ok &= check("limits endpoint", st == 200 and "used_today_micros" in js, js)
|
||||
|
||||
if "--live" in sys.argv:
|
||||
target = sys.argv[sys.argv.index("--live") + 1]
|
||||
st, js = call("/v1/jobs", "POST", {
|
||||
"target": target,
|
||||
"instruction": "Enumerate exposed paths and response headers, report missing security headers with evidence. Stay on this host.",
|
||||
"budget_micros": 200000})
|
||||
print("live launch:", st, json.dumps(js)[:400])
|
||||
if st in (200, 202):
|
||||
jid = js["id"]
|
||||
for _ in range(60):
|
||||
time.sleep(15)
|
||||
st, jj = call("/v1/jobs/" + jid)
|
||||
print("status", jj.get("status"), "spent", jj.get("spent_micros"))
|
||||
if str(jj.get("status")).lower() in ("completed", "failed", "cancelled", "canceled"):
|
||||
print(json.dumps(jj, ensure_ascii=False)[:2000])
|
||||
break
|
||||
else:
|
||||
ok = False
|
||||
|
||||
print("RESULT:", "OK" if ok else "FAILURES")
|
||||
sys.exit(0 if ok else 1)
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env python3
|
||||
"""prove_exec.py - acceptance tests for the E2B exec broker.
|
||||
|
||||
Must run under the native Python311. Starts the broker, fires real requests,
|
||||
verifies every guarantee. Exit 0 = all pass.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
PORT = 48971
|
||||
BASE = "http://127.0.0.1:%d" % PORT
|
||||
|
||||
keys = json.load(open(os.path.join(HERE, "keys.json"), encoding="utf-8"))
|
||||
if isinstance(keys, dict):
|
||||
keys = keys.get("keys", [])
|
||||
TOK = keys[0]["token"]
|
||||
|
||||
PROC = None
|
||||
|
||||
|
||||
def up():
|
||||
global PROC
|
||||
PROC = subprocess.Popen(
|
||||
[sys.executable, os.path.join(HERE, "exec_broker.py")],
|
||||
cwd=HERE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
text=True, encoding="utf-8", errors="replace")
|
||||
for _ in range(30):
|
||||
time.sleep(0.5)
|
||||
try:
|
||||
with urllib.request.urlopen(BASE + "/healthz", timeout=5) as r:
|
||||
if r.status == 200:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def call(method, path, body=None, token=TOK, timeout=200):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
req = urllib.request.Request(BASE + path, data=data, method=method)
|
||||
if token:
|
||||
req.add_header("x-sandbox-key", token)
|
||||
if data:
|
||||
req.add_header("content-type", "application/json")
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return r.status, json.loads(r.read().decode())
|
||||
except urllib.error.HTTPError as e:
|
||||
try:
|
||||
return e.code, json.loads(e.read().decode())
|
||||
except Exception:
|
||||
return e.code, {}
|
||||
|
||||
|
||||
def main():
|
||||
results = []
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
results.append((name, bool(cond), detail))
|
||||
print(("PASS" if cond else "FAIL"), name, (str(detail)[:160] if detail else ""), flush=True)
|
||||
|
||||
if not up():
|
||||
print("broker did not start")
|
||||
if PROC:
|
||||
print(PROC.stdout.read()[:2000])
|
||||
sys.exit(2)
|
||||
|
||||
st, h = call("GET", "/healthz", token=None)
|
||||
check("healthz", st == 200 and h.get("ok") and h["pool"]["keys"] >= 1, "keys=%s" % h.get("pool", {}).get("keys"))
|
||||
|
||||
# 1. real execution
|
||||
st, r = call("POST", "/v1/exec", {"code": "import platform\nprint('EXEC OK', 6*7, platform.python_version())"})
|
||||
check("exec_real", st == 200 and "42" in r.get("stdout", ""), "exit=%s out=%r" % (r.get("exit_code"), r.get("stdout", "")[:80]))
|
||||
|
||||
# 2. no egress from sandbox
|
||||
st, r = call("POST", "/v1/exec", {"code": "import urllib.request\ntry:\n print('LEAK', urllib.request.urlopen('http://api.ipify.org', timeout=8).read()[:40])\nexcept Exception as e:\n print('NET BLOCKED', type(e).__name__)"})
|
||||
check("egress_blocked", st == 200 and "NET BLOCKED" in r.get("stdout", "") and "LEAK" not in r.get("stdout", ""), r.get("stdout", "")[:80])
|
||||
|
||||
# 3. dns fails too (socket)
|
||||
st, r = call("POST", "/v1/exec", {"code": "import socket\ntry:\n print(socket.gethostbyname('e2b.dev'))\nexcept Exception as e:\n print('DNS BLOCKED', type(e).__name__)"})
|
||||
check("dns_blocked", "DNS BLOCKED" in r.get("stdout", ""), r.get("stdout", "")[:60])
|
||||
|
||||
# 4. secrets in code refused
|
||||
st, r = call("POST", "/v1/exec", {"code": "k='sk-abcdefghijklmnop1234567890'\nprint(len(k))"})
|
||||
check("deny_secret_code", st == 403 and r.get("error") == "code_refused", st)
|
||||
|
||||
# 5. e2b key in code refused
|
||||
st, r = call("POST", "/v1/exec", {"code": "K='e2b_0123456789abcdef0123456789abcdef'\nprint(K[:6])"})
|
||||
check("deny_e2b_key", st == 403, st)
|
||||
|
||||
# 6. output redaction (code passes, output contains key-shaped string)
|
||||
st, r = call("POST", "/v1/exec", {"code": "print('token: ghp_abcdefghijklmnopqrstuvwx1234567890abcd')"})
|
||||
check("output_redacted", st == 200 and "ghp_" not in r.get("stdout", ""), repr(r.get("stdout", ""))[:80])
|
||||
|
||||
# 7. wrong token
|
||||
st, r = call("POST", "/v1/exec", {"code": "print(1)"}, token="wrong-token")
|
||||
check("auth_401", st == 401, st)
|
||||
|
||||
# 8. code too large
|
||||
st, r = call("POST", "/v1/exec", {"code": "x=1\n" + "#" * 20000})
|
||||
check("code_too_large", st == 400 and r.get("error") == "code_too_large", st)
|
||||
|
||||
# 9. timeout enforcement (sleep 90 with timeout 10)
|
||||
t0 = time.time()
|
||||
st, r = call("POST", "/v1/exec", {"code": "import time\ntime.sleep(90)\nprint('NO TIMEOUT')", "timeout_s": 10}, timeout=120)
|
||||
dt = time.time() - t0
|
||||
check("timeout_kills", st == 200 and r.get("timeout") and "NO TIMEOUT" not in r.get("stdout", "") and dt < 70,
|
||||
"elapsed=%.1f status=%s timeout=%s" % (dt, st, r.get("timeout")))
|
||||
|
||||
# 10. limits endpoint
|
||||
st, r = call("GET", "/v1/limits")
|
||||
check("limits", st == 200 and "jobs_today" in r, r)
|
||||
|
||||
# 11. audit has no code, only sha
|
||||
audit_path = os.path.join(HERE, "state", "audit_exec.jsonl")
|
||||
raw = open(audit_path, encoding="utf-8").read()
|
||||
check("audit_no_payload", "EXEC OK" not in raw and "ghp_" not in raw and "code_sha256" in raw, "bytes=%d" % len(raw))
|
||||
|
||||
if PROC:
|
||||
PROC.terminate()
|
||||
try:
|
||||
PROC.wait(timeout=10)
|
||||
except Exception:
|
||||
PROC.kill()
|
||||
|
||||
fails = [n for n, ok, _ in results if not ok]
|
||||
print("TOTAL %d/%d PASS" % (len(results) - len(fails), len(results)))
|
||||
sys.exit(1 if fails else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,96 @@
|
||||
# sandbox_sup.py — держит живыми: (1) exec_broker.py (E2B, локально),
|
||||
# (2) reverse-тunnel home->VPS 127.0.0.1:48979 -> local 48971.
|
||||
# Запуск вручную или кроном Hermes (no_agent): python sandbox_sup.py
|
||||
import os, sys, time, json, subprocess, socket, urllib.request
|
||||
|
||||
HOME_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
PY311 = r"C:\Users\User\AppData\Local\Programs\Python\Python311\python.exe"
|
||||
CMD = r"C:\Windows\System32\cmd.exe"
|
||||
VPS = "root@2.27.98.196"
|
||||
VPS_FWD = "48979:127.0.0.1:48971" # VPS:48979 -> home:48971
|
||||
LOCAL_HEALTH = "http://127.0.0.1:48971/healthz"
|
||||
VPS_HEALTH = "http://127.0.0.1:48979/healthz"
|
||||
SSH_OPTS = ("-o StrictHostKeyChecking=no -o BatchMode=yes -o ServerAliveInterval=30 "
|
||||
"-o ServerAliveCountMax=3 -o ExitOnForwardFailure=yes -o ConnectTimeout=15")
|
||||
LOG = os.path.join(HOME_DIR, "sandbox_sup.log")
|
||||
DETACHED = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
|
||||
|
||||
def _ensure_winhome():
|
||||
# hermes-bash env lacks USERPROFILE -> native ssh.exe can't resolve ~/.ssh (rc 255, silent)
|
||||
if "USERPROFILE" not in os.environ:
|
||||
os.environ["USERPROFILE"] = r"C:\Users\User"
|
||||
os.environ["HOMEDRIVE"] = "C:"
|
||||
os.environ["HOMEPATH"] = r"\Users\User"
|
||||
os.environ["HOME"] = r"C:\Users\User"
|
||||
|
||||
_ensure_winhome()
|
||||
|
||||
def log(msg):
|
||||
with open(LOG, "a", encoding="utf-8") as f:
|
||||
f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} {msg}\n")
|
||||
|
||||
def http_ok(url, timeout=4):
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=timeout) as r:
|
||||
return r.status == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def kill_matching(substr):
|
||||
import psutil
|
||||
me = os.getpid()
|
||||
n = 0
|
||||
for p in psutil.process_iter(["pid", "cmdline"]):
|
||||
try:
|
||||
cl = " ".join(p.info["cmdline"] or [])
|
||||
except Exception:
|
||||
continue
|
||||
if substr in cl and p.info["pid"] != me and "sandbox_sup" not in cl:
|
||||
try:
|
||||
p.kill(); n += 1
|
||||
except Exception:
|
||||
pass
|
||||
return n
|
||||
|
||||
def vps_probe(timeout=45):
|
||||
# питфол: нативный python -> ssh.exe напрямую = rc 255 молча; только через cmd.exe.
|
||||
# Без кавычек и %{} в remote-команде: cmd.exe ест %, remote-bash ломается на вложенных кавычках.
|
||||
r = subprocess.run([CMD, "/c",
|
||||
"ssh %s %s curl -s -m 5 %s" % (SSH_OPTS, VPS, VPS_HEALTH)],
|
||||
capture_output=True, text=True, timeout=timeout, stdin=subprocess.DEVNULL)
|
||||
return '"ok": true' in (r.stdout or ""), r
|
||||
|
||||
def spawn_detached_cmd(cmdline):
|
||||
with open(os.path.join(HOME_DIR, "tunnel.log"), "ab") as fh:
|
||||
subprocess.Popen([CMD, "/c", cmdline], cwd=HOME_DIR, stdout=fh,
|
||||
stderr=subprocess.STDOUT, creationflags=DETACHED,
|
||||
stdin=subprocess.DEVNULL, close_fds=True)
|
||||
|
||||
def main():
|
||||
# 1) локальный брокер
|
||||
if http_ok(LOCAL_HEALTH):
|
||||
log("broker ok")
|
||||
else:
|
||||
kill_matching("exec_broker.py")
|
||||
time.sleep(1)
|
||||
spawn([PY311, os.path.join(HOME_DIR, "exec_broker.py")], out="broker.log")
|
||||
time.sleep(6)
|
||||
log("broker " + ("started" if http_ok(LOCAL_HEALTH) else "START FAILED"))
|
||||
|
||||
# 2) reverse-туннель на прод (проверяем с той стороны)
|
||||
ok, _ = vps_probe()
|
||||
if ok:
|
||||
log("tunnel ok")
|
||||
return
|
||||
kill_matching(VPS_FWD)
|
||||
time.sleep(1)
|
||||
spawn_detached_cmd("ssh %s -N -R %s %s" % (SSH_OPTS, VPS_FWD, VPS))
|
||||
time.sleep(8)
|
||||
ok, r = vps_probe()
|
||||
if ok:
|
||||
log("tunnel started")
|
||||
else:
|
||||
log("tunnel START FAILED rc=%s out=%r err=%r" % (r.returncode, r.stdout[:80], r.stderr[:120]))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user