Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
security: six advisories — loader bounds, router NaN, serve limits
JustVuggedcdd4e36b2d
diff --git a/c/inkling.c b/c/inkling.cindex 52fba9ff..1ecb4738 100644--- a/c/inkling.c+++ b/c/inkling.c@@ -527,23 +527,43 @@ static void load_cfg(Cfg *c, const char *snap) {}if (c->n_layers > MAXL) { fprintf(stderr,"n_layers %d > MAXL\n", c->n_layers); exit(1); }+ /* SEC: these loops run to n_layers -- a number from config.json, up to+ * MAXL -- while indexing a JSON array whose length is a different, equally+ * attacker-chosen number. "num_hidden_layers": 66 with a one-element+ * layer_types[] read kids[1..65] past a malloc'd array that starts at+ * capacity 8, then dereferenced whatever was there as a string. config.json+ * alone was enough; no weights and no valid snapshot were needed.+ *+ * A short array now means "not specified for these layers", so the loop+ * falls through to the same default it would have used had the key been+ * absent. The element type is checked too: kids[i]->str is a union member+ * that is only a valid pointer when t == J_STR. */+ #define LT_STR(arr, i) \+ ((arr) && (arr)->t == J_ARR && (i) < (arr)->len && \+ (arr)->kids[i] && (arr)->kids[i]->t == J_STR ? (arr)->kids[i]->str : NULL)+/* attention layer types: explicit layer_types[] > local_layer_ids[] > (i+1)%6 rule */jval *lt = json_get(r,"layer_types");jval *ll = json_get(r,"local_layer_ids");for (int i = 0; i < c->n_layers; i++) {- if (lt && lt->t == J_ARR) c->local[i] = (strcmp(lt->kids[i]->str,"hybrid_sliding")==0);+ const char *ltype = LT_STR(lt, i);+ if (ltype) c->local[i] = (strcmp(ltype,"hybrid_sliding")==0);else if (ll && ll->t == J_ARR) {c->local[i] = 0;- for (int j = 0; j < ll->len; j++) if ((int)ll->kids[j]->num == i) { c->local[i] = 1; break; }+ for (int j = 0; j < ll->len; j++)+ if (ll->kids[j] && ll->kids[j]->t == J_NUM &&+ (int)ll->kids[j]->num == i) { c->local[i] = 1; break; }} else c->local[i] = ((i + 1) % 6) != 0;}/* MLP types: explicit mlp_layer_types[] > dense_mlp_idx (first k layers dense) */jval *mt = json_get(r,"mlp_layer_types");int dense_idx = (int)jnum(r,"dense_mlp_idx",0);for (int i = 0; i < c->n_layers; i++) {- if (mt && mt->t == J_ARR) c->sparse[i] = (strcmp(mt->kids[i]->str,"sparse")==0);+ const char *mtype = LT_STR(mt, i);+ if (mtype) c->sparse[i] = (strcmp(mtype,"sparse")==0);else c->sparse[i] = (i >= dense_idx);}+ #undef LT_STRfree(buf); free(arena);}@@ -557,7 +577,18 @@ static float *load_t(Model *m, const char *name) {}static float load_scalar(Model *m, const char *name, float dflt) {if (!st_has(&m->S, name)) return dflt;- float v; st_read_f32(&m->S, name, &v, 0); return v;+ /* SEC: `v` is four bytes on the stack, and st_read_f32 writes as many as+ * the FILE says the tensor holds -- it validates the header against itself+ * (numel*esz == nbytes) and cannot know the destination size. A crafted+ * snapshot declaring e.g. model.layers.0.mlp.gate.global_scale as F32+ * shape [4096] therefore drops 16 KiB of attacker bytes over this frame+ * and its return address; the reported crash had RSP fully controlled.+ *+ * st_read_f32_cap is the same read with the caller's capacity passed in.+ * A scalar's capacity is 1. Anything larger is a hostile or corrupt file+ * and stops the load, which is the behaviour every other bounds check in+ * st.h already has. */+ float v; st_read_f32_cap(&m->S, name, &v, 1, 0); return v;}/* chunked pread: a single pread caps at ~2.1 GB on Linux, and the bf16@@ -1202,7 +1233,9 @@ static void moe(Model *m, Layer *l, int layer, float *x, int S, float *out) {float ch = sigmoidf(lg[e]) + l->rbias[e];if (!taken && ch > bv) { bv = ch; best = e; }}- si[kk] = best;+ /* SEC: all-NaN logits leave best at -1, and lg[-1] / eusage[-1] are+ * next. See rt_router_pick in route_trace.h. */+ si[kk] = rt_router_pick(best, kk, E, layer);}/* combine weights: sigmoids of the raw logits of (topK routed + shared),* normalized to sum 1 over all K+ns, x route_scale x gate.global_scale */@@ -1761,7 +1794,21 @@ static int serve_read_cmd(const char *cur_id) {int nf = sscanf(ln, "%*s %*s %d %d %d %f %f %d", &slot, &plen, &max_tok, &temp, &top_p, &alen);/* 6th field (optional, backward compatible): DMel byte count appended* verbatim after the text payload — frames x mel_bins u8 levels */- if (nf < 5 || plen < 0 || plen > (1<<22) || alen < 0 || alen > (1<<26)) {+ /* SEC: max_tok was the one field nobody validated, and it is the one+ * the context check is built on. prompt_reject() asks+ * `np + want > ctx_max`; a negative `want` makes that sum smaller than+ * np, so the check passes for any prompt length. kv_alloc() is then+ * sized on the same np + max_tok + 8 and comes out shorter than the+ * prompt, and prefill writes past the end of the K/V cache -- a heap+ * overflow whose length and contents both follow from the request.+ *+ * The official gateway forces a positive integer, so this is not+ * reachable through openai_server.py. The SERVE protocol is public and+ * anything bridging it (socat, a custom gateway, a sidecar) exposes it+ * directly, so the check belongs here, next to the one plen already+ * has, rather than in one of its callers. */+ if (nf < 5 || plen < 0 || plen > (1<<22) || alen < 0 || alen > (1<<26) ||+ max_tok < 1 || max_tok > (1<<20)) {printf("ERROR %s bad submit header\n", id); fflush(stdout); return 0; }(void)slot;char *pl = malloc((size_t)plen + 1);diff --git a/c/kimi_k3.c b/c/kimi_k3.cindex d7e1ad34..c056c908 100644--- a/c/kimi_k3.c+++ b/c/kimi_k3.c@@ -1156,6 +1156,9 @@ static void moe_forward(Model *m, Layer *l, int li, const float *x, int C, floatfloat sv=st[e]+o->rbias[e];if(!taken&&sv>bv){ bv=sv; best=e; }}+ /* SEC: all-NaN scores leave best at -1, and st[-1] is read on the+ * very next expression. See rt_router_pick in route_trace.h. */+ best = rt_router_pick(best, kk, E, li);idx[kk]=best; wsel[kk]=st[best]; /* weight = RAW sigmoid score */}{ float sm=0; for(int kk=0;kk<K;kk++) sm+=wsel[kk];diff --git a/c/olmoe.c b/c/olmoe.cindex 2d15ee7e..41429fe2 100644--- a/c/olmoe.c+++ b/c/olmoe.c@@ -657,7 +657,11 @@ static void moe(Model *m, Layer *l, int layer, float *x, int S, float *out) {int taken = 0; for (int j = 0; j < kk; j++) if (idx[j]==e){taken=1;break;}if (!taken && pr[e] > bv) { bv = pr[e]; best = e; }}- idx[kk] = best; val[kk] = bv;+ /* SEC: all-NaN probabilities leave best at -1, which reaches+ * expert_get() and then last_access[layer*E - 1] -- a heap write at+ * a negative index. See rt_router_pick in route_trace.h. */+ best = rt_router_pick(best, kk, E, layer);+ idx[kk] = best; val[kk] = pr[best];}if (c->norm_topk) { float sm=0; for(int kk=0;kk<K;kk++) sm+=val[kk]; for(int kk=0;kk<K;kk++) val[kk]/=sm; }/* IMPROVEMENT 2: update activation heatmap (before pinning activates) */diff --git a/c/openai_server.py b/c/openai_server.pyindex 7c312c7a..3c41b517 100644--- a/c/openai_server.py+++ b/c/openai_server.py@@ -1708,9 +1708,38 @@ def model_object(model_id, created):return {"id": model_id, "object": "model", "created": created, "owned_by": "colibri"}+def _positive_env(name, default):+ try:+ value = int(os.environ.get(name, "") or default)+ except ValueError:+ return default+ return value if value > 0 else default++class APIServer(ThreadingHTTPServer):daemon_threads = True+ # SEC: ThreadingHTTPServer spawns one thread per TCP connection with no+ # ceiling, and each carries a default 8 MiB stack. Opening connections and+ # never completing a request therefore grows thread count -- and memory --+ # without bound, before any Host check or auth runs. max_queue bounds the+ # inference queue, not the accept loop.+ #+ # 64 is deliberately small: the engine serves one request at a time+ # (kv_slots) behind a queue of 8, so hundreds of concurrent connections buy+ # nothing a dashboard plus a handful of clients does not already have. Over+ # the cap we close immediately rather than queue, so the cost of a flood is+ # paid by the attacker's socket and not by our address space.+ MAX_CONNECTIONS = _positive_env("COLI_MAX_CONNECTIONS", 64)++ # A global cap alone turns memory exhaustion into connection starvation: one+ # attacker holding all 64 slots still locks every real client out. Measured+ # exactly that while testing the cap. So also bound what a single source may+ # hold, and keep it well under the global cap: a browser opens a handful of+ # parallel connections, an SDK fewer, so 8 is generous for any one client and+ # leaves 56 slots that one address cannot touch.+ MAX_CONNECTIONS_PER_IP = _positive_env("COLI_MAX_CONNECTIONS_PER_IP", 8)+def __init__(self, address, engine, model_id, api_key=None, max_tokens=1024,cors_origins=DEFAULT_CORS_ORIGINS, max_queue=8, queue_timeout=300,kv_slots=1, allowed_hosts=()):@@ -1728,16 +1757,106 @@ class APIServer(ThreadingHTTPServer):self.allowed_hosts = tuple(h.strip().lower() for h in allowed_hosts if h and h.strip())self.created = int(time.time())+ self._conn_lock = threading.Lock()+ self._conn_live = 0+ self._conn_by_ip = {}+ self._conn_owner = {}++ def process_request(self, request, client_address):+ """Refuse past the caps instead of spawning an unbounded thread."""+ peer = client_address[0] if client_address else "?"+ with self._conn_lock:+ mine = self._conn_by_ip.get(peer, 0)+ if self._conn_live >= self.MAX_CONNECTIONS:+ reason = "server cap %d" % self.MAX_CONNECTIONS+ elif mine >= self.MAX_CONNECTIONS_PER_IP:+ reason = "per-address cap %d" % self.MAX_CONNECTIONS_PER_IP+ else:+ reason = None+ self._conn_live += 1+ self._conn_by_ip[peer] = mine + 1+ self._conn_owner[id(request)] = peer+ if reason:+ sys.stderr.write("[api] %s - refused: %s\n" % (peer, reason))+ self.shutdown_request(request)+ return+ try:+ super().process_request(request, client_address)+ except BaseException:+ self._release(request)+ raise++ def _release(self, request):+ with self._conn_lock:+ peer = self._conn_owner.pop(id(request), None)+ if peer is None:+ return # never counted, or already released+ if self._conn_live > 0:+ self._conn_live -= 1+ left = self._conn_by_ip.get(peer, 1) - 1+ if left > 0:+ self._conn_by_ip[peer] = left+ else:+ self._conn_by_ip.pop(peer, None) # do not grow a map per peer++ def close_request(self, request):+ self._release(request)+ super().close_request(request)+++class _DeadlineReader:+ """rfile wrapper enforcing a CUMULATIVE deadline on reading one request.++ SEC: `timeout` below is per socket operation, so it restarts on every byte.+ A client dripping one byte every 29 s renews it forever and holds a thread+ and a connection slot indefinitely -- the code's own comment claimed the+ opposite. The deadline here is absolute: every read shrinks the socket+ timeout to the time left, so a drip runs the clock down instead of resetting+ it.++ It covers the request-read phase only. Generation is not on this clock: a+ 600-second answer is normal and must not be cut off, so send_response()+ hands the socket back to the ordinary timeout once the status line is out.+ """++ def __init__(self, raw, sock, per_read, budget):+ self._raw, self._sock, self._per_read = raw, sock, per_read+ self._expires = time.monotonic() + budget++ def _arm(self):+ left = self._expires - time.monotonic()+ if left <= 0:+ raise TimeoutError("request read deadline exceeded")+ self._sock.settimeout(min(self._per_read, left))++ def readline(self, *args):+ self._arm()+ return self._raw.readline(*args)++ def read(self, *args):+ self._arm()+ return self._raw.read(*args)++ def __getattr__(self, name):+ return getattr(self._raw, name)class APIHandler(BaseHTTPRequestHandler):protocol_version = "HTTP/1.1"- timeout = 30 # per-request socket timeout: a slowloris client that dribbles its- # request line/body can't pin a worker thread (and a slot) forever+ timeout = 30 # per socket OPERATION. On its own this does not stop a slowloris:+ # it restarts on every byte received, so a drip renews it forever.+ # READ_DEADLINE below is the cumulative bound that actually does.+ READ_DEADLINE = _positive_env("COLI_READ_DEADLINE", 30) # accept -> request readserver_version = "colibri"_committed = False # status line already on the wire; reset per request below_body_read = False # request body fully consumed, so nothing is left to drain+ def setup(self):+ super().setup()+ # Keep the socket-backed reader; handle_one_request re-wraps it with a+ # fresh deadline per request rather than wrapping a wrapper each time.+ self._raw_rfile = self.rfile+def log_message(self, fmt, *args):sys.stderr.write("[api] %s - %s\n" % (self.address_string(), fmt % args))@@ -1753,8 +1872,19 @@ class APIHandler(BaseHTTPRequestHandler):instead of asking each early return to remember."""self._committed = Falseself._body_read = False+ # Fresh budget per request: a keep-alive connection may serve many, and+ # each is entitled to its own read window -- but none may drip forever.+ self.rfile = _DeadlineReader(self._raw_rfile, self.connection,+ self.timeout, self.READ_DEADLINE)try:super().handle_one_request()+ except TimeoutError:+ # The read budget ran out. Say so and close; do not answer, because+ # we never received a complete request to answer.+ sys.stderr.write("[api] %s - request read deadline exceeded\n"+ % self.address_string())+ self.close_connection = True+ returnexcept (BrokenPipeError, ConnectionResetError):# The client hung up mid-response. That is not an error here, it is# how HTTP clients behave: `coli chat` polls /health while the model@@ -1776,6 +1906,14 @@ class APIHandler(BaseHTTPRequestHandler):"""Single choke point for "the status line is out". Overriding here rather thantracking it at each call site means no responder can forget (#597 item 3)."""self._committed = True+ # The request is fully read by the time anything answers, so the read+ # deadline has done its job. Restore the plain per-operation timeout:+ # generation legitimately takes minutes and must not inherit a clock+ # sized for reading a request header.+ try:+ self.connection.settimeout(self.timeout)+ except OSError:+ passsuper().send_response(code, message)def _drain_request_body(self):@@ -1964,9 +2102,18 @@ class APIHandler(BaseHTTPRequestHandler):self.send_json(200, payload, request_id)returnif path == "/profile":+ # (#SEC-8) same gate as /health and /experts above: this endpoint+ # is served before require_auth(), so an unauthenticated caller+ # reached it even with --api-key set. It carries per-turn+ # telemetry -- prompt and completion token counts, per-phase+ # timings, up to 120 turns -- which describes what the operator+ # is running and how much. The pass that added _is_authed() to+ # the two endpoints above did not reach this one.eng = self.server.engine- payload = {"seq": getattr(eng, "profile_seq", 0) if eng else 0,- "turns": list(getattr(eng, "profile", ()) or ()) if eng else []}+ payload = {"seq": 0, "turns": []}+ if self._is_authed() and eng:+ payload["seq"] = getattr(eng, "profile_seq", 0)+ payload["turns"] = list(getattr(eng, "profile", ()) or ())self.send_json(200, payload, request_id)returnif self.serve_static(path):diff --git a/c/route_trace.h b/c/route_trace.hindex e39b0154..00ae0c34 100644--- a/c/route_trace.h+++ b/c/route_trace.h@@ -351,4 +351,45 @@ static int rt_save(const char *path, int quiet){return 1;}+/* ---- router safety: a top-k pick that is always a valid expert id ----------+ *+ * Every engine selects experts with the same loop:+ *+ * int best = -1; float bv = -1e30f;+ * for (e ...) if (!taken && score[e] > bv) { bv = score[e]; best = e; }+ * idx[kk] = best;+ *+ * If every candidate score is NaN, no comparison succeeds -- NaN > bv is false+ * for any bv -- and `best` stays -1. It is then used directly as an index.+ * Downstream that becomes score[-1] (heap read), usage[-1]++ (heap write) and,+ * because an expert id also picks a file offset, a pread at a negative offset.+ * In a release build none of that faults: the process finishes and returns+ * wrong numbers over quietly corrupted memory, which is worse than a crash.+ *+ * NaN reaches the router from a corrupt or hostile expert tile, or from an fp+ * overflow at an eviction boundary; c/tests/test_logit_nan.c documents both and+ * hardened only the sampling side, which is downstream of this.+ *+ * colibri.c has carried this guard as a private router_best_or_fallback() since+ * that test was written. inkling.c, kimi_k3.c and olmoe.c never received it --+ * the recurring shape of defects in this tree, a fix that lands in one engine+ * and not its siblings. It lives here now because route_trace.h is the one+ * header all four engines already include, and because "which expert did we+ * pick" is exactly what this file is about.+ *+ * Degrading deterministically (to kk, the slot's own index) keeps the selection+ * reproducible and in range; the warning fires once so a poisoned tile is+ * visible without flooding a long generation. */+static int rt_router_pick(int best, int kk, int experts, int layer) {+ if (best >= 0) return best;+ static int rt_router_warned;+ if (!rt_router_warned) {+ rt_router_warned = 1;+ fprintf(stderr, "[router] non-finite logits at layer %d: selection degraded "+ "(corrupt expert tile, or overflow at an eviction boundary)\n",+ layer);+ }+ return kk < experts ? kk : 0;+}+#endif /* ROUTE_TRACE_H */diff --git a/c/tests/test_openai_server.py b/c/tests/test_openai_server.pyindex 796bba02..4153858a 100644--- a/c/tests/test_openai_server.py+++ b/c/tests/test_openai_server.py@@ -726,9 +726,17 @@ class HTTPTest(unittest.TestCase):self.assertIn("queued", scheduler)self.assertEqual(health["kv_slots"], 2)- def test_profile_reports_recent_turns_without_auth(self):- with urlopen(self.base + "/profile", timeout=2) as response:- self.assertEqual(json.load(response), {"seq": 0, "turns": []})+ def test_profile_requires_auth(self):+ """/profile is served before require_auth(), so it needs its own gate.++ This test previously asserted the opposite -- that the telemetry was+ readable without a key. That was not a client requirement: the web+ dashboard sends `Authorization: Bearer` to /profile exactly as it does+ to /health and /experts (web/src/lib/api.ts). The turns carry prompt and+ completion token counts and per-phase timings for the last 120 requests,+ which describes what the operator is running and how much of it, so an+ anonymous caller now gets the same empty shape those two endpoints give.+ """turn = {"wall_s": 2.5, "prompt_tokens": 7, "completion_tokens": 12,"expert_disk_s": 0.4, "expert_wait_s": 0.1, "expert_matmul_s": 0.9,"attention_s": 0.6, "lm_head_s": 0.2, "forwards": 15}@@ -736,7 +744,11 @@ class HTTPTest(unittest.TestCase):self.engine.profile_seq = 1try:with urlopen(self.base + "/profile", timeout=2) as response:- self.assertEqual(json.load(response), {"seq": 1, "turns": [turn]})+ self.assertEqual(json.load(response), {"seq": 0, "turns": []},+ "unauthenticated caller received telemetry")+ with self.request("/profile") as response:+ self.assertEqual(json.load(response), {"seq": 1, "turns": [turn]},+ "authenticated caller lost access")finally:del self.engine.profile, self.engine.profile_seq@@ -1669,5 +1681,72 @@ class ConversationCacheSlotTest(unittest.TestCase):self.assertEqual(conversation_cache_slot(conv, 8), conversation_cache_slot(conv, 8))+class ConnectionLimitTest(unittest.TestCase):+ """Bounds on the accept loop, which nothing bounded before.++ ThreadingHTTPServer spawns a thread per connection with no ceiling, and+ `timeout` is per socket operation, so it restarts on every byte: a client+ dripping one byte kept a thread and a slot forever. Threads at 8 MiB of+ stack each made that a memory-exhaustion DoS, reachable before any Host+ check or auth.+ """++ def setUp(self):+ self.engine = FakeEngine()+ APIServer.MAX_CONNECTIONS = 6+ APIServer.MAX_CONNECTIONS_PER_IP = 3+ APIHandler.READ_DEADLINE = 2+ self.addCleanup(setattr, APIServer, "MAX_CONNECTIONS", 64)+ self.addCleanup(setattr, APIServer, "MAX_CONNECTIONS_PER_IP", 8)+ self.addCleanup(setattr, APIHandler, "READ_DEADLINE", 30)+ self.server = APIServer(("127.0.0.1", 0), self.engine, "m", None, 16, kv_slots=1)+ threading.Thread(target=self.server.serve_forever, daemon=True).start()+ self.addCleanup(self.server.server_close)+ self.addCleanup(self.server.shutdown)+ self.addCleanup(self.server.scheduler.close)+ self.port = self.server.server_port+ self.held = []+ self.addCleanup(self._drop_all)++ def _drop_all(self):+ for sock in self.held:+ try:+ sock.close()+ except OSError:+ pass++ def _dribble(self, count):+ """Open connections that send a partial request line and never finish."""+ for _ in range(count):+ try:+ sock = socket.create_connection(("127.0.0.1", self.port), 2)+ sock.settimeout(2)+ sock.sendall(b"GET /health HTTP/1.1\r\n")+ self.held.append(sock)+ except OSError:+ pass+ time.sleep(0.4)++ def test_slowloris_cannot_grow_threads_without_bound(self):+ self._dribble(40)+ self.assertLessEqual(self.server._conn_live, APIServer.MAX_CONNECTIONS)++ def test_one_address_cannot_take_every_slot(self):+ """A global cap alone only turns exhaustion into starvation."""+ self._dribble(40)+ self.assertLessEqual(self.server._conn_live,+ APIServer.MAX_CONNECTIONS_PER_IP)+ self.assertLess(self.server._conn_live, APIServer.MAX_CONNECTIONS,+ "one source filled the server cap")++ def test_dripping_connections_are_reclaimed(self):+ """The cumulative deadline, which the per-operation timeout is not."""+ self._dribble(10)+ self.assertGreater(self.server._conn_live, 0)+ time.sleep(APIHandler.READ_DEADLINE + 1.5)+ self.assertEqual(self.server._conn_live, 0,+ "dripping connections were never reclaimed")++if __name__ == "__main__":unittest.main()