#!/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()