Skip to content

Run frontier MoE models on hardware you already own β€” pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

server: local image paths need COLI_IMAGE_ROOT; coli chat sends data URIs

JustVuggb1a7b8d674d5
diff --git a/c/coli b/c/coli
index 2f7424ae..375f65bc 100755
--- a/c/coli
+++ b/c/coli
@@ -1583,9 +1583,21 @@ def message_with_images(text):
if rest:
content.append({"type":"text","text":rest})
for path in found:
- content.append({"type":"image_url","image_url":{"url":path}})
+ # The file is read HERE, with the user's own rights, and travels as a
+ # data: URI. The server no longer opens local paths for a client (an
+ # inference client is not the operator; with the API key it could read
+ # any file the server process can), unless the operator sets
+ # COLI_IMAGE_ROOT, and a path sent by mistake would be refused.
+ content.append({"type":"image_url","image_url":{"url":image_data_uri(path)}})
return content
+def image_data_uri(path):
+ """base64 data: URI of a local image, MIME from the extension (PNG when unknown)."""
+ import base64, mimetypes
+ mime = mimetypes.guess_type(path)[0] or "image/png"
+ with open(path, "rb") as handle:
+ return f"data:{mime};base64," + base64.b64encode(handle.read()).decode("ascii")
+
def cmd_chat(a):
# ATTACH: a running `coli serve` beats a private engine every time β€” the load
diff --git a/c/openai_server.py b/c/openai_server.py
index 3b90bde1..7476fc08 100644
--- a/c/openai_server.py
+++ b/c/openai_server.py
@@ -1640,14 +1640,18 @@ GLM53_IMAGE_OPEN, GLM53_IMAGE, GLM53_IMAGE_CLOSE = (
def _image_bytes_from_url(url):
"""data: URI, file:// o percorso sul disco -> i byte dell'immagine.
- A local path is read with the server process's own permissions. On a
- server that binds beyond loopback (which already requires an API key),
- an authenticated client could otherwise read any file the process can
- reach -- e.g. "file:///etc/passwd". Two guards without breaking the
- documented loopback single-user case: '..' is refused outright (never
- needed for a real image path), and if COLI_IMAGE_ROOT is set the resolved
- path must stay inside it, mirroring serve_static's relative_to() check.
- Errors stay generic so the reply never confirms a path or its permissions."""
+ A local path is read with the server process's own permissions, and an
+ inference client is not the operator: with the API key it could read any
+ file the process can reach ("file:///etc/passwd", or a bare "/etc/passwd").
+ #1354 refused '..' and confined reads to COLI_IMAGE_ROOT when set, which
+ left every absolute path readable on the default install (the variable is
+ unset out of the box). So local paths are now denied unless the operator
+ sets COLI_IMAGE_ROOT, and then only inside it (resolve() follows symlinks
+ before the relative_to() check, the same one serve_static uses). The
+ clients that used to send paths read the file themselves with the user's
+ own rights and send a data: URI: `coli chat` since this change, `coli web`
+ always did. Errors stay generic so a reply never confirms a path or its
+ permissions."""
if not isinstance(url, str) or not url:
raise APIError(400, "image_url.url must be a non-empty string.", "messages")
if url.startswith("data:"):
@@ -1666,13 +1670,20 @@ def _image_bytes_from_url(url):
"as a base64 data: URI or a path on this machine.",
"messages")
raw = url[7:] if url.startswith("file://") else url
+ image_root = os.environ.get("COLI_IMAGE_ROOT")
+ if not image_root:
+ raise APIError(400, "local image paths are disabled on this server: send the image "
+ "as a base64 data: URI (coli chat and coli web do), or start the "
+ "server with COLI_IMAGE_ROOT=<dir> to allow files under that "
+ "directory.", "messages")
if ".." in Path(raw).parts:
raise APIError(400, "image path is not allowed.", "messages")
try:
+ root = Path(image_root).resolve(strict=True)
+ if not root.is_dir():
+ raise ValueError("COLI_IMAGE_ROOT is not a directory")
target = Path(raw).resolve()
- image_root = os.environ.get("COLI_IMAGE_ROOT")
- if image_root:
- target.relative_to(Path(image_root).resolve())
+ target.relative_to(root)
except (ValueError, OSError):
raise APIError(400, "image path is not allowed.", "messages")
try:
diff --git a/c/tests/test_chat_images.py b/c/tests/test_chat_images.py
new file mode 100644
index 00000000..ac23aede
--- /dev/null
+++ b/c/tests/test_chat_images.py
@@ -0,0 +1,59 @@
+"""`coli chat` reads a pasted image itself and sends a data: URI: the server no
+longer opens local paths for a client (see ImageUrlPathGuard in
+test_openai_server). A path the user pastes must therefore never reach the
+request as a path."""
+import base64
+import importlib.machinery
+import importlib.util
+import os
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+CLI = Path(__file__).resolve().parent.parent / "coli"
+
+
+def load_cli():
+ loader = importlib.machinery.SourceFileLoader("coli_images_t", str(CLI))
+ spec = importlib.util.spec_from_loader(loader.name, loader)
+ module = importlib.util.module_from_spec(spec)
+ argv = sys.argv
+ sys.argv = ["coli"]
+ try:
+ loader.exec_module(module)
+ finally:
+ sys.argv = argv
+ return module
+
+
+class ChatImagesTest(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.m = load_cli()
+
+ def test_pasted_path_becomes_a_data_uri(self):
+ with tempfile.TemporaryDirectory() as d:
+ img = Path(d) / "shot.png"
+ img.write_bytes(b"\x89PNG\r\n\x1a\n")
+ content = self.m.message_with_images(f"what is this {img} ?")
+ self.assertIsInstance(content, list)
+ parts = {p["type"]: p for p in content}
+ self.assertEqual(parts["text"]["text"], "what is this ?")
+ url = parts["image_url"]["image_url"]["url"]
+ self.assertTrue(url.startswith("data:image/png;base64,"), url)
+ self.assertEqual(base64.b64decode(url.split(",", 1)[1]), b"\x89PNG\r\n\x1a\n")
+ self.assertNotIn(str(img), url)
+
+ def test_jpeg_gets_its_mime(self):
+ with tempfile.TemporaryDirectory() as d:
+ img = Path(d) / "photo.jpg"
+ img.write_bytes(b"\xff\xd8\xff")
+ self.assertTrue(self.m.image_data_uri(str(img)).startswith("data:image/jpeg;base64,"))
+
+ def test_plain_text_is_untouched(self):
+ self.assertEqual(self.m.message_with_images("no images here"), "no images here")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/c/tests/test_openai_server.py b/c/tests/test_openai_server.py
index dcb39ce3..b08d5dff 100644
--- a/c/tests/test_openai_server.py
+++ b/c/tests/test_openai_server.py
@@ -2588,8 +2588,10 @@ class ReasoningEffortTest(unittest.TestCase):
class ImageUrlPathGuard(unittest.TestCase):
- """image_url.url points at a local file read with the server's rights.
- A '..' path is refused; COLI_IMAGE_ROOT confines reads; errors stay
+ """image_url.url naming a local file is read with the server's rights, so
+ it is denied unless the operator sets COLI_IMAGE_ROOT, and then only
+ inside it (GHSA follow-up to #1354, whose guards left every absolute path
+ readable by default). data: URIs are the client's way in. Errors stay
generic so a reply never confirms a path or its permissions."""
def setUp(self):
@@ -2600,31 +2602,62 @@ class ImageUrlPathGuard(unittest.TestCase):
if self._saved is not None:
os.environ["COLI_IMAGE_ROOT"] = self._saved
- def test_reads_a_plain_file_by_default(self):
+ def test_data_uri_is_the_default_way_in(self):
+ import base64
+ payload = base64.b64encode(b"\x89PNG\r\n").decode()
+ self.assertEqual(_image_bytes_from_url("data:image/png;base64," + payload), b"\x89PNG\r\n")
+
+ def test_local_paths_are_denied_by_default(self):
with tempfile.TemporaryDirectory() as root:
img = Path(root) / "pic.png"
img.write_bytes(b"\x89PNG\r\n")
- self.assertEqual(_image_bytes_from_url(str(img)), b"\x89PNG\r\n")
- self.assertEqual(_image_bytes_from_url("file://" + str(img)),
- b"\x89PNG\r\n")
-
- def test_dotdot_is_refused(self):
- with self.assertRaises(APIError) as caught:
- _image_bytes_from_url("/var/data/../../etc/passwd")
- self.assertEqual(caught.exception.status, 400)
- self.assertNotIn("passwd", str(caught.exception))
-
- def test_image_root_confines_reads(self):
+ for url in (str(img), "file://" + str(img), "/etc/passwd", "file:///etc/passwd", "relative.png"):
+ with self.assertRaises(APIError) as caught:
+ _image_bytes_from_url(url)
+ self.assertEqual(caught.exception.status, 400)
+ self.assertIn("COLI_IMAGE_ROOT", str(caught.exception))
+ self.assertNotIn("passwd", str(caught.exception))
+
+ def test_image_root_allows_inside_and_refuses_outside(self):
with tempfile.TemporaryDirectory() as root, \
- tempfile.NamedTemporaryFile() as outside:
+ tempfile.NamedTemporaryFile(suffix=".png") as outside:
os.environ["COLI_IMAGE_ROOT"] = root
inside = Path(root) / "ok.png"
inside.write_bytes(b"ok")
self.assertEqual(_image_bytes_from_url(str(inside)), b"ok")
+ self.assertEqual(_image_bytes_from_url("file://" + str(inside)), b"ok")
+ for url in (outside.name, "/etc/passwd", str(Path(root) / ".." / Path(outside.name).name)):
+ with self.assertRaises(APIError) as caught:
+ _image_bytes_from_url(url)
+ self.assertNotIn(Path(outside.name).name, str(caught.exception))
+
+ def test_a_symlink_escaping_the_root_is_refused(self):
+ if not hasattr(os, "symlink"):
+ self.skipTest("no symlinks here")
+ with tempfile.TemporaryDirectory() as root, \
+ tempfile.NamedTemporaryFile(suffix=".png") as outside:
+ os.environ["COLI_IMAGE_ROOT"] = root
+ link = Path(root) / "link.png"
+ try:
+ os.symlink(outside.name, link)
+ except OSError:
+ self.skipTest("cannot create symlinks here")
+ with self.assertRaises(APIError):
+ _image_bytes_from_url(str(link))
+
+ def test_a_missing_or_file_root_denies_everything(self):
+ with tempfile.TemporaryDirectory() as root:
+ img = Path(root) / "pic.png"
+ img.write_bytes(b"x")
+ os.environ["COLI_IMAGE_ROOT"] = str(Path(root) / "nowhere")
+ with self.assertRaises(APIError):
+ _image_bytes_from_url(str(img))
+ os.environ["COLI_IMAGE_ROOT"] = str(img)
with self.assertRaises(APIError):
- _image_bytes_from_url(outside.name)
+ _image_bytes_from_url(str(img))
def test_error_does_not_leak_the_path(self):
+ os.environ["COLI_IMAGE_ROOT"] = tempfile.gettempdir()
with self.assertRaises(APIError) as caught:
_image_bytes_from_url("/no/such/secret-name.png")
self.assertNotIn("secret-name", str(caught.exception))
diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md
index aa0584f1..53664bd0 100644
--- a/docs/ENVIRONMENT.md
+++ b/docs/ENVIRONMENT.md
@@ -462,6 +462,7 @@ These are read by the Python programs (not the `glm` engine), so they don't appe
| `COLI_MODEL` | unset | Default model directory (fallback for `--model`). |
| `COLI_MODEL_ID` | `glm-5.2-colibri` | Model id reported by the API. |
| `COLI_API_KEY` | unset | Required bearer token for the server. |
+| `COLI_IMAGE_ROOT` | unset (local paths denied) | Directory under which an `image_url.url` naming a local path or `file://` URI may be read. Unset, the server refuses local paths: a client sends images as base64 `data:` URIs (`coli chat` and `coli web` do), because a file read here happens with the server's own rights and an inference client is not the operator. Set it to allow paths under one directory only; symlinks are resolved before the check. |
| `COLI_ALLOWED_HOSTS` | unset | Comma-separated hostnames or IP addresses accepted by the DNS-rebinding guard in addition to loopback and the bind address. Equivalent to repeating `--allowed-host`. |
| `COLI_MAX_QUEUE` | `8` | Max queued requests. |
| `COLI_QUEUE_TIMEOUT` | `300` | Seconds a request may wait in the queue. |
diff --git a/docs/glm53-flash.md b/docs/glm53-flash.md
index 58bbcb5d..322f3bf4 100644
--- a/docs/glm53-flash.md
+++ b/docs/glm53-flash.md
@@ -102,9 +102,12 @@ hold experts rather than as an accelerator here.
## Vision
-Reachable from every surface: a path pasted in `coli chat`, a file attached or
-dropped in `coli web`, or an OpenAI `image_url` part with a base64 data URI or a
-local path. Remote URLs are refused rather than fetched β€” a request should not
+Reachable from every surface: a path pasted in `coli chat` (read by the client,
+sent as a data URI), a file attached or dropped in `coli web`, or an OpenAI
+`image_url` part with a base64 data URI. A local path in the request is read
+only under `COLI_IMAGE_ROOT` (see `docs/ENVIRONMENT.md`): a file read by the
+server happens with its own rights, and an inference client is not the
+operator. Remote URLs are refused rather than fetched β€” a request should not
make the server open a network connection of the sender's choosing.
`tools/glm53_image.py` does the preprocessing and is pinned against the official
diff --git a/docs/qwen38.md b/docs/qwen38.md
index 507b6389..c771870a 100644
--- a/docs/qwen38.md
+++ b/docs/qwen38.md
@@ -275,8 +275,10 @@ arithmetic rather than a defect, and the threshold sits between it and the
### Wired up
-Images work end to end. Send an OpenAI `image_url` part with a base64 data URI or
-a local path; the gateway preprocesses it, replaces the part with
+Images work end to end. Send an OpenAI `image_url` part with a base64 data URI
+(a local path is accepted only under `COLI_IMAGE_ROOT`, see
+`docs/ENVIRONMENT.md`; `coli chat` reads a pasted path itself and sends the
+data URI); the gateway preprocesses it, replaces the part with
`<|vision_start|>` + N x `<|image_pad|>` + `<|vision_end|>`, and hands the patches
to the engine in an `IMAGE` frame ahead of the `SUBMIT` they belong to. The engine
runs the tower once and substitutes its output for the embedding of each