Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
serve: image sources - network paths refused, URLs capped at 32 MiB and fetched outside the FIFO, no local files for other sites' pages
sergiywith58dd26b9f26c
diff --git a/serve/server.py b/serve/server.pyindex bfc2a4f28..65dad2f8d 100644--- a/serve/server.py+++ b/serve/server.py@@ -43,6 +43,7 @@ import threadingimport timeimport urllib.requestimport uuid+from http.client import HTTPExceptionfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import Pathfrom typing import Iterator, Protocol@@ -1264,6 +1265,17 @@ class StrataEngine:self.progress, self.last = None, {}+IMAGE_URL_MAX = 32 << 20 # an image URL is read up to this (the web app attaches pictures of up to 20 MB)+++def network_path(path: str) -> bool:+ r"""A path to another computer: \\host\share or //host/share (either slash), \\?\UNC\host\..., \\.\UNC\host\...+ or the NT form \??\UNC\host\... Windows connects to that host at the first look at the path (os.path.isfile is+ enough) and signs in with the user's NTLM credentials. \\?\ and \??\ name local files too; no client needs them."""+ p = path.replace("/", "\\")+ return p.startswith("\\\\") or p.startswith("\\??\\")++class Vision:"""The resident image encoder: `strata-vision` (llama.cpp mtmd + the mmproj file) reads `ENC <image> <out>`lines and writes each image's embeddings; results are cached by the image's hash, so a conversation that@@ -1315,14 +1327,35 @@ class Vision:if source.startswith("data:"):return base64.b64decode(source.split(",", 1)[1])if source.startswith(("http://", "https://")):- req = urllib.request.Request(source, headers={"User-Agent": "strata"})- with urllib.request.urlopen(req, timeout=60) as r:- return r.read()+ return Vision.download(source)path = source[7:] if source.startswith("file://") else source+ # refused before anything looks at the path: file://host/share/x.png is \\host\share\x.png ("file://C:/x.png",+ # a drive, is a client's spelling of file:///C:/x.png)+ host = re.split(r"[/\\]", path, maxsplit=1)[0] if source.startswith("file://") else ""+ if network_path(path) or host and not re.fullmatch(r"[A-Za-z]:|localhost", host, re.IGNORECASE):+ raise ValueError("an image file must be on this computer: network paths (\\\\host\\share, //host/share, "+ "file://host/...) are not read")if path and os.path.isfile(path):return Path(path).read_bytes()raise ValueError("an image must be a data: URL, an http(s) URL or a local file path")+ @staticmethod+ def download(url: str) -> bytes:+ """An image URL's bytes, at most IMAGE_URL_MAX of them: the whole response was read, so a huge or endless one+ filled the memory. One that cannot be read is a ValueError (a 400 that says so), not a dropped connection."""+ too_big = f"the image URL's file is over {IMAGE_URL_MAX >> 20} MiB"+ try:+ with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": "strata"}), timeout=60) as r:+ size = r.headers.get("Content-Length") or ""+ if size.isdigit() and int(size) > IMAGE_URL_MAX:+ raise ValueError(too_big)+ data = r.read(IMAGE_URL_MAX + 1)+ except (OSError, HTTPException) as e:+ raise ValueError(f"the image URL could not be read: {e}") from None+ if len(data) > IMAGE_URL_MAX:+ raise ValueError(too_big)+ return data+@staticmethoddef normalize(data: bytes) -> bytes:"""The formats strata-vision's decoder (stb_image) reads pass through; anything else is converted to PNG."""@@ -1351,9 +1384,9 @@ class Vision:im.save(out, format="PNG")return out.getvalue()- def encode(self, source: str) -> tuple[Path, int]:- """-> (embeddings file, number of image tokens)."""- data = self.normalize(self.load(source))+ def encode(self, source: str | bytes) -> tuple[Path, int]:+ """-> (embeddings file, number of image tokens). `source`: what load() reads, or the image's bytes."""+ data = self.normalize(source if isinstance(source, bytes) else self.load(source))key = hashlib.sha256(data).hexdigest()[:32]with self.lock:if key in self.cache:@@ -2159,6 +2192,9 @@ class Service:"'vision'), so it cannot read images")pad = self.tok.encode(IMAGE_PAD, parse_special=True)[0]start = self.tok.encode(VISION_START, parse_special=True)[0]+ # An image URL is downloaded first, outside the FIFO: under it, a slow server held every other request+ # for as long as urlopen waited.+ images = [Vision.download(src) if src.startswith(("http://", "https://")) else src for src in images]# Encode only while the engine is idle: the engine and the image encoder (a separate process) must not# run on the GPU at the same time - an encode during a running request left that request stuck at# "reading the prompt" with CPU and GPU busy, for good (reproduced). So encoding takes its turn in the@@ -3251,12 +3287,7 @@ def make_handler(svc: Service):if not self.headers.get("Content-Type", "").startswith("application/json"):self._json(415, {"error": {"message": "send application/json"}})return False- # The Origin must be this server's own address (host and port), or an origin the config trusts- # (trusted_origins: the web app behind a reverse proxy or tunnel). Headers a proxy adds (X-Forwarded-*,- # CF-Ray, CF-Connecting-IP) prove nothing about the page that sent the request, so they open nothing.- origin = (self.headers.get("Origin") or "").rstrip("/")- if origin and origin.split("://", 1)[-1] != self.headers.get("Host", "") and \- origin not in svc.trusted_origins:+ if self._foreign_origin():self._json(403, {"error": {"message": f"{what} only from Strata's own page (or an origin in the "f"config's trusted_origins)"}})return False@@ -3299,6 +3330,26 @@ def make_handler(svc: Service):print(f"[strata] the Settings view changed {', '.join(changed)} in {Path(svc.config_path).name} "f"(the earlier file: {bak.name}); used from the next start", flush=True)self._json(200, {**runconfig.view(new, svc.config_path), "changed": changed})+ def _foreign_origin(self) -> bool:+ """A web page of another origin sent this. The Origin must be this server's own address (host and port),+ or an origin the config trusts (trusted_origins: the web app behind a reverse proxy or tunnel); no Origin+ is a client that is no browser. Headers a proxy adds (X-Forwarded-*, CF-Ray, CF-Connecting-IP) prove+ nothing about the page that sent the request, so they open nothing."""+ origin = (self.headers.get("Origin") or "").rstrip("/")+ return bool(origin) and origin.split("://", 1)[-1] != self.headers.get("Host", "") and \+ origin not in svc.trusted_origins++ def _no_local_images(self, messages):+ """A web page of another origin must not have a file on this computer read as an image. Without an+ api_key, _foreign_page refuses such a page unless cors_origins lets it in - and a page cors_origins lets+ in (["*"]: every page) could name any file and, CORS allowing, read what the model says about it. data:+ and http(s) images are the page's own to send; files come from Strata's own page, a trusted origin or a+ client that is no browser. ValueError (a 400)."""+ if self._foreign_origin() and any(not src.startswith(("data:", "http://", "https://"))+ for src in images_of(messages)):+ raise ValueError("a web page of another origin cannot have a file on this computer read as an "+ "image: send it as a data: URL (or add the page's origin to the config's "+ "trusted_origins)")def _settings(self):# They change what every client gets, so only the app's own page may set them@@ -3366,6 +3417,7 @@ def make_handler(svc: Service):def _openai(self, req):req = svc.with_shared(req, "openai")messages, tools, kw = openai_to_messages(req)+ self._no_local_images(messages)messages, validator = prepare_format(req.get("response_format"), messages)if validator is not None and (tools or req.get("strata_mcp")):raise ValueError("structured response_format with tools/MCP is not supported")@@ -3551,6 +3603,7 @@ def make_handler(svc: Service):svc.load()req = svc.with_shared(req, "anthropic")messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked)+ self._no_local_images(messages)max_new = int(req.get("max_tokens") or 0) # 0/-1: the rest of the contextsvc.reasoning_budget(req) # a bad value is a 400 before anything is sentids, thinking, max_new = svc.prepare(messages, tools, kw, max_new)diff --git a/serve/test_server.py b/serve/test_server.pyindex 0ffe2f6c9..34ef69e0b 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -2681,5 +2681,150 @@ class LostStep(unittest.TestCase):self.run_mode("stop", stream=False)+class ImageSources(unittest.TestCase):+ """What an image source may name: never a network path (Windows signs in to the host at the first look), a URL up+ to IMAGE_URL_MAX and downloaded outside the request FIFO, a file on this computer not for a page of another site."""++ NETWORK = [r"\\host\share\x.png", "//host/share/x.png", r"\\?\UNC\host\share\x.png", r"\\.\UNC\host\share\x.png",+ r"\??\UNC\host\share\x.png", r"/\host\share\x.png", "file://host/share/x.png",+ "file:////host/share/x.png", r"file://\\host\share\x.png"]++ class Vision(ImageMarkers.FakeVision):+ def __init__(self, d):+ super().__init__(d)+ self.got = []++ def encode(self, source):+ self.got.append(source)+ return super().encode(source)++ def test_network_paths_are_refused_before_any_look(self):+ from serve.server import Vision+ with mock.patch("os.path.isfile") as isfile, mock.patch.object(Path, "read_bytes") as read:+ for src in self.NETWORK:+ with self.subTest(src=src), self.assertRaisesRegex(ValueError, "network paths"):+ Vision.load(src)+ isfile.assert_not_called()+ read.assert_not_called()+ with tempfile.TemporaryDirectory() as d: # files on this computer load as before+ f = Path(d) / "x.png"+ f.write_bytes(b"\x89PNG\r\n\x1a\n")+ for src in (str(f), "file://" + str(f), "data:image/png;base64,iVBORw0KGgo="):+ with self.subTest(src=src):+ self.assertEqual(Vision.load(src), b"\x89PNG\r\n\x1a\n")++ def test_a_url_is_read_up_to_the_cap(self):+ import http.server+ import serve.server as server++ class Files(http.server.BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_GET(self):+ body = {"/small": b"x" * 100, "/big": b"x" * 5000}.get(urllib.parse.urlsplit(self.path).path)+ if body is None:+ self.send_error(404)+ return+ self.send_response(200)+ if "length" in self.path: # else the body ends when the connection does+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ try:+ self.wfile.write(body)+ except OSError: # the reader stopped at the cap+ pass++ httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Files)+ threading.Thread(target=httpd.serve_forever, daemon=True).start()+ base = f"http://127.0.0.1:{httpd.server_address[1]}"+ try:+ with mock.patch.object(server, "IMAGE_URL_MAX", 1000):+ for q in ("", "?length"):+ with self.subTest(q=q):+ self.assertEqual(server.Vision.load(base + "/small" + q), b"x" * 100)+ with self.assertRaisesRegex(ValueError, "is over"):+ server.Vision.load(base + "/big" + q)+ with self.assertRaisesRegex(ValueError, "could not be read: HTTP Error 404"):+ server.Vision.load(base + "/missing")+ finally:+ httpd.shutdown()+ httpd.server_close()++ def test_a_url_is_downloaded_outside_the_fifo(self):+ import serve.server as server+ tok = ByteTokenizer()+ with tempfile.TemporaryDirectory() as d:+ vision = self.Vision(d)+ svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"),+ vision=vision)+ held = []++ def download(url):+ held.append(svc.fifo.locked())+ return b"the picture"++ msgs = [{"role": "user", "content": [{"type": "image", "source": "https://example.com/x.png"},+ {"type": "image", "source": "x.png"}]}]+ with mock.patch.object(server.Vision, "download", side_effect=download):+ svc.prepare(msgs, None, {})+ self.assertEqual(held, [False]) # not while every other request waits+ self.assertEqual(vision.got, [b"the picture", "x.png"])+ svc.embeddings.path.unlink(missing_ok=True)++ def test_a_page_of_another_site_cannot_name_a_file(self):+ tok = ByteTokenizer()+ with tempfile.TemporaryDirectory() as d:+ vision = self.Vision(d)+ svc = Service(MockEngine(tok, "</think>\n\nok", max_context=CTX), tok,+ ChatTemplate(ROOT / "serve/chat_template.jinja"), vision=vision)+ httpd = serve(svc, port=0)+ host = f"127.0.0.1:{httpd.server_address[1]}"++ def post(path, src, headers):+ image = {"type": "image_url", "image_url": {"url": src}} if path.endswith("completions") else \+ {"type": "image", "source": {"type": "url", "url": src}}+ body = {"model": "m", "max_tokens": 8, "messages": [{"role": "user", "content": [+ {"type": "text", "text": "what is it?"}, image]}]}+ req = urllib.request.Request(f"http://{host}{path}", data=json.dumps(body).encode(), headers=headers)+ try:+ with urllib.request.urlopen(req, timeout=30) as r:+ return r.status, json.loads(r.read())+ except urllib.error.HTTPError as e:+ with e:+ return e.code, json.loads(e.read())++ try:+ f = str(Path(d) / "secret.png")+ # a page on any site, no api_key (the default): text/plain needs no CORS preflight - 0.1.38 refuses+ # such a page outright (403)+ page = {"Content-Type": "text/plain;charset=UTF-8", "Origin": "https://evil.example"}+ status, b = post("/v1/chat/completions", f, page)+ self.assertEqual(status, 403, b)+ # a page cors_origins lets in (here every page) may send JSON, and still cannot name a file+ svc.cors_origins = ["*"]+ page = {"Content-Type": "application/json", "Origin": "https://evil.example"}+ for path in ("/v1/chat/completions", "/v1/messages"):+ for src in (f, "file://" + f):+ with self.subTest(path=path, src=src):+ status, b = post(path, src, page)+ self.assertEqual(status, 400, b)+ self.assertIn("another origin", b["error"]["message"])+ self.assertEqual(vision.got, []) # nothing was read+ svc.trusted_origins = ["https://app.example"]+ data = "data:image/png;base64,iVBORw0KGgo="+ for src, headers in ((data, page), # the page's own picture+ (f, {"Content-Type": "application/json"}), # curl, SDKs, agents+ (f, {"Content-Type": "application/json", "Origin": "http://" + host}),+ (f, {"Content-Type": "application/json", "Origin": "https://app.example"})):+ with self.subTest(src=src[:20], headers=headers):+ status, b = post("/v1/chat/completions", src, headers)+ self.assertEqual(status, 200, b)+ self.assertEqual(vision.got, [data, f, f, f])+ finally:+ httpd.shutdown()+ httpd.server_close()++if __name__ == "__main__":unittest.main()