diff --git a/scripts/allen/DEPENDENCIES.md b/scripts/allen/DEPENDENCIES.md index 79646d5..15014a0 100644 --- a/scripts/allen/DEPENDENCIES.md +++ b/scripts/allen/DEPENDENCIES.md @@ -31,7 +31,7 @@ exist (OMEGESE.md section 10, native host extension). | bubblewrap | 0.9.0 (Ubuntu) | Namespace sandbox around omc and irwasm | Isolation tool around the compiler, not first-party logic | kept | n/a | | nginx (hub) | 1.28.3 (Ubuntu) | TLS, PROXY protocol, rate limits, routing | Existing edge | kept for now | Omega TLS server words (omega-mv#788) | | `science/allen_science.py`, `science/science_protocol.py`, `allen_science.py` gateway adapter | CPython 3.12.3, standard library only | Bounded loopback HTTP/JSON framing, six strict tool schemas, native function-call results and pane v1 envelopes; no external HTTP client in the service, no project store | Temporary adapter to the existing Python gateway while the bounded HTTP/JSON libraries are delivered; native Omega sockets already exist, so this is NOT a missing-socket claim | `allen-science.om` and gateway's `allen-gw.om`, using `seed/net/http.om` and `seed/json/json.om` | OmegaNet's bounded HTTP/JSON library: successor libraries merged in aien-dev/omega-mv#814 (77ebd3fd, omc 189ada82); allen-science.om port not yet written, so the Python adapter remains in production path. | -| `science/science_sandbox.py`, `science/launch.py`, `science/install.sh`, `science/allen-science-fg` | CPython 3.12.3 stdlib, POSIX install/launcher glue, bubblewrap 0.9.0 and util-linux 2.39.3 | Dedicated-user empty-network-namespace service, one inherited loopback listener, fixed pinned compute binaries, bounded resources/output and read-only mounts | Host isolation boundary around native Omega units, recorded explicitly, not represented as generated Omega | `allen-science-launch.om` using native process/file/socket words plus aien-supervise's merged sandbox contract | Supervisor policy integration and inherited-listener boundary; no additional compiler word is asserted missing | +| `science/science_sandbox.py`, `science/launch.py`, `science/install.sh`, `science/allen-science-fg`, `science/allen-science-math-fg` | CPython 3.12.3 stdlib, POSIX install/launcher glue, bubblewrap 0.9.0 and util-linux 2.39.3 | Dedicated-user empty-network-namespace service, one inherited loopback listener, fixed pinned compute binaries, bounded resources/output and read-only mounts; the math-only instance (18114, `--tools math_compute`) is the only science port the public gateway may reach | Host isolation boundary around native Omega units, recorded explicitly, not represented as generated Omega | `allen-science-launch.om` using native process/file/socket words plus aien-supervise's merged sandbox contract | Supervisor policy integration and inherited-listener boundary; no additional compiler word is asserted missing | | `science/math-admit.om` and `aien-math` | Seeded Omega; admission compiler sha256 734f0a39319fbfa930bcc62cb30dbf06d47d78e126372b74f5baf478e6126b61; aien-math uses its own tools/omc.pin | Positive mathematical symbol/unit admission, then symbolic/numeric computation in a no-network sandbox | Native Omega, not a host-language dependency | Implemented; exact source/engine pins in engine.json and sandbox constants | No Wolfram runtime, account, key or external CAS | | `allen_transcribe.py` (gateway module, POST `transcribe`) | CPython 3.12.3, stdlib (`struct`, `subprocess`, `resource`) | Push-to-talk: content-type and magic-byte check, strict WAV header parse, duration and size caps, runs the decoder and the recogniser below in two bwrap sandboxes over pipes (no audio file anywhere), zeroes its buffers, returns the text | Same process as the gateway | part of `allen-gw.om`: byte-level RIFF parser, the same two sandboxed process calls with pipe I/O | Socket/HTTP host words (omega-mv#788); process and pipe words exist | | `whisper-cli` (`/opt/allen-chat/whisper-cli`) | whisper.cpp v1.9.5 (commit `d1be6fde11ac6e0407606b4e42fe72d34add8037`), C/C++, built here with gcc 13.3.0 / cmake 3.28.3: `cmake -B build-static -DCMAKE_BUILD_TYPE=Release -DGGML_CUDA=OFF -DGGML_OPENMP=OFF -DBUILD_SHARED_LIBS=OFF -DWHISPER_BUILD_TESTS=OFF -DWHISPER_BUILD_SERVER=OFF -DWHISPER_SDL2=OFF -DGGML_NATIVE=ON -DCMAKE_EXE_LINKER_FLAGS=-static && cmake --build build-static -j2 --target whisper-cli` (nice 19, CPU only), static, sha256 `0b3d63f4a90d5df14031479ed039fe1f96ffc52fff8b193e85f71daa3762ed5a` (pinned in `allen_transcribe.py`) | Speech to text on the CPU (greedy decode, English, 4 threads), stdin WAV to stdout text, inside bwrap with only itself and the model bound read-only | No speech recogniser exists in `.om` yet; this is a third-party model runtime | Successor path (same as the voice/TTS row below): open CPU STT on the Spark (this row: whisper.cpp, MIT, already open and local) -> a trained Aien STT model (fine-tuned on the Aien name and project vocabulary) -> Omega runtime `allen-hear.om` (log-mel front end and encoder/decoder over the trained weights, CPU) | Not yet written in `.om`: needs a float32 tensor library (matmul, conv1d, softmax, layer norm) at SIMD speed and a ggml weight reader; extension proposal, not filed | diff --git a/scripts/allen/README.md b/scripts/allen/README.md index f7fff9d..0cffdda 100644 --- a/scripts/allen/README.md +++ b/scripts/allen/README.md @@ -157,9 +157,11 @@ python3 scripts/allen/allen_infer.py bench http://127.0.0.1:8000 --model &2; exit 1; fi +exec /usr/bin/setpriv --reuid=allen-science --regid=allen-science --clear-groups \ + --no-new-privs --inh-caps=-all --bounding-set=-all \ + /usr/bin/env -i PATH=/usr/bin:/bin \ + /usr/bin/python3.12 -I /opt/allen-science/launch.py --listen 127.0.0.1:18114 \ + -- --port 18114 --tools math_compute diff --git a/scripts/allen/science/allen-science-math.svc b/scripts/allen/science/allen-science-math.svc new file mode 100644 index 0000000..c1c806a --- /dev/null +++ b/scripts/allen/science/allen-science-math.svc @@ -0,0 +1,16 @@ +exec /usr/bin/python3.12 -I /opt/allen-science/launch.py --listen 127.0.0.1:18114 -- --port 18114 --tools math_compute +user allen-science +restart always +env PATH=/usr/bin:/bin +ro /opt/allen-science +net filter +allow 127.0.0.1 +listen 18114 127.0.0.1 +net-default drop +memory-max 1610612736 +tasks-max 64 +cpu-quota 200 +syscalls @system-service @mount @ns +namespaces yes +syscall-error eperm +families unix inet netlink diff --git a/scripts/allen/science/allen_science.py b/scripts/allen/science/allen_science.py index b09a2ab..fcc631d 100755 --- a/scripts/allen/science/allen_science.py +++ b/scripts/allen/science/allen_science.py @@ -14,7 +14,7 @@ from http.server import BaseHTTPRequestHandler, HTTPServer # Isolated interpreter (-I) intentionally excludes cwd; only the root-owned install dir is imported. import sys sys.path.insert(0, str(Path(__file__).resolve().parent)) -from science_protocol import MAX_BYTES, event, packed, validate +from science_protocol import MAX_BYTES, TOOLS, event, packed, validate from science_protocol import content as validate_content from science_sandbox import AIEN_MATH_PIN, run_math, run_omega, selftest ENGINE = 'aien-math' @@ -129,6 +129,8 @@ class Handler(BaseHTTPRequestHandler): if len(raw) != size: raise ValueError('Truncated request') from science_protocol import parse_call name, args = parse_call(raw.decode('utf-8')) + if name not in self.server.tools: + self.reply(403, {'error':'tool_not_allowed'}); return output = perform(name,args) except (ValueError, UnicodeError, json.JSONDecodeError): self.reply(422, {'error':'invalid_compute_request'}); return @@ -141,6 +143,7 @@ class Server(socketserver.ThreadingMixIn, HTTPServer): daemon_threads = True allow_reuse_address = True slots = threading.BoundedSemaphore(2) + tools = frozenset(TOOLS) def process_request(self, request, client_address): if not self.slots.acquire(False): request.sendall(b'HTTP/1.0 503 Service Unavailable\r\nContent-Length: 0\r\n\r\n') @@ -153,10 +156,19 @@ class Server(socketserver.ThreadingMixIn, HTTPServer): try: super().process_request_thread(request,client_address) finally: self.slots.release() +def allowed_tools(text): + """The --tools list: a non-empty, duplicate-free subset of TOOLS. A public gateway gets an + instance that serves only what it calls, so its reach is the tool, not the whole service.""" + names = text.split(',') + if not text or len(set(names)) != len(names) or not set(names) <= set(TOOLS): + raise argparse.ArgumentTypeError('--tools takes a comma list of ' + ','.join(TOOLS)) + return frozenset(names) + if __name__ == '__main__': parser = argparse.ArgumentParser() - parser.add_argument('--listen', default='127.0.0.1:18113', choices=['127.0.0.1:18113']) parser.add_argument('--listen-fd', type=int) + parser.add_argument('--port', type=int, default=18113, choices=[18113, 18114]) + parser.add_argument('--tools', type=allowed_tools, default=frozenset(TOOLS)) options = parser.parse_args() load_manifest() problems = selftest() @@ -164,10 +176,11 @@ if __name__ == '__main__': raise SystemExit('Science sandbox self-test refused startup: ' + '; '.join(problems)) if options.listen_fd is None: raise SystemExit('Science service requires the isolated inherited-socket launcher') - server = Server(('127.0.0.1',18113),Handler,bind_and_activate=False) + server = Server(('127.0.0.1',options.port),Handler,bind_and_activate=False) + server.tools = options.tools server.socket.close() server.socket = socket.socket(fileno=options.listen_fd) server.server_address = server.socket.getsockname() - if server.server_address != ('127.0.0.1',18113): + if server.server_address != ('127.0.0.1',options.port): raise SystemExit('Unexpected inherited listener') server.serve_forever() diff --git a/scripts/allen/science/install.sh b/scripts/allen/science/install.sh index 2ee341b..193b131 100755 --- a/scripts/allen/science/install.sh +++ b/scripts/allen/science/install.sh @@ -52,6 +52,7 @@ install $OWN -m 0755 "$ENGINE" "$DEST/aien-math" install $OWN -m 0755 "$OMC" "$DEST/omc" install $OWN -m 0755 "$IRWASM" "$DEST/irwasm" install $OWN -m 0755 "$SRC/allen-science-fg" "$LIBEXEC/allen-science-fg" +install $OWN -m 0755 "$SRC/allen-science-math-fg" "$LIBEXEC/allen-science-math-fg" cmp -s "$DEST/science_protocol.py" "$GW/science_protocol.py" || { echo "install.sh: service and gateway science_protocol.py differ" >&2; exit 1; } echo "installed $DEST and $GW/science_protocol.py; not started" diff --git a/scripts/allen/science/test_science_service.py b/scripts/allen/science/test_science_service.py index 42ab637..1155f02 100644 --- a/scripts/allen/science/test_science_service.py +++ b/scripts/allen/science/test_science_service.py @@ -1,7 +1,10 @@ +import argparse +import http.client import importlib.util import json from pathlib import Path import tempfile +import threading import unittest from unittest.mock import patch import allen_science as service @@ -51,5 +54,34 @@ class ServiceControls(unittest.TestCase): with self.assertRaises(ValueError): content('math',{'text':'result','html':''}) with self.assertRaises(ValueError): content('omega',{'source':'ir','language':'omega','wasm':'!!!!'}) with self.assertRaises(ValueError): content('doc',{'markdown':'draft','citations':[],'title':'extra'}) + def test_tools_option_is_a_subset_of_the_protocol(self): + self.assertEqual(service.allowed_tools('math_compute'),frozenset({'math_compute'})) + for bad in ('','deploy','math_compute,math_compute','math_compute,'): + with self.assertRaises(argparse.ArgumentTypeError): service.allowed_tools(bad) + def test_math_only_instance_refuses_other_tools(self): + server=service.Server(('127.0.0.1',0),service.Handler) + server.tools=frozenset({'math_compute'}) + threading.Thread(target=server.serve_forever,daemon=True).start() + self.addCleanup(server.server_close) + self.addCleanup(server.shutdown) + def call(tool,arguments): + conn=http.client.HTTPConnection(*server.server_address,timeout=10) + body=json.dumps({'tool':tool,'arguments':arguments}) + conn.request('POST','/compute',body,{'Content-Type':'application/json'}) + resp=conn.getresponse() + return resp.status,json.loads(resp.read()) + with patch.object(service,'run_math',return_value={'ok':True,'output':'1/3'}) as math, \ + patch.object(service,'run_omega') as omega: + status,out=call('math_compute',{'title':'Math','expression':'Integrate[x^2,{x,0,1}]'}) + self.assertEqual(status,200) + self.assertEqual(out['events'][1]['data']['content']['text'],'1/3') + status,out=call('omega_compile',{'title':'Omega','source':'1 2 + .'}) + self.assertEqual((status,out),(403,{'error':'tool_not_allowed'})) + status,out=call('paper',{'title':'Paper','markdown':'draft','citations':[]}) + self.assertEqual((status,out),(403,{'error':'tool_not_allowed'})) + omega.assert_not_called() + self.assertEqual(math.call_count,1) + def test_default_instance_keeps_every_tool(self): + self.assertEqual(service.Server.tools,frozenset(service.TOOLS)) if __name__=='__main__': unittest.main(verbosity=2)