Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienos.com/blob/main/scripts/allen/science/test_science_sandbox.py # aienos.com Source of www.aienos.com, served from my own hardware Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienos.com / scripts / allen / science / test_science_sandbox.py` 711 lines ยท 36460 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Boundary probes for allen-science: the per-request engine sandbox (science_sandbox.run_math), 3 the Omega compile path (run_omega, checked against the gateway it was copied from), and the 4 service sandbox built by launch.py. Every negative check has a positive control showing the probe 5 itself works (the same probe succeeds outside the sandbox, or a permitted action succeeds inside). 6 7 Host-only; needs no root and touches no live service. Usage: 8 python3 test_science_sandbox.py [--engine PATH] [--omc PATH] [--irwasm PATH] [--gateway DIR] 9 [--busybox PATH] [--service-port PORT] 10 --service-port runs the real allen_science.py next to this file through launch.py on that port 11 (it only accepts 127.0.0.1:18113) when the port is free. 12 """ 13 14 import argparse 15 import inspect 16 import json 17 import os 18 import shutil 19 import socket 20 import subprocess 21 import sys 22 import tempfile 23 import threading 24 import time 25 26 HERE = os.path.dirname(os.path.abspath(__file__)) 27 HOST_HOME = os.path.expanduser("~") # the running user's home: it exists outside and must be hidden inside 28 sys.path.insert(0, HERE) 29 import science_sandbox as ss # noqa: E402 30 31 ap = argparse.ArgumentParser() 32 ap.add_argument("--engine", default="/tmp/allen-science-math-release/build/aien-math") 33 ap.add_argument("--omc", default="/opt/allen-chat/omc") 34 ap.add_argument("--irwasm", default="/opt/allen-chat/irwasm") 35 ap.add_argument("--math-admit", default=os.path.join(HERE, "math-admit")) 36 ap.add_argument("--gateway", default="/tmp/allenchat/gw") 37 ap.add_argument("--busybox", default="/usr/bin/busybox") 38 ap.add_argument("--service-port", type=int, default=0) 39 A = ap.parse_args() 40 ss.AIEN_MATH, ss.OMC, ss.IRWASM, ss.MATH_ADMIT = A.engine, A.omc, A.irwasm, A.math_admit 41 ss.ENGINE_MANIFEST = os.path.join(HERE, "engine.json") 42 43 results = [] 44 45 46 def check(name, ok, detail=""): 47 results.append((name, bool(ok))) 48 print("%s %s: %s" % ("PASS" if ok else "FAIL", name, detail)) 49 50 51 def bare(expr, env=None): 52 """The engine with no sandbox: the positive control for every file/env probe.""" 53 p = subprocess.run([A.engine, "eval"], input=expr.encode(), capture_output=True, timeout=20, 54 env=env, cwd="/tmp") 55 return p.stdout.decode() 56 57 58 def listener(host): 59 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 60 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 61 s.bind((host, 0)) 62 s.listen(8) 63 64 def serve(): 65 while True: 66 try: 67 c, _ = s.accept() 68 except OSError: 69 return 70 c.sendall(b"HOSTSIDE\n") 71 c.close() 72 threading.Thread(target=serve, daemon=True).start() 73 return s, s.getsockname()[1] 74 75 76 def tailnet_ip(): 77 out = subprocess.run(["ip", "-4", "-o", "addr", "show", "scope", "global"], capture_output=True, 78 text=True).stdout 79 for line in out.split("\n"): 80 w = line.split() 81 if "inet" in w: 82 return w[w.index("inet") + 1].split("/")[0] 83 return None 84 85 86 def aien_math_procs(): 87 return subprocess.run(["pgrep", "-f", "^/aien-math eval"], capture_output=True).stdout.split() 88 89 90 def E(expr): 91 """The raw engine in its sandbox: no gate, no wrapper. math-admit refuses most probes below; 92 the sandbox must hold even for an expression the gate wrongly admitted.""" 93 text, failed = ss.engine_text(expr.encode()) 94 if failed: 95 return failed 96 at = text.rfind(ss.OUT_MARK) 97 value = text[at + len(ss.OUT_MARK):].rstrip("\n") if at >= 0 else "" 98 messages = [ln for ln in text.splitlines() if "::" in ln] 99 ok = at >= 0 and not messages and "$Failed" not in value 100 return {"ok": ok, "status": "ok" if ok else "unsupported", "output": value, "messages": messages} 101 102 103 # ---------------------------------------------------------------- 1. engine results 104 r = ss.run_math(ss.SELFTEST_MATH[0]) 105 check("symbolic fixture admitted and evaluated (control)", r["ok"] and r["output"] == ss.SELFTEST_MATH[1], r) 106 r = E("FooBar[x]") 107 check("raw engine: undefined symbol carries a message", not r["ok"] 108 and any(m.startswith("Symbol::undefined") for m in r["messages"]), r) 109 r = ss.run_math("Sin[x]") 110 check("unevaluated Sin[x] is unsupported", not r["ok"] and "unevaluated" in r.get("error", ""), r) 111 r = E("f[x_] := x^2; f[3]") 112 check("raw engine evaluates a compound statement (control for the probes below)", 113 r["ok"] and r["output"] == "9", r) 114 r = E("1+") 115 check("raw engine: syntax error is not ok", not r["ok"], r) 116 117 # ---------------------------------------------------------------- 1b. admission gate (math-admit) 118 fixtures = json.load(open(os.path.join(HERE, "admission-tests.json"))) 119 check("admission fixtures name the pinned gate", fixtures["binary_sha256"] == ss.MATH_ADMIT_PIN 120 and fixtures["compiler_sha256"] == ss.OMC_PIN, fixtures["binary_sha256"]) 121 wrong = [] 122 for case in fixtures["negative"]: 123 # run_math refuses (the NUL case already at the byte bound); the gate alone must refuse too. 124 r = ss.run_math(case["expression"]) 125 g = ss.admit(case["expression"].encode()) 126 if r["status"] != "refused" or not g or g.get("error") != ss.ADMIT_REFUSAL: 127 wrong.append((case["expression"], r["status"], g)) 128 check("run_math and the gate alone refuse every unsafe fixture (%d)" % len(fixtures["negative"]), 129 not wrong and fixtures["negative"], wrong) 130 for unsafe in ("Pause[30]", 'ReadString["/etc/hostname"]', 'Export["/tmp/x", 1]', 'Environment["HOME"]', 131 "FooBar[x]", "f[x_] := x^2; f[3]", "While[True, 1]", 'ToExpression["Run"]', "x++", "--x"): 132 r = ss.run_math(unsafe) 133 check("refused before the engine: %s" % unsafe, r["status"] == "refused", r) 134 for safe in ("Integrate[x^2, {x, 0, 1}]", "D[x^3, x]", "Factor[x^2 - 1]"): 135 r = ss.run_math(safe) 136 check("gate admits %s (control)" % safe, r["status"] not in ("refused", "error"), r) 137 for safe in ("x+1", "x-1"): 138 g = ss.admit(safe.encode()) 139 r = ss.run_math(safe) 140 check("gate alone admits %s (control for ++/--)" % safe, g is None and r["ok"], (g, r)) 141 for unsafe in ("x++", "--x"): 142 g = ss.admit(unsafe.encode()) 143 check("gate alone refuses %s" % unsafe, g is not None and g.get("error") == ss.ADMIT_REFUSAL, g) 144 145 # ---------------------------------------------------------------- 1c. result classifier 146 def wrapped_out(value): 147 return "Out[1]= %s%s%s\n" % (ss.COMPUTED[0], value, ss.COMPUTED[1]) 148 149 150 cases = [ 151 ("Out[1]= aienUnsupported\n", "unsupported"), 152 (wrapped_out("{Sin[x], Integrate[E^x^3, x]}"), "unsupported"), 153 (wrapped_out("{{x -> 1}, Solve[q, x]}"), "unsupported"), 154 (wrapped_out("$Failed"), "unsupported"), 155 ("Power::infy: Infinite expression 1/0 encountered.\n\n" + wrapped_out("ComplexInfinity"), "unsupported"), 156 ("Out[1]= {Sin[x]}\n", "unsupported"), 157 ("Out[1]= aienComputed[x\n", "unsupported"), 158 ("Out[1]= aienComputed[" + "a" * 4986 + " ... " + "b" * 4996 + "]\n", "unsupported"), 159 (wrapped_out("Sin[x]"), "ok"), 160 (wrapped_out("2*Cos[x]*Sin[x]"), "ok"), 161 (wrapped_out("c" * 9985), "ok"), 162 ] 163 got = [ss.parse_engine(t)[0] for t, _ in cases] 164 check("wrapper classifier: only a complete aienComputed[...] without messages, $Failed, residual " 165 "operations or printer cut is ok", got == [w for _, w in cases], got) 166 r = ss.run_math("Range[3000]") 167 check("real engine truncation (Range[3000]) is unsupported, not exact", r["status"] == "unsupported" 168 and r["output"] == "" and "cut" in r.get("error", ""), r) 169 for echo in ("{Sin[x]}", "List[Sin[x]]", "{ Sin[ x ] , 2 }", "List[Sin[x], 2]"): 170 r = ss.run_math(echo) 171 check("real structural echo %s is unsupported" % echo, r["status"] == "unsupported" 172 and "unevaluated" in r.get("error", ""), r) 173 for computed in (("D[Sin[x]^2, x]", "Sin[x]"), ("Plus[x, x]", "2*x"), ("List[Sin[x], 1+1]", "{Sin[x], 2}"), 174 ("x+1", "x"), ("Plus[x, 0]", "x"), ("x+0", "x"), ("Times[x, 1]", "x")): 175 r = ss.run_math(computed[0]) 176 check("real computed result %s is ok (control)" % computed[0], r["ok"] and computed[1] in r["output"], r) 177 for bad in ("x, y", "Sin[x]]", "{x", "Sin[x); y", "aienR", 'f["]'): 178 check("not one expression refused before any process: %r" % bad, not ss.single_expression(bad), bad) 179 check("one expression with commas inside brackets and strings passes (control)", 180 ss.single_expression('{Sin[x], 2, ","}') and ss.single_expression("Plus[x, 0]"), "") 181 check("wrapper text is internal: the computed output is the bare value", "aien" not in 182 ss.run_math("Plus[x, x]")["output"], "") 183 184 # ---------------------------------------------------------------- 2. input bounds never spawn 185 real_popen = subprocess.Popen 186 spawned = [] 187 subprocess.Popen = lambda *a, **k: spawned.append(a) or (_ for _ in ()).throw(AssertionError("spawned")) 188 refusals = [ss.run_math(x) for x in (None, b"1+1", "", " ", "1+\0" + "1", "x" * (ss.MAX_EXPR + 1), 189 "\ud800")] 190 subprocess.Popen = real_popen 191 check("bad inputs refused without a subprocess", 192 all(x["status"] == "refused" and not x["ok"] for x in refusals) and not spawned, 193 [x["error"] for x in refusals]) 194 r = ss.run_math("x" * (ss.MAX_EXPR - 10) + " + 0") 195 check("input at the cap passes the byte bound (control)", "longer than" not in r.get("error", ""), r) 196 197 # ---------------------------------------------------------------- 3. engine sandbox: filesystem 198 probe = 'ReadString["/etc/hostname"]' 199 outside = bare(probe) 200 r = E(probe) 201 check("host file unreadable inside (outside control reads it)", 202 not r["ok"] and "Out[1]= \"" in outside, "inside=%r outside=%r" % (r["output"], outside[-40:])) 203 for path in ("/etc/passwd", "/home", os.path.expanduser("~"), "/root", "/proc/self", "/dev/null", 204 "/opt/allen-science", "/usr"): 205 e = 'FileExistsQ["%s"]' % path 206 out_host = bare(e) 207 r = E(e) 208 check("%s invisible inside" % path, r["output"] == "False", 209 "inside=%s outside=%s" % (r["output"], out_host.strip().rsplit(" ", 1)[-1])) 210 r = E('Export["/tmp/ok.txt", "hi"]; ReadString["/tmp/ok.txt"]') 211 check("private tmpfs writable and readable (control)", r["ok"] and r["output"] == '"hi"', r) 212 r = E('Export["/tmp/ok.txt", "hi"]; FileExistsQ["/tmp/ok.txt"]') 213 r2 = E('FileExistsQ["/tmp/ok.txt"]') 214 check("tmpfs does not persist between requests", r["output"] == "True" and r2["output"] == "False", 215 "%s then %s" % (r["output"], r2["output"])) 216 for target in ("/evil.txt", "/aien-math"): 217 r = E('Export["%s", "x"]; FileByteCount["%s"]' % (target, target)) 218 check("write to %s refused" % target, r["output"] != "1", r["output"][:60]) 219 size = E('Export["/tmp/big.txt", StringRepeat["a", `3000000`]]; FileByteCount["/tmp/big.txt"]') 220 check("file size capped at 1 MiB", not size["ok"] or int(size["output"] or 0) <= 1 << 20, size) 221 222 # ---------------------------------------------------------------- 4. environment 223 env = dict(os.environ, SCIENCE_CANARY="should-not-leak") 224 outside = bare('Environment["SCIENCE_CANARY"]', env) 225 os.environ["SCIENCE_CANARY"] = "should-not-leak" 226 r = E('Environment["SCIENCE_CANARY"]') 227 r2 = E('Environment["HOME"]') 228 del os.environ["SCIENCE_CANARY"] 229 check("environment cleared (outside control sees the canary)", 230 "should-not-leak" in outside and "should-not-leak" not in json.dumps(r) and r2["output"] == "$Failed", 231 "inside=%r home=%r" % (r["output"], r2["output"])) 232 233 # ---------------------------------------------------------------- 5. time, CPU, output, memory 234 seen = [] 235 w = threading.Thread(target=lambda: (time.sleep(2), seen.append(aien_math_procs()))) 236 w.start() 237 t0 = time.monotonic() 238 r = E("Pause[30]; 1") 239 dt = time.monotonic() - t0 240 w.join() 241 time.sleep(0.5) 242 check("sleep killed at the wall clock", r["status"] == "timeout" and dt < ss.MATH_WALL_S + 2, "%.1fs" % dt) 243 check("engine visible while running (control)", bool(seen and seen[0]), seen) 244 check("no engine process survives the kill", not aien_math_procs(), aien_math_procs()) 245 t0 = time.monotonic() 246 r = E("While[True, 1]") 247 dt = time.monotonic() - t0 248 time.sleep(0.5) 249 check("CPU spin stopped within the wall clock and nothing survives", not r["ok"] and dt < ss.MATH_WALL_S + 2 250 and not aien_math_procs(), "%s %.1fs %s" % (r["status"], dt, r.get("error"))) 251 # The engine truncates a printed value at about 10000 characters itself; Print is not truncated. 252 r = E('Do[Print[StringRepeat["a", 5000]], {100}]; 1') 253 check("output past 64 KiB is cut off", r["status"] == "too_large", r["status"]) 254 r = E('Do[Print[StringRepeat["a", 50]], {10}]; StringLength[StringRepeat["ab", 100000]]') 255 check("same work with small output passes (control)", r["ok"] and r["output"] == "200000", r) 256 t0 = time.monotonic() 257 r = E("Length[Range[10^9]]") 258 check("huge allocation fails bounded", not r["ok"] and time.monotonic() - t0 < ss.MATH_WALL_S + 2, 259 "%s %s" % (r["status"], r.get("error"))) 260 r = E("Length[Range[10^5]]") 261 check("moderate allocation works (control)", r["ok"] and r["output"] == "100000", r) 262 263 # ---------------------------------------------------------------- 6. network, via busybox in the 264 # exact engine sandbox argv (the engine has no network builtins to probe with). 265 PRE = 'b() { (exec -a busybox /aien-math "$@"); }; ' 266 267 268 def in_engine_sandbox(script, wall=6): 269 argv = ss.math_argv(A.busybox, ["sh", "-c", PRE + script]) 270 i = argv.index("--") 271 argv[i:i] = ["--argv0", "busybox"] 272 st, out, err, rc = ss.run_bounded(ss.limited(ss.MATH_LIMITS, argv), b"", wall, 1 << 16, 4096) 273 return out.decode("utf-8", "replace") 274 275 276 o = in_engine_sandbox("echo ALIVE") 277 check("busybox probe runs in the engine sandbox (control)", o.strip() == "ALIVE", repr(o)) 278 lo, lo_port = listener("127.0.0.1") 279 tip = tailnet_ip() 280 tn, tn_port = listener(tip) if tip else (None, 0) 281 for host, port in (("127.0.0.1", lo_port), (tip, tn_port)): 282 if not host: 283 continue 284 o = in_engine_sandbox("b nc -w 2 %s %d &1; b env; echo END") 290 check("engine sandbox root holds only the engine and tmp, no /proc, /dev", 291 sorted(o.split("END")[0].split("\n")[0:2]) == ["aien-math", "tmp"] or 292 ("aien-math\ntmp" in o and "/proc" in o and "No such file" in o), repr(o[:200])) 293 o = in_engine_sandbox("b unshare -U b echo NESTED 2>&1; echo END") 294 check("nested user namespaces disabled", "NESTED" not in o.replace("b echo NESTED", ""), repr(o[:120])) 295 o = in_engine_sandbox("ulimit -t; ulimit -n; echo END") 296 check("prlimit applied the CPU and descriptor limits in the leaf", o.split()[:2] == ["5", "32"], repr(o)) 297 check("no Python pre-exec callback anywhere in the helper", "preexec" not in inspect.getsource(ss), "") 298 299 # ---------------------------------------------------------------- 6b. bounded collection (compiler path) 300 BB_PRE = 'b() { (exec -a busybox /tool "$@"); }; ' 301 302 303 def busybox_procs(): 304 return subprocess.run(["pgrep", "-f", "^busybox (yes|sleep 5|sh -c b)"], capture_output=True).stdout.split() 305 306 307 t0 = time.monotonic() 308 out, err, rc = ss.sandboxed(A.busybox, b"", 5, 1 << 20, args=("yes",), argv0="busybox") 309 check("compiler-path stdout flood stopped at the cap", out is None and err == b"output too large" 310 and time.monotonic() - t0 < 4, "%r %r %.1fs" % (err, rc, time.monotonic() - t0)) 311 t0 = time.monotonic() 312 st, out, err, rc = ss.run_bounded(ss.limited(ss.OMEGA_LIMITS, ss.sandbox_argv( 313 A.busybox, ("sh", "-c", BB_PRE + "b yes >&2"), "busybox")), b"", 2, 1 << 20, 4096) 314 check("stderr flood: kept to 4096 bytes and killed at the deadline", st == "timeout" and len(err) == 4096 315 and not out and time.monotonic() - t0 < 4, "%s err=%d %.1fs" % (st, len(err), time.monotonic() - t0)) 316 big = b"x" * (8 << 20) 317 out, err, rc = ss.sandboxed(A.busybox, big, 10, 1 << 20, args=("wc", "-c"), argv0="busybox") 318 check("8 MiB stdin fed without deadlock (control)", out is not None and out.strip() == b"`8388608`", (out, err, rc)) 319 t0 = time.monotonic() 320 out, err, rc = ss.sandboxed(A.busybox, big, 2, 1 << 20, args=("sleep", "5"), argv0="busybox") 321 check("unread 8 MiB stdin does not block past the deadline", out is None and err == b"timeout" 322 and time.monotonic() - t0 < 4, "%r %.1fs" % (err, time.monotonic() - t0)) 323 time.sleep(0.5) 324 check("no flood or sleep process survives", not busybox_procs(), busybox_procs()) 325 326 # ---------------------------------------------------------------- 7. Omega compile path parity 327 sys.path.insert(0, A.gateway) 328 import allen_chat as gw # noqa: E402 329 same = {k: getattr(gw, k) == getattr(ss, k) for k in 330 ("BWRAP", "OMC_PIN", "IRWASM_PIN", "MAX_SOURCE", "OMC_HINTS", "TYPES")} 331 same["OMC_ERR"] = gw.OMC_ERR.pattern == ss.OMC_ERR.pattern 332 same["NAME"] = gw.NAME.pattern == ss.NAME.pattern 333 same["signatures"] = inspect.getsource(gw.signatures) == inspect.getsource(ss.signatures) 334 335 336 class Spawned(Exception): 337 pass 338 339 340 def record(argv, **kw): 341 seen_argv.append(argv) 342 raise Spawned() 343 344 345 seen_argv = [] 346 347 348 def spawned_argv(mod): 349 seen_argv.clear() 350 real_popen = mod.subprocess.Popen 351 mod.subprocess.Popen = record 352 try: 353 mod.sandboxed("/x/tool", b"", 1, 1, args=("a", "b"), argv0="busybox") 354 except Spawned: 355 pass 356 finally: 357 mod.subprocess.Popen = real_popen 358 return list(seen_argv) 359 360 361 gw_argv, ss_argv = spawned_argv(gw), spawned_argv(ss) 362 same["argv"] = len(gw_argv) == 1 and gw_argv == ss_argv 363 check("omega path spawns exactly the gateway's argv (prlimit limits + bwrap) with its pins and hints", 364 all(same.values()), [k for k, v in same.items() if not v] or " ".join(ss_argv[0][:7])) 365 handler = inspect.getsource(gw.Handler.omega) if hasattr(gw, "Handler") else "" 366 check("gateway handler still uses sandboxed(app.omc/irwasm) as copied", 367 "sandboxed(app.omc, data, 5, 4 << 20)" in handler and "sandboxed(app.irwasm, ir, 5, 1 << 20)" in handler, 368 "handler found=%s" % bool(handler)) 369 good = "fn gcd a ulong b ulong to ulong\nwhile ne b 0\nt = rem a b\na = b\nb = t\nend\nret a\nend\n" 370 o = ss.run_omega(good) 371 check("omega gcd compiles to wasm (control)", o.get("ok") and o["functions"][0]["name"] == "gcd" 372 and __import__("base64").b64decode(o["wasm"])[:4] == b"\0asm", {k: o.get(k) for k in ("ok", "functions")}) 373 o = ss.run_omega("fn f a ulong to ulong\nx = add a 1 7\nret x\nend\n") 374 check("native pre-check refuses IR-accepted extra words", not o["ok"] and o["code"] == 5, o) 375 o = ss.run_omega("x" * (ss.MAX_SOURCE + 1)) 376 check("oversized Omega source refused", not o["ok"] and o["stage"] == "input", o["message"]) 377 378 # ---------------------------------------------------------------- 8. selftest, and pin failure 379 check("selftest passes with pinned tools (control)", ss.selftest() == [], "") 380 bad = tempfile.NamedTemporaryFile(delete=False) 381 bad.write(b"not the engine") 382 bad.close() 383 keep, ss.AIEN_MATH = ss.AIEN_MATH, bad.name 384 r = ss.run_math("1+1") 385 problems = ss.selftest() 386 ss.AIEN_MATH = keep 387 check("unpinned engine is refused (fail closed)", r["status"] == "error" and "engine" in r["error"] 388 and "pin" in r["error"] and problems, problems) 389 keep, ss.MATH_ADMIT = ss.MATH_ADMIT, bad.name 390 r = ss.run_math("1+1") 391 problems = ss.selftest() 392 ss.MATH_ADMIT = keep 393 os.unlink(bad.name) 394 check("unpinned admission gate is refused (fail closed)", r["status"] == "error" and "gate" in r["error"] 395 and problems, problems) 396 397 # ---------------------------------------------------------------- 8b. engine provenance manifest 398 check("shipped engine.json names the pinned engine (control)", ss.manifest_problem() is None, 399 ss.manifest_problem()) 400 good_manifest = json.load(open(ss.ENGINE_MANIFEST)) 401 bad_manifests = {"missing": None, "not JSON": "{", "stale commit": dict(good_manifest, commit="0" * 40), 402 "other binary": dict(good_manifest, binary_sha256="0" * 64), "array": []} 403 tmpdir = tempfile.mkdtemp(prefix="science-manifest-") 404 keep_manifest = ss.ENGINE_MANIFEST 405 for label, content in bad_manifests.items(): 406 path = os.path.join(tmpdir, label.replace(" ", "-") + ".json") 407 if content is not None: 408 with open(path, "w") as fh: 409 fh.write(content if isinstance(content, str) else json.dumps(content)) 410 ss.ENGINE_MANIFEST = path 411 ss._manifest.clear() 412 problems = ss.selftest() 413 r = ss.run_math(ss.SELFTEST_MATH[0]) 414 check("%s manifest refuses startup and every math request" % label, 415 any("manifest" in p for p in problems) and r["status"] == "error" and "manifest" in r["error"], 416 (problems, r.get("error"))) 417 ss.ENGINE_MANIFEST = keep_manifest 418 ss._manifest.clear() 419 shutil.rmtree(tmpdir) 420 421 # ---------------------------------------------------------------- 8c. installer (DESTDIR, no root) 422 def install(src_dir, destdir, engine=None): 423 env = {"PATH": "/usr/bin:/bin"} 424 if destdir is not None: 425 env["DESTDIR"] = destdir 426 return subprocess.run(["sh", os.path.join(src_dir, "install.sh"), engine or A.engine, A.omc, A.irwasm, 427 A.math_admit], capture_output=True, env=env, timeout=60) 428 429 430 def tree(d): 431 return sorted(os.path.relpath(os.path.join(p, n), d) for p, _, ns in os.walk(d) for n in ns) 432 433 434 inst = tempfile.mkdtemp(prefix="science-install-") 435 p = install(HERE, inst) 436 opt, gwdir = os.path.join(inst, "opt/allen-science"), os.path.join(inst, "opt/allen-chat") 437 same_bytes = lambda a, b: open(a, "rb").read() == open(b, "rb").read() 438 ok_pins = p.returncode == 0 and all(ss.sha256_file(os.path.join(opt, n)) == pin for n, pin in ( 439 ("aien-math", ss.AIEN_MATH_PIN), ("math-admit", ss.MATH_ADMIT_PIN), ("omc", ss.OMC_PIN), ("irwasm", ss.IRWASM_PIN))) 440 check("install places pinned tools and a valid manifest (control)", 441 ok_pins and ss.manifest_problem(os.path.join(opt, "engine.json")) is None, p.stderr.decode()[-200:]) 442 check("installed service and gateway science_protocol.py are byte-identical to the source (copies, not links)", 443 p.returncode == 0 and same_bytes(os.path.join(opt, "science_protocol.py"), os.path.join(HERE, "science_protocol.py")) 444 and same_bytes(os.path.join(gwdir, "science_protocol.py"), os.path.join(HERE, "science_protocol.py")) 445 and not os.path.islink(os.path.join(gwdir, "science_protocol.py")), tree(inst)) 446 stale_src = tempfile.mkdtemp(prefix="science-stale-") 447 for n in os.listdir(HERE): 448 if os.path.isfile(os.path.join(HERE, n)): 449 shutil.copy2(os.path.join(HERE, n), os.path.join(stale_src, n)) 450 with open(os.path.join(stale_src, "engine.json"), "w") as fh: 451 json.dump(dict(good_manifest, commit="0" * 40), fh) 452 dest2 = tempfile.mkdtemp(prefix="science-install-") 453 p = install(stale_src, dest2) 454 check("install refuses a stale manifest and writes nothing", p.returncode != 0 and b"manifest" in p.stderr 455 and tree(dest2) == [], p.stderr.decode().strip()[-160:]) 456 os.unlink(os.path.join(stale_src, "engine.json")) 457 p = install(stale_src, dest2) 458 check("install refuses a missing manifest and writes nothing", p.returncode != 0 and b"manifest" in p.stderr 459 and tree(dest2) == [], p.stderr.decode().strip()[-160:]) 460 p = install(HERE, dest2, engine=A.math_admit) 461 check("install refuses an engine that is not the pinned one", p.returncode != 0 and b"pinned" in p.stderr 462 and tree(dest2) == [], p.stderr.decode().strip()[-160:]) 463 p = install(HERE, None) 464 check("install without DESTDIR requires root", (os.getuid() == 0) or (p.returncode != 0 and b"root" in p.stderr), 465 p.stderr.decode().strip()) 466 for d in (inst, stale_src, dest2): 467 shutil.rmtree(d) 468 469 # ---------------------------------------------------------------- 9. service sandbox (launch.py) 470 PROBE_SERVICE = r''' 471 import os 472 def is_open(n): 473 try: 474 os.fstat(n) 475 return True 476 except OSError: 477 return False 478 open_fds = [n for n in range(1024) if is_open(n)] 479 import json, socket, sys 480 sys.path.insert(0, "/opt/allen-science") 481 import science_sandbox as ss 482 fd = int(sys.argv[sys.argv.index("--listen-fd") + 1]) 483 lo_port, tn_host, tn_port = int(sys.argv[-3]), sys.argv[-2], int(sys.argv[-1]) 484 f = {"fds": open_fds} 485 def attempt(fn): 486 try: 487 return fn() 488 except Exception as e: 489 return "ERR %s" % type(e).__name__ 490 def connect(h, p): 491 s = socket.socket(); s.settimeout(2); s.connect((h, p)); d = s.recv(64); s.close(); return d.decode() 492 def write(p): 493 with open(p, "w") as fh: 494 fh.write("x") 495 return "WROTE" 496 f["uid"] = os.getuid() 497 f["env"] = dict(os.environ) 498 f["root"] = sorted(os.listdir("/")) 499 f["home"] = sorted(os.listdir("/home")) 500 for p in ("/etc/passwd", "/etc/shadow", "/root", "/var", "/run", "@HOST_HOME@", "/usr/bin/curl", 501 "/usr/bin/sudo", "/usr/lib/python3/dist-packages", "/tmp/aien-gb10.lock"): 502 f["exists " + p] = os.path.exists(p) 503 f["write /"] = attempt(lambda: write("/evil")) 504 f["write opt"] = attempt(lambda: write("/opt/allen-science/evil")) 505 f["write usr"] = attempt(lambda: write("/usr/lib/python3.12/evil")) 506 f["write tmp"] = attempt(lambda: write("/tmp/ok")) 507 f["write home"] = attempt(lambda: write(os.environ["HOME"] + "/ok")) 508 f["loopback out"] = attempt(lambda: connect("127.0.0.1", lo_port)) 509 f["tailnet out"] = attempt(lambda: connect(tn_host, tn_port)) if tn_port else "skipped" 510 f["internet out"] = attempt(lambda: connect("1.1.1.1", 443)) 511 f["pids"] = sorted(int(p) for p in os.listdir("/proc") if p.isdigit()) 512 f["capeff"] = [l.split()[1] for l in open("/proc/self/status") if l.startswith("CapEff")][0] 513 f["nnp"] = [l.split()[1] for l in open("/proc/self/status") if l.startswith("NoNewPrivs")][0] 514 f["math"] = ss.run_math(ss.SELFTEST_MATH[0]) 515 f["math file"] = ss.evaluate('FileExistsQ["/opt/allen-science/aien-math"]', b'FileExistsQ["/opt/allen-science/aien-math"]') 516 f["math run"] = ss.run_math("Run[x]") 517 f["omega"] = {k: v for k, v in ss.run_omega(ss.SELFTEST_OMEGA).items() if k != "wasm"} 518 f["selftest"] = ss.selftest() 519 srv = socket.socket(fileno=fd) 520 f["listen"] = list(srv.getsockname()) 521 body = json.dumps(f).encode() 522 while True: 523 c, _ = srv.accept() 524 c.sendall(body) 525 c.close() 526 ''' 527 528 529 def free_port(): 530 s = socket.socket() 531 s.bind(("127.0.0.1", 0)) 532 p = s.getsockname()[1] 533 s.close() 534 return p 535 536 537 def wait_body(port, proc, seconds=30): 538 end = time.monotonic() + seconds 539 while time.monotonic() < end and proc.poll() is None: 540 try: 541 c = socket.create_connection(("127.0.0.1", port), timeout=1) 542 c.settimeout(20) 543 data = b"" 544 while True: 545 d = c.recv(65536) 546 if not d: 547 break 548 data += d 549 c.close() 550 return data 551 except OSError: 552 time.sleep(0.2) 553 return None 554 555 556 def stop(proc): 557 if proc.poll() is None: 558 proc.kill() 559 proc.wait() 560 561 562 root = tempfile.mkdtemp(prefix="science-root-") 563 for src, name in ((os.path.join(HERE, "science_sandbox.py"), "science_sandbox.py"), (A.engine, "aien-math"), 564 (A.omc, "omc"), (A.irwasm, "irwasm"), (A.math_admit, "math-admit"), 565 (os.path.join(HERE, "engine.json"), "engine.json")): 566 shutil.copy2(src, os.path.join(root, name)) 567 with open(os.path.join(root, "allen_science.py"), "w") as fh: 568 fh.write(PROBE_SERVICE.replace("@HOST_HOME@", HOST_HOME)) 569 os.chmod(root, 0o755) 570 port = free_port() 571 canary_env = dict(os.environ, SCIENCE_CANARY="should-not-leak", ALLEN_UPSTREAM_TOKEN="should-not-leak") 572 canary_r, canary_w = os.pipe() 573 canary_sock = socket.socket() 574 HIGH_FD = 900 575 os.dup2(canary_r, HIGH_FD) 576 # The launcher starts with soft RLIMIT_NOFILE 64 and a descriptor numbered 900 above it: a 577 # closerange up to the soft limit would leave it open. 578 launch_argv = ["/usr/bin/prlimit", "--nofile=64:4096", "--", sys.executable, "-I", 579 os.path.join(HERE, "launch.py"), "--listen", "127.0.0.1:%d" % port, 580 "--root", root, "--", str(lo_port), tip or "", str(tn_port)] 581 ctl = subprocess.run(["/usr/bin/prlimit", "--nofile=64:4096", "--", sys.executable, "-I", "-c", 582 "import os, resource; print(os.path.exists('/proc/self/fd/%d'), " 583 "resource.getrlimit(resource.RLIMIT_NOFILE)[0])" % HIGH_FD], 584 capture_output=True, text=True, pass_fds=(HIGH_FD,)).stdout.split() 585 check("high fd control: fd %d is open in a child whose soft limit is lower" % HIGH_FD, 586 ctl == ["True", "64"], ctl) 587 proc = subprocess.Popen(launch_argv, env=canary_env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, 588 pass_fds=(canary_r, canary_w, canary_sock.fileno(), HIGH_FD)) 589 passed_fds = sorted((canary_r, canary_w, canary_sock.fileno(), HIGH_FD)) 590 os.close(HIGH_FD) 591 data = wait_body(port, proc) 592 stop(proc) 593 log = proc.stdout.read().decode("utf-8", "replace") 594 f = json.loads(data) if data else {} 595 check("service reachable inbound over loopback via the inherited socket (control)", bool(f), 596 "launcher output: %r" % log[-400:]) 597 if f: 598 check("service runs unprivileged, same uid, no capabilities, no_new_privs", 599 f["uid"] == os.getuid() and f["capeff"] == "`0000000000000000`" and f["nnp"] == "1", 600 "uid=%s capeff=%s nnp=%s" % (f["uid"], f["capeff"], f["nnp"])) 601 check("only stdin, stdout, stderr and the listener reach the service (canary fds %s passed in)" % passed_fds, 602 f["fds"] == [0, 1, 2, 3] and all(n > 3 for n in passed_fds), f["fds"]) 603 # bwrap sets PWD for --chdir; it holds the private home, nothing from the host. 604 check("environment is only HOME, LANG, PATH, PWD (launcher canaries absent)", 605 f["env"] == {"HOME": "/home/allen-science", "LANG": "C.UTF-8", "PATH": "/usr/bin:/bin", 606 "PWD": "/home/allen-science"}, f["env"]) 607 check("root holds only the bound tree", f["root"] == ["bin", "dev", "home", "lib", "opt", "proc", "tmp", "usr"], 608 f["root"]) 609 check("/home holds only the private home", f["home"] == ["allen-science"], f["home"]) 610 hidden = {k: v for k, v in f.items() if k.startswith("exists ")} 611 host = {k: os.path.exists(k[7:]) for k in hidden} 612 check("host credentials and files invisible (they exist outside)", 613 not any(hidden.values()) and host["exists /etc/passwd"] and host["exists " + HOST_HOME], 614 "inside=%s outside=%s" % ([k for k, v in hidden.items() if v], [k for k, v in host.items() if v])) 615 check("read-only root, install dir and stdlib", 616 all(f[k].startswith("ERR") for k in ("write /", "write opt", "write usr")), 617 [f[k] for k in ("write /", "write opt", "write usr")]) 618 check("private /tmp and HOME writable (control)", f["write tmp"] == "WROTE" and f["write home"] == "WROTE", 619 [f["write tmp"], f["write home"]]) 620 lo_out = socket.create_connection(("127.0.0.1", lo_port), timeout=2).recv(64).decode() 621 check("no outbound loopback from the service (host control reaches it)", 622 f["loopback out"].startswith("ERR") and "HOSTSIDE" in lo_out, [f["loopback out"], lo_out.strip()]) 623 if tip: 624 tn_out = socket.create_connection((tip, tn_port), timeout=2).recv(64).decode() 625 check("no outbound tailnet from the service (host control reaches it)", 626 f["tailnet out"].startswith("ERR") and "HOSTSIDE" in tn_out, [f["tailnet out"], tn_out.strip()]) 627 check("no outbound internet from the service", f["internet out"].startswith("ERR"), f["internet out"]) 628 check("own pid namespace", len(f["pids"]) <= 4 and max(f["pids"]) < 50, f["pids"]) 629 check("nested engine sandbox works inside the service sandbox", f["math"]["ok"] 630 and f["math"]["output"] == ss.SELFTEST_MATH[1], f["math"]) 631 check("engine cannot see the service's install dir", f["math file"]["output"] == "False", f["math file"]) 632 check("nested admission gate refuses Run[x] inside the service sandbox", 633 f["math run"]["status"] == "refused" and f["math run"].get("error") == ss.ADMIT_REFUSAL, f["math run"]) 634 check("nested Omega compile works inside the service sandbox", f["omega"].get("ok"), f["omega"]) 635 check("selftest passes inside the service sandbox", f["selftest"] == [], f["selftest"]) 636 p = subprocess.run([sys.executable, "-I", os.path.join(HERE, "launch.py"), "--listen", "0.0.0.0:%d" % free_port(), 637 "--root", root], capture_output=True, timeout=20) 638 check("launcher refuses a non-loopback listen address", p.returncode != 0 and b"127.0.0.1" in p.stderr, 639 p.stderr.decode().strip()) 640 641 # ---------------------------------------------------------------- 10. the real service, optional 642 if A.service_port: 643 taken = subprocess.run(["ss", "-ltnH", "sport = :%d" % A.service_port], capture_output=True).stdout.strip() 644 if taken: 645 print("NOT_RUN real service: port %d in use" % A.service_port) 646 else: 647 real = tempfile.mkdtemp(prefix="science-real-") 648 for name in os.listdir(root): 649 if name != "allen_science.py": 650 shutil.copy2(os.path.join(root, name), os.path.join(real, name)) 651 for name in ("allen_science.py", "science_protocol.py", "engine.json"): 652 if os.path.exists(os.path.join(HERE, name)): 653 shutil.copy2(os.path.join(HERE, name), os.path.join(real, name)) 654 os.chmod(real, 0o755) 655 proc = subprocess.Popen([sys.executable, "-I", os.path.join(HERE, "launch.py"), "--listen", 656 "127.0.0.1:%d" % A.service_port, "--root", real], 657 stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 658 up = False 659 end = time.monotonic() + 30 660 while time.monotonic() < end and proc.poll() is None and not up: 661 try: 662 socket.create_connection(("127.0.0.1", A.service_port), timeout=1).close() 663 up = True 664 except OSError: 665 time.sleep(0.2) 666 time.sleep(2) 667 alive = proc.poll() is None 668 669 def compute(tool, arguments): 670 body = json.dumps({"tool": tool, "arguments": arguments}).encode() 671 c = socket.create_connection(("127.0.0.1", A.service_port), timeout=30) 672 c.sendall(b"POST /compute HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\n" 673 b"Connection: close\r\nContent-Length: %d\r\n\r\n" % len(body) + body) 674 data = b"" 675 while True: 676 d = c.recv(65536) 677 if not d: 678 break 679 data += d 680 c.close() 681 head, _, payload = data.partition(b"\r\n\r\n") 682 return head.split(b"\r\n")[0].decode(), payload.decode("utf-8", "replace") 683 684 computed = unsupported = refused = compiled = ("", "") 685 if up and alive: 686 computed = compute("math_compute", {"title": "fixture", "expression": ss.SELFTEST_MATH[0]}) 687 unsupported = compute("math_compute", {"title": "nested echo", "expression": "{Sin[x]}"}) 688 refused = compute("math_compute", {"title": "unsafe", "expression": "Run[x]"}) 689 compiled = compute("omega_compile", {"title": "f", "source": ss.SELFTEST_OMEGA}) 690 stop(proc) 691 out = proc.stdout.read().decode("utf-8", "replace") 692 check("real allen_science.py starts in the launcher sandbox (selftest passed, accepting)", 693 up and alive, "output=%r" % out[-400:]) 694 check("real /compute math: computed with the pinned commit", " 200 " in computed[0] 695 and '"computed"' in computed[1] and ss.SELFTEST_MATH[1] in computed[1] 696 and ss.ENGINE_COMMIT in computed[1], computed[0] + " " + computed[1][:300]) 697 check("real /compute nested echo {Sin[x]} is not computed", '"computed"' not in unsupported[1] 698 and '"unsupported"' in unsupported[1], unsupported[0] + " " + unsupported[1][:200]) 699 check("real /compute Run[x] is refused, never computed", '"computed"' not in refused[1] 700 and refused[0] != "", refused[0] + " " + refused[1][:200]) 701 check("real /compute omega_compile returns wasm", " 200 " in compiled[0] and '"wasm"' in compiled[1], 702 compiled[0] + " " + compiled[1][:200]) 703 shutil.rmtree(real) 704 shutil.rmtree(root) 705 lo.close() 706 if tn: 707 tn.close() 708 709 failed = [n for n, ok in results if not ok] 710 print("%d/%d passed" % (len(results) - len(failed), len(results))) 711 sys.exit(1 if failed else 0)