aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / scripts / allen / science / science_sandbox.py
| 1 | """Isolated execution for the allen-science service. |
| 2 | |
| 3 | run_math(expression) first checks that the expression is exactly one bracket-balanced expression |
| 4 | and runs the pinned admission gate math-admit (seeded Omega, math-admit.om) on it; only an |
| 5 | expression it admits (exit 0, empty stdout) reaches the pinned aien-math engine (`aien-math eval`, |
| 6 | code on stdin), spliced into the internal completeness wrapper WRAP and evaluated once. Both |
| 7 | programs run in the same bubblewrap sandbox: |
| 8 | every namespace unshared (no network at all, not even loopback), nested user namespaces disabled, |
| 9 | cleared environment, the one binary as the only read-only bind, a small private tmpfs at /tmp, no |
| 10 | /dev, no /proc. Resource limits are set by the fixed /usr/bin/prlimit argv in front of bwrap (no |
| 11 | Python code runs between fork and exec, so a request thread cannot hang in the child before the |
| 12 | deadline starts). stdin is fed and stdout/stderr are collected incrementally under one deadline; |
| 13 | the sandbox is killed past the stdout cap and only a bounded stderr prefix is kept. No shell is |
| 14 | involved anywhere: argv is a fixed list. |
| 15 | |
| 16 | The engine's provenance manifest (engine.json: commit and binary sha256) is required and must name |
| 17 | exactly the pinned engine; a missing or stale manifest refuses every math request and selftest(). |
| 18 | |
| 19 | run_omega(source) is the gateway's Omega compile path (allen_chat.py): the same bwrap argv, the |
| 20 | same per-process limits, the same two-stage omc then omc-ir compile and irwasm, and the same |
| 21 | response dicts; only the collection differs (bounded and incremental here, where the gateway uses |
| 22 | communicate()). test_science_sandbox.py checks the argv and limits against the gateway. |
| 23 | |
| 24 | selftest() verifies the four pins and the manifest, runs one fixture through each path and checks |
| 25 | that the gate refuses Run[x] and URLRead[x]; the service calls it at startup and refuses to start |
| 26 | when it returns problems. |
| 27 | """ |
| 28 | |
| 29 | import base64 |
| 30 | import hashlib |
| 31 | import json |
| 32 | import os |
| 33 | import re |
| 34 | import selectors |
| 35 | import subprocess |
| 36 | import threading |
| 37 | import time |
| 38 | |
| 39 | ROOT = "/opt/allen-science" |
| 40 | BWRAP = "/usr/bin/bwrap" |
| 41 | PRLIMIT = "/usr/bin/prlimit" |
| 42 | AIEN_MATH = ROOT + "/aien-math" |
| 43 | OMC = ROOT + "/omc" |
| 44 | IRWASM = ROOT + "/irwasm" |
| 45 | MATH_ADMIT = ROOT + "/math-admit" |
| 46 | ENGINE_MANIFEST = ROOT + "/engine.json" |
| 47 | |
| 48 | # aien-math main 43c629db (clean tree, reproducible) built with omc e623d440 (omega-mv 3d000060); |
| 49 | # frozen copy /tmp/allen-science-math-release/build/aien-math. The commit and the sha256 are one |
| 50 | # pin: engine.json must state both exactly. |
| 51 | ENGINE_COMMIT = "43c629db362b48aeec3590a8f0cd30e927e5ec16" |
| 52 | AIEN_MATH_PIN = "a3c538e9e2c8b255ba3daf4cf5a486b379e2722e86a177c173ff2d097e9ddd59" |
| 53 | ENGINE_OMC_PIN = "e623d440956b1473ca32da85a019cbb3c953d4bdd6e384952d9989e8039425e3" |
| 54 | # math-admit.om (sha256 d064507f...5931) compiled with the gateway's omc (OMC_PIN); exit 0 admit, |
| 55 | # 2 refuse, 3 IO. This build refuses ++/--, a top-level ',' and the wrapper's names (WRAP). |
| 56 | MATH_ADMIT_PIN = "04c58b6861d15f21d038aff560aa1ae6eeadd76387154f3ada208b73d43632c9" |
| 57 | # The gateway's pins (allen_chat.py OMC_PIN, IRWASM_PIN). |
| 58 | OMC_PIN = "734f0a39319fbfa930bcc62cb30dbf06d47d78e126372b74f5baf478e6126b61" |
| 59 | IRWASM_PIN = "2d235a70c39ac1461a09c41e10e058d962b767ae83893cdcfc693ef6c47182e6" |
| 60 | |
| 61 | MATH_ARGV = ("eval",) # code on stdin: no argv quoting, nothing visible in the host's ps |
| 62 | MAX_EXPR = 4096 # bytes of UTF-8 accepted from the service |
| 63 | ADMIT_WALL_S = 2 |
| 64 | MATH_WALL_S = 8 # wall clock; spinning code uses about 60% CPU, so this fires first |
| 65 | RUN_WALL_S = ADMIT_WALL_S + MATH_WALL_S # one deadline for a whole run_math |
| 66 | MATH_OUT_CAP = 64 << 10 # stdout bytes; past this the sandbox is killed |
| 67 | ERR_CAP = 4096 # stderr bytes kept (the rest is drained and dropped) |
| 68 | MATH_TMPFS = 8 << 20 |
| 69 | # The engine's static RW segment is about 978 MiB of zero pages (readelf: 0x3d220ee0), so the |
| 70 | # address-space limit must sit above it; its pools are fixed, exhaustion exits 3. |
| 71 | MATH_AS = 1152 << 20 |
| 72 | MATH_LIMITS = ("--cpu=5:6", "--as=%d" % MATH_AS, "--fsize=%d" % (1 << 20), "--nofile=32", "--core=0") |
| 73 | # The gateway's sandbox_limits(): CPU 4/5 s, 512 MiB, 4 MiB files, 64 descriptors, no core. |
| 74 | OMEGA_LIMITS = ("--cpu=4:5", "--as=%d" % (512 << 20), "--fsize=%d" % (4 << 20), "--nofile=64", |
| 75 | "--core=0") |
| 76 | MATH_SLOTS = threading.BoundedSemaphore(2) |
| 77 | OMEGA_SLOTS = threading.BoundedSemaphore(2) |
| 78 | |
| 79 | OUT_MARK = "Out[1]= " |
| 80 | # The pinned printer (src/print/pr.om pr_trunc at 43c629db) cuts any result over 10005 code points |
| 81 | # to its first 4998 and last 4997 around " ... ": exactly 10000. Anything this long may be cut. |
| 82 | TRUNCATED_AT = 10000 |
| 83 | # Admitted heads that ask the engine to do something. One left anywhere in the result means that |
| 84 | # part was not done; mathematical functions (Sin, Exp, Gamma, ...) are legitimate in results. |
| 85 | EVAL_HEADS = frozenset(""" |
| 86 | N D Integrate NIntegrate Limit Series Normal Sum Product Solve Reduce Simplify FullSimplify Expand |
| 87 | Factor Together Apart Cancel Numerator Denominator Coefficient CoefficientList Collect Det Inverse |
| 88 | Transpose Eigenvalues Eigenvectors EigenSystem Eigensystem MatrixRank RowReduce LinearSolve Dot Tr |
| 89 | DSolve DSolveValue NDSolve Mean Median Variance StandardDeviation Covariance Correlation PDF CDF |
| 90 | Quantile Probability Expectation Length Total Range Table First Chop SingularValueList MatrixExp |
| 91 | IdentityMatrix DiagonalMatrix UnitConvert UnitSimplify QuantityMagnitude QuantityUnit |
| 92 | """.split()) |
| 93 | EVAL_HEAD = re.compile(r"(?<![A-Za-z0-9$`])(%s)\[" % "|".join(sorted(EVAL_HEADS, key=len, reverse=True))) |
| 94 | |
| 95 | |
| 96 | def limited(limits, argv): |
| 97 | """argv run under fixed rlimits: prlimit sets them on itself, then execs argv.""" |
| 98 | return [PRLIMIT] + list(limits) + ["--"] + argv |
| 99 | |
| 100 | |
| 101 | def math_argv(tool, args=MATH_ARGV, dest="/aien-math"): |
| 102 | """bwrap argv for one run; `tool` is bound read-only at dest and is all there is.""" |
| 103 | return [ |
| 104 | BWRAP, "--unshare-all", "--unshare-user", "--disable-userns", "--die-with-parent", |
| 105 | "--new-session", "--clearenv", "--cap-drop", "ALL", |
| 106 | "--ro-bind", tool, dest, "--size", str(MATH_TMPFS), "--tmpfs", "/tmp", |
| 107 | "--remount-ro", "/", "--chdir", "/tmp", "--", dest, |
| 108 | ] + list(args) |
| 109 | |
| 110 | |
| 111 | def run_bounded(argv, data, wall_s, out_cap, err_cap): |
| 112 | """Run argv with data on stdin; returns (status, stdout, stderr, rc). status is "done", |
| 113 | "timeout" or "too_large". stdin is written non-blocking alongside the reads, so any input size |
| 114 | is fed under the same deadline. The process group is always killed and reaped.""" |
| 115 | deadline = time.monotonic() + wall_s |
| 116 | p = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 117 | start_new_session=True, close_fds=True) |
| 118 | status, out, err = "done", bytearray(), bytearray() |
| 119 | view, pos = memoryview(data), 0 |
| 120 | sel = selectors.DefaultSelector() |
| 121 | try: |
| 122 | if data: |
| 123 | os.set_blocking(p.stdin.fileno(), False) |
| 124 | sel.register(p.stdin, selectors.EVENT_WRITE) |
| 125 | else: |
| 126 | p.stdin.close() |
| 127 | sel.register(p.stdout, selectors.EVENT_READ, out) |
| 128 | sel.register(p.stderr, selectors.EVENT_READ, err) |
| 129 | while sel.get_map(): |
| 130 | left = deadline - time.monotonic() |
| 131 | if left <= 0: |
| 132 | status = "timeout" |
| 133 | break |
| 134 | for key, _ in sel.select(left): |
| 135 | if key.fileobj is p.stdin: |
| 136 | try: |
| 137 | pos += os.write(key.fd, view[pos:pos + 65536]) |
| 138 | except BlockingIOError: |
| 139 | continue |
| 140 | except BrokenPipeError: |
| 141 | pos = len(view) |
| 142 | if pos >= len(view): |
| 143 | sel.unregister(p.stdin) |
| 144 | p.stdin.close() |
| 145 | continue |
| 146 | chunk = os.read(key.fd, 65536) |
| 147 | if not chunk: |
| 148 | sel.unregister(key.fileobj) |
| 149 | elif key.data is out: |
| 150 | out += chunk |
| 151 | if len(out) > out_cap: |
| 152 | status = "too_large" |
| 153 | break |
| 154 | elif len(err) < err_cap: |
| 155 | err += chunk[:err_cap - len(err)] |
| 156 | if status != "done": |
| 157 | break |
| 158 | if status == "done": |
| 159 | try: |
| 160 | p.wait(max(0.0, deadline - time.monotonic())) |
| 161 | except subprocess.TimeoutExpired: |
| 162 | status = "timeout" |
| 163 | finally: |
| 164 | sel.close() |
| 165 | if p.poll() is None: |
| 166 | # prlimit execs bwrap in place, so p.pid leads the sandbox's session; --die-with-parent |
| 167 | # and the pid namespace take everything inside down with it. |
| 168 | try: |
| 169 | os.killpg(p.pid, 9) |
| 170 | except ProcessLookupError: |
| 171 | pass |
| 172 | p.wait() |
| 173 | for f in (p.stdin, p.stdout, p.stderr): |
| 174 | try: |
| 175 | f.close() |
| 176 | except OSError: |
| 177 | pass |
| 178 | return status, bytes(out), bytes(err), p.returncode |
| 179 | |
| 180 | |
| 181 | def sha256_file(path): |
| 182 | h = hashlib.sha256() |
| 183 | with open(path, "rb") as f: |
| 184 | for block in iter(lambda: f.read(1 << 16), b""): |
| 185 | h.update(block) |
| 186 | return h.hexdigest() |
| 187 | |
| 188 | |
| 189 | _pinned = {} |
| 190 | _pin_lock = threading.Lock() |
| 191 | |
| 192 | |
| 193 | def pinned(path, pin): |
| 194 | """True when path hashes to pin. Cached per (path, pin): the install directory is root-owned |
| 195 | and read-only to the service, and the service runs it read-only bound.""" |
| 196 | key = (path, pin) |
| 197 | with _pin_lock: |
| 198 | if key not in _pinned: |
| 199 | try: |
| 200 | _pinned[key] = sha256_file(path) == pin |
| 201 | except OSError: |
| 202 | _pinned[key] = False |
| 203 | return _pinned[key] |
| 204 | |
| 205 | |
| 206 | def manifest_problem(path=None): |
| 207 | """None when the engine manifest names exactly the pinned engine, else why not.""" |
| 208 | path = path or ENGINE_MANIFEST |
| 209 | try: |
| 210 | with open(path, "rb") as f: |
| 211 | m = json.loads(f.read(65536)) |
| 212 | except (OSError, ValueError) as e: |
| 213 | return "engine manifest %s unreadable: %s" % (path, type(e).__name__) |
| 214 | # engine.json is shared with ScienceMath's corpus receipt; these four fields are the identity. |
| 215 | want = {"engine": "aien-dev/aien-math", "commit": ENGINE_COMMIT, "binary_sha256": AIEN_MATH_PIN, |
| 216 | "omc_sha256": ENGINE_OMC_PIN} |
| 217 | if not isinstance(m, dict): |
| 218 | return "engine manifest %s is not an object" % path |
| 219 | wrong = sorted(k for k, v in want.items() if m.get(k) != v) |
| 220 | if wrong: |
| 221 | return "engine manifest %s does not match the pinned engine: %s" % (path, ", ".join(wrong)) |
| 222 | return None |
| 223 | |
| 224 | |
| 225 | _manifest = {} |
| 226 | |
| 227 | |
| 228 | def manifest_ok(): |
| 229 | with _pin_lock: |
| 230 | if ENGINE_MANIFEST not in _manifest: |
| 231 | _manifest[ENGINE_MANIFEST] = manifest_problem() is None |
| 232 | return _manifest[ENGINE_MANIFEST] |
| 233 | |
| 234 | |
| 235 | # ScienceMath's completeness wrapper for aien-math 43c629db (no engine change): the expression is |
| 236 | # evaluated once inside With; HoldComplete keeps the input's structure (List[x] and {x} alike, no |
| 237 | # Evaluate or Sequence splicing) for an exact SameQ test, and the FreeQ guard marks results that |
| 238 | # still hold an operation, or the derivative pattern behind the known wrong Limit answers. |
| 239 | WRAP = ("With[{aienR = ", "}, If[HoldComplete[", "] =!= HoldComplete[aienR] && FreeQ[HoldComplete[aienR], " |
| 240 | "Integrate|D|DSolve|NDSolve|Limit|Sum|Product|Solve|NSolve|Series|Simplify|FullSimplify|" |
| 241 | "Expectation|Probability|Eigensystem|SingularValueDecomposition|MatrixExp|UnitConvert|" |
| 242 | "Derivative[_][Abs|Sign|Floor|Ceiling|Round|UnitStep][_]], aienComputed[aienR], aienUnsupported]]") |
| 243 | COMPUTED = ("aienComputed[", "]") |
| 244 | UNSUPPORTED = "aienUnsupported" |
| 245 | |
| 246 | |
| 247 | def single_expression(expr): |
| 248 | """True when expr can be spliced into WRAP as exactly one expression: brackets balanced and |
| 249 | nested correctly outside strings, no top-level ',' or ';', no ';' anywhere, no wrapper names. |
| 250 | math-admit enforces the same; this is the helper's own boundary before splicing.""" |
| 251 | if ";" in expr or "aien" in expr: |
| 252 | return False |
| 253 | stack, quoted, i = [], False, 0 |
| 254 | pairs = {"]": "[", "}": "{", ")": "("} |
| 255 | while i < len(expr): |
| 256 | c = expr[i] |
| 257 | if quoted: |
| 258 | if c == "\\": |
| 259 | i += 1 |
| 260 | elif c == '"': |
| 261 | quoted = False |
| 262 | elif c == '"': |
| 263 | quoted = True |
| 264 | elif c in "[{(": |
| 265 | stack.append(c) |
| 266 | elif c in pairs: |
| 267 | if not stack or stack.pop() != pairs[c]: |
| 268 | return False |
| 269 | elif c == "," and not stack: |
| 270 | return False |
| 271 | i += 1 |
| 272 | return not stack and not quoted |
| 273 | |
| 274 | |
| 275 | def wrapped(data): |
| 276 | return (WRAP[0] + "%s" + WRAP[1] + "%s" + WRAP[2]).encode() % (data, data) |
| 277 | |
| 278 | |
| 279 | def parse_engine(text): |
| 280 | """Split the wrapper's engine stdout into (status, value, messages, error). Success is only |
| 281 | exactly "Out[1]= aienComputed[VALUE]" with no line containing "::", a value short enough that |
| 282 | the printer did not cut it, no $Failed/$Aborted and no evaluation request (Integrate[, ...) |
| 283 | left anywhere in it.""" |
| 284 | messages = [ln for ln in text.splitlines() if "::" in ln] |
| 285 | if messages: |
| 286 | return "unsupported", "", messages, "the engine reported: " + messages[0][:200] |
| 287 | body = text.rstrip("\n") |
| 288 | if not body.startswith(OUT_MARK): |
| 289 | return "unsupported", "", messages, "the engine printed no result" |
| 290 | value = body[len(OUT_MARK):] |
| 291 | if value == UNSUPPORTED: |
| 292 | return "unsupported", "", messages, "the engine left the expression or an operation unevaluated" |
| 293 | if len(value) >= TRUNCATED_AT: |
| 294 | return "unsupported", "", messages, "the result is too long to print whole (the engine cut it)" |
| 295 | if not (value.startswith(COMPUTED[0]) and value.endswith(COMPUTED[1])): |
| 296 | return "unsupported", "", messages, "the engine printed an unexpected result" |
| 297 | value = value[len(COMPUTED[0]):-len(COMPUTED[1])] |
| 298 | if "$Failed" in value or "$Aborted" in value: |
| 299 | return "unsupported", value, messages, "the engine returned $Failed" |
| 300 | m = EVAL_HEAD.search(value) |
| 301 | if m: |
| 302 | return "unsupported", value, messages, "%s stayed unevaluated" % m.group(1) |
| 303 | return "ok", value, messages, None |
| 304 | |
| 305 | |
| 306 | def math_result(status, output="", error=None, messages=()): |
| 307 | r = {"ok": status == "ok", "status": status, "output": output, "messages": list(messages)} |
| 308 | if error: |
| 309 | r["error"] = error |
| 310 | return r |
| 311 | |
| 312 | |
| 313 | def checked_input(expression): |
| 314 | """(data, None) for an expression within the byte bounds, else (None, refusal).""" |
| 315 | if not isinstance(expression, str): |
| 316 | return None, math_result("refused", error="expression must be a string") |
| 317 | if "\0" in expression: |
| 318 | return None, math_result("refused", error="expression contains a NUL byte") |
| 319 | try: |
| 320 | data = expression.encode("utf-8") |
| 321 | except UnicodeEncodeError: |
| 322 | return None, math_result("refused", error="expression is not valid Unicode") |
| 323 | if not expression.strip(): |
| 324 | return None, math_result("refused", error="empty expression") |
| 325 | if len(data) > MAX_EXPR: |
| 326 | return None, math_result("refused", error="expression longer than %d bytes" % MAX_EXPR) |
| 327 | if not single_expression(expression): |
| 328 | return None, math_result("refused", error="not exactly one bracket-balanced expression") |
| 329 | return data, None |
| 330 | |
| 331 | |
| 332 | ADMIT_REFUSAL = "outside the admitted mathematics (math-admit refused it)" |
| 333 | |
| 334 | |
| 335 | def left_until(deadline, cap): |
| 336 | return min(cap, deadline - time.monotonic()) |
| 337 | |
| 338 | |
| 339 | def admit(data, deadline=None): |
| 340 | """None when math-admit admits data (exit 0, nothing on stdout), else the refusal or error.""" |
| 341 | deadline = deadline or time.monotonic() + RUN_WALL_S |
| 342 | status, out, err, rc = run_bounded(limited(MATH_LIMITS, math_argv(MATH_ADMIT, (), "/math-admit")), |
| 343 | data, left_until(deadline, ADMIT_WALL_S), 4096, ERR_CAP) |
| 344 | if status != "done": |
| 345 | return math_result("error", error="the admission gate failed: " + status) |
| 346 | if rc == 2 and not out: |
| 347 | return math_result("refused", error=ADMIT_REFUSAL) |
| 348 | if rc != 0 or out: |
| 349 | return math_result("error", error="the admission gate failed: exit %d" % rc) |
| 350 | return None |
| 351 | |
| 352 | |
| 353 | def engine_text(data, wall_s=MATH_WALL_S): |
| 354 | """(stdout text, None) from one engine run, or (None, failure result).""" |
| 355 | status, out, err, rc = run_bounded(limited(MATH_LIMITS, math_argv(AIEN_MATH)), data, wall_s, |
| 356 | MATH_OUT_CAP, ERR_CAP) |
| 357 | if status == "timeout": |
| 358 | return None, math_result("timeout", error="the engine ran past %d s" % MATH_WALL_S) |
| 359 | if status == "too_large": |
| 360 | return None, math_result("too_large", error="the engine printed more than %d bytes" % MATH_OUT_CAP) |
| 361 | if rc != 0: |
| 362 | why = ("memory pool exhausted" if rc == 3 else "trap %d" % (rc - 100) if 100 <= rc < 200 |
| 363 | else "CPU limit" if rc in (-24, -9) else "exit %d" % rc) |
| 364 | return None, math_result("error", error="the engine stopped: " + why) |
| 365 | try: |
| 366 | return out.decode("utf-8"), None |
| 367 | except UnicodeDecodeError: |
| 368 | return None, math_result("error", error="the engine printed invalid UTF-8") |
| 369 | |
| 370 | |
| 371 | def evaluate(expression, data, deadline=None): |
| 372 | """One engine run of the expression inside WRAP (run_math is the only production caller; the |
| 373 | caller has checked single_expression). The wrapper is internal: the expression alone is what |
| 374 | the service records as provenance.""" |
| 375 | deadline = deadline or time.monotonic() + RUN_WALL_S |
| 376 | wall = left_until(deadline, MATH_WALL_S) |
| 377 | if wall <= 0: |
| 378 | return math_result("timeout", error="the request ran past its time budget") |
| 379 | text, failed = engine_text(wrapped(data), wall) |
| 380 | if failed: |
| 381 | return failed |
| 382 | st, value, messages, error = parse_engine(text) |
| 383 | return math_result(st, value, error, messages) |
| 384 | |
| 385 | |
| 386 | def run_math(expression): |
| 387 | """Admit, then evaluate one expression with the pinned aien-math. Never raises for gate or |
| 388 | engine behaviour.""" |
| 389 | data, refusal = checked_input(expression) |
| 390 | if refusal: |
| 391 | return refusal |
| 392 | if not (os.access(BWRAP, os.X_OK) and os.access(PRLIMIT, os.X_OK)): |
| 393 | return math_result("error", error="sandbox missing") |
| 394 | if not pinned(MATH_ADMIT, MATH_ADMIT_PIN): |
| 395 | return math_result("error", error="admission gate does not match its pin") |
| 396 | if not pinned(AIEN_MATH, AIEN_MATH_PIN): |
| 397 | return math_result("error", error="engine does not match its pin") |
| 398 | if not manifest_ok(): |
| 399 | return math_result("error", error="engine manifest missing or stale") |
| 400 | if not MATH_SLOTS.acquire(blocking=False): |
| 401 | return math_result("busy", error="the engine is busy") |
| 402 | try: |
| 403 | deadline = time.monotonic() + RUN_WALL_S |
| 404 | return admit(data, deadline) or evaluate(expression, data, deadline) |
| 405 | finally: |
| 406 | MATH_SLOTS.release() |
| 407 | |
| 408 | |
| 409 | # ---- Omega compile path: the gateway's (allen_chat.py: sandboxed, signatures, OMC_HINTS, OMC_ERR, |
| 410 | # TYPES, NAME, MAX_SOURCE and the omega() handler body), with bounded collection. ---- |
| 411 | |
| 412 | MAX_SOURCE = 16384 |
| 413 | OMC_HINTS = { |
| 414 | 3: "An unknown name or a word IR mode refuses: floats, host words, continue, sizeof, or a call to " |
| 415 | "a function that is not defined earlier (no recursion, no forward calls).", |
| 416 | 4: "The line ended before the statement was complete.", |
| 417 | 5: "Extra words at the end of the line: every op takes a fixed number of values.", |
| 418 | 6: "A number is malformed: digits only, at most 20, with an optional leading minus.", |
| 419 | 7: "Types do not match or a value is used the wrong way. There are no implicit conversions: " |
| 420 | "convert with the type word, for example ulong x.", |
| 421 | 8: "A number is outside the range of its type.", |
| 422 | 9: "Not allowed here: a call cycle or recursion (call only earlier functions), struct, global " |
| 423 | "or text in IR mode, more than 6 parameters, or break outside a loop.", |
| 424 | 10: "A name is reused: no shadowing, and a name cannot repeat a function name.", |
| 425 | 11: "Ambiguous number: two bare numbers in one op, or a bare number with no type around it. " |
| 426 | "Write the type, for example ulong 1.", |
| 427 | 12: "Too many live values for the 16 registers. Split the function into smaller earlier helpers.", |
| 428 | 13: "A name is too long (at most 8 characters) or a function is unknown.", |
| 429 | 14: "A capacity was exceeded.", |
| 430 | 15: "A block is missing its end.", |
| 431 | 16: "A word was not understood where a type or value was expected.", |
| 432 | 17: "A line follows ret, break or trap in the same block and can never run.", |
| 433 | 18: "The function can reach its end without ret.", |
| 434 | 22: "A text literal has a bad escape.", |
| 435 | } |
| 436 | OMC_ERR = re.compile(rb"omc: line (\d+): error (\d+)") |
| 437 | TYPES = {"bool", "uchar", "ushort", "uint", "ulong", "byte", "short", "int", "long"} |
| 438 | NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,62}$") |
| 439 | |
| 440 | |
| 441 | def sandbox_argv(tool, args=(), argv0=None): |
| 442 | """The gateway's bwrap argv for omc and irwasm, unchanged.""" |
| 443 | return [ |
| 444 | BWRAP, "--unshare-all", "--die-with-parent", "--new-session", "--clearenv", |
| 445 | "--cap-drop", "ALL", "--ro-bind", tool, "/tool", "--size", str(8 << 20), "--tmpfs", "/tmp", |
| 446 | "--dev", "/dev", "--remount-ro", "/", "--chdir", "/tmp", |
| 447 | ] + (["--argv0", argv0] if argv0 else []) + ["--", "/tool"] + list(args) |
| 448 | |
| 449 | |
| 450 | def sandboxed(tool, data, wall_s, out_cap, args=(), argv0=None): |
| 451 | """The gateway's sandboxed(): same argv, limits and return values (out, err, rc), with stdout |
| 452 | capped while it is read and stderr kept to its first 4096 bytes.""" |
| 453 | status, out, err, rc = run_bounded(limited(OMEGA_LIMITS, sandbox_argv(tool, args, argv0)), data, |
| 454 | wall_s, out_cap, ERR_CAP) |
| 455 | if status == "timeout": |
| 456 | return None, b"timeout", -9 |
| 457 | if status == "too_large": |
| 458 | return None, b"output too large", -1 |
| 459 | return out, err, rc |
| 460 | |
| 461 | |
| 462 | def signatures(source): |
| 463 | fns = [] |
| 464 | for line in source.splitlines(): |
| 465 | w = line.split() |
| 466 | if len(w) < 3 or w[0] != "fn" or "to" not in w: |
| 467 | continue |
| 468 | cut = w.index("to") |
| 469 | name, params, ret = w[1], w[2:cut], w[cut + 1:] |
| 470 | if not NAME.match(name) or len(params) % 2 or len(ret) != 1: |
| 471 | return None |
| 472 | ps = [] |
| 473 | for i in range(0, len(params), 2): |
| 474 | if params[i + 1] not in TYPES: |
| 475 | return None |
| 476 | ps.append({"name": params[i], "type": params[i + 1]}) |
| 477 | if ret[0] not in TYPES and ret[0] != "void": |
| 478 | return None |
| 479 | fns.append({"name": name, "params": ps, "ret": ret[0]}) |
| 480 | return fns |
| 481 | |
| 482 | |
| 483 | def omega_refusal(stage, message, hint="", code=None): |
| 484 | return {"ok": False, "stage": stage, "code": code, "line": None, "message": message, "hint": hint} |
| 485 | |
| 486 | |
| 487 | def run_omega(source): |
| 488 | """Compile Omega source to WebAssembly exactly as the gateway's /omega route does. Returns the |
| 489 | gateway's JSON body as a dict; input and busy refusals use stage "input" and "busy".""" |
| 490 | if not isinstance(source, str) or not source.strip(): |
| 491 | return omega_refusal("input", "Send the Omega source as a string.") |
| 492 | if len(source.encode("utf-8", "replace")) > MAX_SOURCE: |
| 493 | return omega_refusal("input", "Omega source is limited to 16 KiB here.") |
| 494 | if not (os.access(BWRAP, os.X_OK) and os.access(PRLIMIT, os.X_OK)): |
| 495 | return omega_refusal("sandbox", "The compile sandbox is missing.") |
| 496 | if not (pinned(OMC, OMC_PIN) and pinned(IRWASM, IRWASM_PIN)): |
| 497 | return omega_refusal("sandbox", "The compiler does not match its pin.") |
| 498 | if not OMEGA_SLOTS.acquire(blocking=False): |
| 499 | return omega_refusal("busy", "The compiler is busy. Try again in a moment.") |
| 500 | try: |
| 501 | body = source.replace("\r\n", "\n") |
| 502 | if body.split("\n", 1)[0].strip() == "ir": |
| 503 | body = body.split("\n", 1)[1] if "\n" in body else "" |
| 504 | t0 = time.monotonic() |
| 505 | # The pinned omc's IR mode skips checks its native mode makes, so the same unit must first |
| 506 | # pass the native function-mode compile (its machine words are discarded), then IR. |
| 507 | for stage, data, shift in (("omc", body.encode("utf-8"), 0), |
| 508 | ("omc-ir", b"ir\n" + body.encode("utf-8"), 1)): |
| 509 | out, err, rc = sandboxed(OMC, data, 5, 4 << 20) |
| 510 | if rc == 0 and out: |
| 511 | ir = out |
| 512 | continue |
| 513 | m = OMC_ERR.search(err or b"") |
| 514 | code = int(m.group(2)) if m else None |
| 515 | line = int(m.group(1)) - shift if m else None |
| 516 | msg = ("omc: line %d: error %d" % (line, code)) if m else ( |
| 517 | "the compiler stopped (%s)" % (err.decode("utf-8", "replace").strip() or "exit %d" % rc)) |
| 518 | if stage == "omc-ir" and m: |
| 519 | msg += " (IR mode)" |
| 520 | return {"ok": False, "stage": "omc", "code": code, "line": line, "message": msg, |
| 521 | "hint": OMC_HINTS.get(code, "See the Omegese guide.")} |
| 522 | wasm, err, rc = sandboxed(IRWASM, ir, 5, 1 << 20) |
| 523 | if rc != 0 or not wasm or wasm[:4] != b"\0asm": |
| 524 | return {"ok": False, "stage": "irwasm", "code": rc, "line": None, |
| 525 | "message": "irwasm: " + (err.decode("utf-8", "replace").strip() or "exit %d" % rc), |
| 526 | "hint": "The IR translator refused this unit; keep to scalar " |
| 527 | "functions that call only earlier functions."} |
| 528 | fns = signatures(source) |
| 529 | if not fns: |
| 530 | return {"ok": False, "stage": "limit", "code": None, "line": None, |
| 531 | "message": "No callable function signature found.", |
| 532 | "hint": "Write functions as: fn name a ulong b ulong to ulong"} |
| 533 | return {"ok": True, "wasm": base64.b64encode(wasm).decode(), "functions": fns, |
| 534 | "compile_ms": int((time.monotonic() - t0) * 1000), |
| 535 | "omc_sha256": OMC_PIN, "irwasm_sha256": IRWASM_PIN} |
| 536 | finally: |
| 537 | OMEGA_SLOTS.release() |
| 538 | |
| 539 | |
| 540 | SELFTEST_MATH = ("Expand[(a+b)^2]", "a^2 + 2*a*b + b^2") |
| 541 | SELFTEST_OMEGA = "fn f a uint to uint\nret a\nend\n" |
| 542 | SELFTEST_REFUSED = ("Run[x]", "URLRead[x]") |
| 543 | |
| 544 | |
| 545 | def selftest(): |
| 546 | """Problems that must stop the service from starting; empty when both paths work.""" |
| 547 | for tool in (BWRAP, PRLIMIT): |
| 548 | if not os.access(tool, os.X_OK): |
| 549 | return ["%s missing" % tool] |
| 550 | problems = [] |
| 551 | for path, pin in ((MATH_ADMIT, MATH_ADMIT_PIN), (AIEN_MATH, AIEN_MATH_PIN), (OMC, OMC_PIN), |
| 552 | (IRWASM, IRWASM_PIN)): |
| 553 | if not pinned(path, pin): |
| 554 | problems.append("%s does not hash to %s" % (path, pin)) |
| 555 | m = manifest_problem() |
| 556 | if m: |
| 557 | problems.append(m) |
| 558 | if problems: |
| 559 | return problems |
| 560 | r = run_math(SELFTEST_MATH[0]) |
| 561 | if not r["ok"] or r["output"] != SELFTEST_MATH[1]: |
| 562 | problems.append("math sandbox fixture failed: %r" % (r,)) |
| 563 | for unsafe in SELFTEST_REFUSED: |
| 564 | r = run_math(unsafe) |
| 565 | if r["status"] != "refused" or r.get("error") != ADMIT_REFUSAL: |
| 566 | problems.append("admission gate did not refuse %s: %r" % (unsafe, r)) |
| 567 | o = run_omega(SELFTEST_OMEGA) |
| 568 | if not o.get("ok"): |
| 569 | problems.append("omega sandbox fixture failed: %r" % (o,)) |
| 570 | return problems |