interplane.Get Omega
Read in your language

aienos.com

Source of www.aienos.com, served from my own hardware

Brought by drakestapleton

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),
3the Omega compile path (run_omega, checked against the gateway it was copied from), and the
4service sandbox built by launch.py. Every negative check has a positive control showing the probe
5itself works (the same probe succeeds outside the sandbox, or a permitted action succeeds inside).
6
7Host-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
14import argparse
15import inspect
16import json
17import os
18import shutil
19import socket
20import subprocess
21import sys
22import tempfile
23import threading
24import time
25
26HERE = os.path.dirname(os.path.abspath(__file__))
27HOST_HOME = os.path.expanduser("~") # the running user's home: it exists outside and must be hidden inside
28sys.path.insert(0, HERE)
29import science_sandbox as ss # noqa: E402
30
31ap = argparse.ArgumentParser()
32ap.add_argument("--engine", default="/tmp/allen-science-math-release/build/aien-math")
33ap.add_argument("--omc", default="/opt/allen-chat/omc")
34ap.add_argument("--irwasm", default="/opt/allen-chat/irwasm")
35ap.add_argument("--math-admit", default=os.path.join(HERE, "math-admit"))
36ap.add_argument("--gateway", default="/tmp/allenchat/gw")
37ap.add_argument("--busybox", default="/usr/bin/busybox")
38ap.add_argument("--service-port", type=int, default=0)
39A = ap.parse_args()
40ss.AIEN_MATH, ss.OMC, ss.IRWASM, ss.MATH_ADMIT = A.engine, A.omc, A.irwasm, A.math_admit
41ss.ENGINE_MANIFEST = os.path.join(HERE, "engine.json")
42
43results = []
44
45
46def check(name, ok, detail=""):
47 results.append((name, bool(ok)))
48 print("%s %s: %s" % ("PASS" if ok else "FAIL", name, detail))
49
50
51def 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
58def 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
76def 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
86def aien_math_procs():
87 return subprocess.run(["pgrep", "-f", "^/aien-math eval"], capture_output=True).stdout.split()
88
89
90def 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
104r = ss.run_math(ss.SELFTEST_MATH[0])
105check("symbolic fixture admitted and evaluated (control)", r["ok"] and r["output"] == ss.SELFTEST_MATH[1], r)
106r = E("FooBar[x]")
107check("raw engine: undefined symbol carries a message", not r["ok"]
108 and any(m.startswith("Symbol::undefined") for m in r["messages"]), r)
109r = ss.run_math("Sin[x]")
110check("unevaluated Sin[x] is unsupported", not r["ok"] and "unevaluated" in r.get("error", ""), r)
111r = E("f[x_] := x^2; f[3]")
112check("raw engine evaluates a compound statement (control for the probes below)",
113 r["ok"] and r["output"] == "9", r)
114r = E("1+")
115check("raw engine: syntax error is not ok", not r["ok"], r)
116
117# ---------------------------------------------------------------- 1b. admission gate (math-admit)
118fixtures = json.load(open(os.path.join(HERE, "admission-tests.json")))
119check("admission fixtures name the pinned gate", fixtures["binary_sha256"] == ss.MATH_ADMIT_PIN
120 and fixtures["compiler_sha256"] == ss.OMC_PIN, fixtures["binary_sha256"])
121wrong = []
122for 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))
128check("run_math and the gate alone refuse every unsafe fixture (%d)" % len(fixtures["negative"]),
129 not wrong and fixtures["negative"], wrong)
130for 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)
134for 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)
137for 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))
141for 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
146def wrapped_out(value):
147 return "Out[1]= %s%s%s\n" % (ss.COMPUTED[0], value, ss.COMPUTED[1])
148
149
150cases = [
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]
163got = [ss.parse_engine(t)[0] for t, _ in cases]
164check("wrapper classifier: only a complete aienComputed[...] without messages, $Failed, residual "
165 "operations or printer cut is ok", got == [w for _, w in cases], got)
166r = ss.run_math("Range[3000]")
167check("real engine truncation (Range[3000]) is unsupported, not exact", r["status"] == "unsupported"
168 and r["output"] == "" and "cut" in r.get("error", ""), r)
169for 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)
173for 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)
177for 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)
179check("one expression with commas inside brackets and strings passes (control)",
180 ss.single_expression('{Sin[x], 2, ","}') and ss.single_expression("Plus[x, 0]"), "")
181check("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
185real_popen = subprocess.Popen
186spawned = []
187subprocess.Popen = lambda *a, **k: spawned.append(a) or (_ for _ in ()).throw(AssertionError("spawned"))
188refusals = [ss.run_math(x) for x in (None, b"1+1", "", " ", "1+\0" + "1", "x" * (ss.MAX_EXPR + 1),
189 "\ud800")]
190subprocess.Popen = real_popen
191check("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])
194r = ss.run_math("x" * (ss.MAX_EXPR - 10) + " + 0")
195check("input at the cap passes the byte bound (control)", "longer than" not in r.get("error", ""), r)
196
197# ---------------------------------------------------------------- 3. engine sandbox: filesystem
198probe = 'ReadString["/etc/hostname"]'
199outside = bare(probe)
200r = E(probe)
201check("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:]))
203for 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]))
210r = E('Export["/tmp/ok.txt", "hi"]; ReadString["/tmp/ok.txt"]')
211check("private tmpfs writable and readable (control)", r["ok"] and r["output"] == '"hi"', r)
212r = E('Export["/tmp/ok.txt", "hi"]; FileExistsQ["/tmp/ok.txt"]')
213r2 = E('FileExistsQ["/tmp/ok.txt"]')
214check("tmpfs does not persist between requests", r["output"] == "True" and r2["output"] == "False",
215 "%s then %s" % (r["output"], r2["output"]))
216for 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])
219size = E('Export["/tmp/big.txt", StringRepeat["a", 3000000]]; FileByteCount["/tmp/big.txt"]')
220check("file size capped at 1 MiB", not size["ok"] or int(size["output"] or 0) <= 1 << 20, size)
221
222# ---------------------------------------------------------------- 4. environment
223env = dict(os.environ, SCIENCE_CANARY="should-not-leak")
224outside = bare('Environment["SCIENCE_CANARY"]', env)
225os.environ["SCIENCE_CANARY"] = "should-not-leak"
226r = E('Environment["SCIENCE_CANARY"]')
227r2 = E('Environment["HOME"]')
228del os.environ["SCIENCE_CANARY"]
229check("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
234seen = []
235w = threading.Thread(target=lambda: (time.sleep(2), seen.append(aien_math_procs())))
236w.start()
237t0 = time.monotonic()
238r = E("Pause[30]; 1")
239dt = time.monotonic() - t0
240w.join()
241time.sleep(0.5)
242check("sleep killed at the wall clock", r["status"] == "timeout" and dt < ss.MATH_WALL_S + 2, "%.1fs" % dt)
243check("engine visible while running (control)", bool(seen and seen[0]), seen)
244check("no engine process survives the kill", not aien_math_procs(), aien_math_procs())
245t0 = time.monotonic()
246r = E("While[True, 1]")
247dt = time.monotonic() - t0
248time.sleep(0.5)
249check("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.
252r = E('Do[Print[StringRepeat["a", 5000]], {100}]; 1')
253check("output past 64 KiB is cut off", r["status"] == "too_large", r["status"])
254r = E('Do[Print[StringRepeat["a", 50]], {10}]; StringLength[StringRepeat["ab", 100000]]')
255check("same work with small output passes (control)", r["ok"] and r["output"] == "200000", r)
256t0 = time.monotonic()
257r = E("Length[Range[10^9]]")
258check("huge allocation fails bounded", not r["ok"] and time.monotonic() - t0 < ss.MATH_WALL_S + 2,
259 "%s %s" % (r["status"], r.get("error")))
260r = E("Length[Range[10^5]]")
261check("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).
265PRE = 'b() { (exec -a busybox /aien-math "$@"); }; '
266
267
268def 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
276o = in_engine_sandbox("echo ALIVE")
277check("busybox probe runs in the engine sandbox (control)", o.strip() == "ALIVE", repr(o))
278lo, lo_port = listener("127.0.0.1")
279tip = tailnet_ip()
280tn, tn_port = listener(tip) if tip else (None, 0)
281for 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 </dev/null; echo rc=$?" % (host, port))
285 c = subprocess.run([A.busybox, "nc", "-w", "2", host, str(port)], capture_output=True,
286 stdin=subprocess.DEVNULL, timeout=10).stdout.decode()
287 check("engine sandbox cannot reach %s:%d (outside control reaches it)" % (host, port),
288 "HOSTSIDE" not in o and "HOSTSIDE" in c, "inside=%r outside=%r" % (o.strip()[-40:], c.strip()))
289o = in_engine_sandbox("b ls / /proc /dev 2>&1; b env; echo END")
290check("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]))
293o = in_engine_sandbox("b unshare -U b echo NESTED 2>&1; echo END")
294check("nested user namespaces disabled", "NESTED" not in o.replace("b echo NESTED", ""), repr(o[:120]))
295o = in_engine_sandbox("ulimit -t; ulimit -n; echo END")
296check("prlimit applied the CPU and descriptor limits in the leaf", o.split()[:2] == ["5", "32"], repr(o))
297check("no Python pre-exec callback anywhere in the helper", "preexec" not in inspect.getsource(ss), "")
298
299# ---------------------------------------------------------------- 6b. bounded collection (compiler path)
300BB_PRE = 'b() { (exec -a busybox /tool "$@"); }; '
301
302
303def busybox_procs():
304 return subprocess.run(["pgrep", "-f", "^busybox (yes|sleep 5|sh -c b)"], capture_output=True).stdout.split()
305
306
307t0 = time.monotonic()
308out, err, rc = ss.sandboxed(A.busybox, b"", 5, 1 << 20, args=("yes",), argv0="busybox")
309check("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))
311t0 = time.monotonic()
312st, 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)
314check("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))
316big = b"x" * (8 << 20)
317out, err, rc = ss.sandboxed(A.busybox, big, 10, 1 << 20, args=("wc", "-c"), argv0="busybox")
318check("8 MiB stdin fed without deadlock (control)", out is not None and out.strip() == b"8388608", (out, err, rc))
319t0 = time.monotonic()
320out, err, rc = ss.sandboxed(A.busybox, big, 2, 1 << 20, args=("sleep", "5"), argv0="busybox")
321check("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))
323time.sleep(0.5)
324check("no flood or sleep process survives", not busybox_procs(), busybox_procs())
325
326# ---------------------------------------------------------------- 7. Omega compile path parity
327sys.path.insert(0, A.gateway)
328import allen_chat as gw # noqa: E402
329same = {k: getattr(gw, k) == getattr(ss, k) for k in
330 ("BWRAP", "OMC_PIN", "IRWASM_PIN", "MAX_SOURCE", "OMC_HINTS", "TYPES")}
331same["OMC_ERR"] = gw.OMC_ERR.pattern == ss.OMC_ERR.pattern
332same["NAME"] = gw.NAME.pattern == ss.NAME.pattern
333same["signatures"] = inspect.getsource(gw.signatures) == inspect.getsource(ss.signatures)
334
335
336class Spawned(Exception):
337 pass
338
339
340def record(argv, **kw):
341 seen_argv.append(argv)
342 raise Spawned()
343
344
345seen_argv = []
346
347
348def 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
361gw_argv, ss_argv = spawned_argv(gw), spawned_argv(ss)
362same["argv"] = len(gw_argv) == 1 and gw_argv == ss_argv
363check("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]))
365handler = inspect.getsource(gw.Handler.omega) if hasattr(gw, "Handler") else ""
366check("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))
369good = "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"
370o = ss.run_omega(good)
371check("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")})
373o = ss.run_omega("fn f a ulong to ulong\nx = add a 1 7\nret x\nend\n")
374check("native pre-check refuses IR-accepted extra words", not o["ok"] and o["code"] == 5, o)
375o = ss.run_omega("x" * (ss.MAX_SOURCE + 1))
376check("oversized Omega source refused", not o["ok"] and o["stage"] == "input", o["message"])
377
378# ---------------------------------------------------------------- 8. selftest, and pin failure
379check("selftest passes with pinned tools (control)", ss.selftest() == [], "")
380bad = tempfile.NamedTemporaryFile(delete=False)
381bad.write(b"not the engine")
382bad.close()
383keep, ss.AIEN_MATH = ss.AIEN_MATH, bad.name
384r = ss.run_math("1+1")
385problems = ss.selftest()
386ss.AIEN_MATH = keep
387check("unpinned engine is refused (fail closed)", r["status"] == "error" and "engine" in r["error"]
388 and "pin" in r["error"] and problems, problems)
389keep, ss.MATH_ADMIT = ss.MATH_ADMIT, bad.name
390r = ss.run_math("1+1")
391problems = ss.selftest()
392ss.MATH_ADMIT = keep
393os.unlink(bad.name)
394check("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
398check("shipped engine.json names the pinned engine (control)", ss.manifest_problem() is None,
399 ss.manifest_problem())
400good_manifest = json.load(open(ss.ENGINE_MANIFEST))
401bad_manifests = {"missing": None, "not JSON": "{", "stale commit": dict(good_manifest, commit="0" * 40),
402 "other binary": dict(good_manifest, binary_sha256="0" * 64), "array": []}
403tmpdir = tempfile.mkdtemp(prefix="science-manifest-")
404keep_manifest = ss.ENGINE_MANIFEST
405for 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")))
417ss.ENGINE_MANIFEST = keep_manifest
418ss._manifest.clear()
419shutil.rmtree(tmpdir)
420
421# ---------------------------------------------------------------- 8c. installer (DESTDIR, no root)
422def 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
430def 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
434inst = tempfile.mkdtemp(prefix="science-install-")
435p = install(HERE, inst)
436opt, gwdir = os.path.join(inst, "opt/allen-science"), os.path.join(inst, "opt/allen-chat")
437same_bytes = lambda a, b: open(a, "rb").read() == open(b, "rb").read()
438ok_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)))
440check("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:])
442check("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))
446stale_src = tempfile.mkdtemp(prefix="science-stale-")
447for 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))
450with open(os.path.join(stale_src, "engine.json"), "w") as fh:
451 json.dump(dict(good_manifest, commit="0" * 40), fh)
452dest2 = tempfile.mkdtemp(prefix="science-install-")
453p = install(stale_src, dest2)
454check("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:])
456os.unlink(os.path.join(stale_src, "engine.json"))
457p = install(stale_src, dest2)
458check("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:])
460p = install(HERE, dest2, engine=A.math_admit)
461check("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:])
463p = install(HERE, None)
464check("install without DESTDIR requires root", (os.getuid() == 0) or (p.returncode != 0 and b"root" in p.stderr),
465 p.stderr.decode().strip())
466for d in (inst, stale_src, dest2):
467 shutil.rmtree(d)
468
469# ---------------------------------------------------------------- 9. service sandbox (launch.py)
470PROBE_SERVICE = r'''
471import os
472def is_open(n):
473 try:
474 os.fstat(n)
475 return True
476 except OSError:
477 return False
478open_fds = [n for n in range(1024) if is_open(n)]
479import json, socket, sys
480sys.path.insert(0, "/opt/allen-science")
481import science_sandbox as ss
482fd = int(sys.argv[sys.argv.index("--listen-fd") + 1])
483lo_port, tn_host, tn_port = int(sys.argv[-3]), sys.argv[-2], int(sys.argv[-1])
484f = {"fds": open_fds}
485def attempt(fn):
486 try:
487 return fn()
488 except Exception as e:
489 return "ERR %s" % type(e).__name__
490def connect(h, p):
491 s = socket.socket(); s.settimeout(2); s.connect((h, p)); d = s.recv(64); s.close(); return d.decode()
492def write(p):
493 with open(p, "w") as fh:
494 fh.write("x")
495 return "WROTE"
496f["uid"] = os.getuid()
497f["env"] = dict(os.environ)
498f["root"] = sorted(os.listdir("/"))
499f["home"] = sorted(os.listdir("/home"))
500for 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)
503f["write /"] = attempt(lambda: write("/evil"))
504f["write opt"] = attempt(lambda: write("/opt/allen-science/evil"))
505f["write usr"] = attempt(lambda: write("/usr/lib/python3.12/evil"))
506f["write tmp"] = attempt(lambda: write("/tmp/ok"))
507f["write home"] = attempt(lambda: write(os.environ["HOME"] + "/ok"))
508f["loopback out"] = attempt(lambda: connect("127.0.0.1", lo_port))
509f["tailnet out"] = attempt(lambda: connect(tn_host, tn_port)) if tn_port else "skipped"
510f["internet out"] = attempt(lambda: connect("1.1.1.1", 443))
511f["pids"] = sorted(int(p) for p in os.listdir("/proc") if p.isdigit())
512f["capeff"] = [l.split()[1] for l in open("/proc/self/status") if l.startswith("CapEff")][0]
513f["nnp"] = [l.split()[1] for l in open("/proc/self/status") if l.startswith("NoNewPrivs")][0]
514f["math"] = ss.run_math(ss.SELFTEST_MATH[0])
515f["math file"] = ss.evaluate('FileExistsQ["/opt/allen-science/aien-math"]', b'FileExistsQ["/opt/allen-science/aien-math"]')
516f["math run"] = ss.run_math("Run[x]")
517f["omega"] = {k: v for k, v in ss.run_omega(ss.SELFTEST_OMEGA).items() if k != "wasm"}
518f["selftest"] = ss.selftest()
519srv = socket.socket(fileno=fd)
520f["listen"] = list(srv.getsockname())
521body = json.dumps(f).encode()
522while True:
523 c, _ = srv.accept()
524 c.sendall(body)
525 c.close()
526'''
527
528
529def 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
537def 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
556def stop(proc):
557 if proc.poll() is None:
558 proc.kill()
559 proc.wait()
560
561
562root = tempfile.mkdtemp(prefix="science-root-")
563for 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))
567with open(os.path.join(root, "allen_science.py"), "w") as fh:
568 fh.write(PROBE_SERVICE.replace("@HOST_HOME@", HOST_HOME))
569os.chmod(root, 0o755)
570port = free_port()
571canary_env = dict(os.environ, SCIENCE_CANARY="should-not-leak", ALLEN_UPSTREAM_TOKEN="should-not-leak")
572canary_r, canary_w = os.pipe()
573canary_sock = socket.socket()
574HIGH_FD = 900
575os.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.
578launch_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)]
581ctl = 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()
585check("high fd control: fd %d is open in a child whose soft limit is lower" % HIGH_FD,
586 ctl == ["True", "64"], ctl)
587proc = 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))
589passed_fds = sorted((canary_r, canary_w, canary_sock.fileno(), HIGH_FD))
590os.close(HIGH_FD)
591data = wait_body(port, proc)
592stop(proc)
593log = proc.stdout.read().decode("utf-8", "replace")
594f = json.loads(data) if data else {}
595check("service reachable inbound over loopback via the inherited socket (control)", bool(f),
596 "launcher output: %r" % log[-400:])
597if 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"])
636p = 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)
638check("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
642if 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)
704shutil.rmtree(root)
705lo.close()
706if tn:
707 tn.close()
708
709failed = [n for n, ok in results if not ok]
710print("%d/%d passed" % (len(results) - len(failed), len(results)))
711sys.exit(1 if failed else 0)