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: decode chunked request bodies on every route that reads one, with a size cap (#893, #894)
Niko1221be8c29185cba
diff --git a/serve/server.py b/serve/server.pyindex 4030a34a7..30e8f85ce 100644--- a/serve/server.py+++ b/serve/server.py@@ -3598,6 +3598,17 @@ def anthropic_collect(events) -> dict:# ------------------------------------------------------------------------------------------------ HTTP+CHUNKED_BODY_MAX = 256 << 20 # #893: the most a Transfer-Encoding: chunked body may hold (read into memory)+++class BadBody(Exception):+ """A request body that cannot be read (a malformed or oversized chunked body): the status and the sentence."""++ def __init__(self, status: int, message: str):+ super().__init__(message)+ self.status = status++def make_handler(svc: Service):class Handler(BaseHTTPRequestHandler):protocol_version = "HTTP/1.0" # SSE ends by closing the connection@@ -3614,8 +3625,56 @@ def make_handler(svc: Service):super().handle_one_request()self._drain_body()+ def _chunked(self) -> bool:+ """#893: a body sent as Transfer-Encoding: chunked (a relay or proxy that does not buffer it). By RFC 9112+ it wins over a Content-Length."""+ te = self.headers.get("Transfer-Encoding", "") or ""+ return te.split(",")[-1].strip().lower() == "chunked"++ def _read_chunked(self, limit: int, keep: bool = True, deadline: float | None = None) -> bytes:+ """Decode a chunked body: at most `limit` bytes (BadBody 413 beyond it - the size is checked before a chunk+ is read, so a huge announced chunk is never allocated), BadBody 400 for a malformed one. keep=False reads+ and drops it (the drain); `deadline` (monotonic) ends the read early."""+ parts, total = [], 0+ while True:+ if deadline is not None:+ wait = deadline - time.monotonic()+ if wait <= 0:+ return b"".join(parts)+ self.connection.settimeout(wait)+ line = self.rfile.readline(1025)+ if not line.endswith(b"\n"):+ raise BadBody(400, "malformed chunked request body")+ try:+ size = int(line.split(b";", 1)[0].strip(), 16)+ except ValueError:+ raise BadBody(400, "malformed chunk size in the request body") from None+ if size < 0:+ raise BadBody(400, "malformed chunk size in the request body")+ if size == 0:+ for _ in range(64): # the trailers, up to the blank line+ if self.rfile.readline(8193).strip() == b"":+ break+ return b"".join(parts)+ total += size+ if total > limit:+ self.close_connection = True+ raise BadBody(413, f"the request body is larger than {limit >> 20} MiB")+ left = size+ while left > 0:+ piece = self.rfile.read(min(left, 1 << 20))+ if not piece:+ raise BadBody(400, "the chunked request body ended early")+ left -= len(piece)+ if keep:+ parts.append(piece)+ if self.rfile.read(2) != b"\r\n":+ raise BadBody(400, "malformed chunked request body")+def _body(self) -> bytes:self.body_read = True+ if self._chunked():+ return self._read_chunked(CHUNKED_BODY_MAX)return self.rfile.read(int(self.headers.get("Content-Length", 0)))def _drain_body(self):@@ -3628,6 +3687,12 @@ def make_handler(svc: Service):headers = getattr(self, "headers", None)if self.body_read or headers is None:return+ if self._chunked():+ try:+ self._read_chunked(CHUNKED_BODY_MAX, keep=False, deadline=time.monotonic() + self.DRAIN_SECONDS)+ except (BadBody, OSError):+ self.close_connection = True+ returntry:left = int(headers.get("Content-Length", 0))except ValueError:@@ -3897,6 +3962,12 @@ def make_handler(svc: Service):self._json(404, {"error": {"message": "not found"}})def do_POST(self):+ try:+ self._post()+ except BadBody as e: # #893: a malformed or oversized chunked body+ self._json(e.status, {"error": {"type": "invalid_request_error", "message": str(e)}})++ def _post(self):if not self._authorized():returnpath = self.path.split("?")[0].rstrip("/") # issue #55: Claude Code posts /v1/messages?beta=true@@ -4055,6 +4126,18 @@ def make_handler(svc: Service):def _control_body(self) -> bool:"""Consume the unused control body before replying/closing (Windows otherwise sends a TCP reset)."""+ if self._chunked():+ self.body_read = True+ try:+ self.connection.settimeout(2.0)+ self._read_chunked(65536, keep=False)+ except BadBody as e:+ self._json(e.status, {"error": {"message": f"control request: {e}"}})+ return False+ except OSError:+ self._json(400, {"error": {"message": "incomplete control request body"}})+ return False+ return Truetry:length = int(self.headers.get("Content-Length", "0"))except ValueError:diff --git a/serve/test_chunked_body.py b/serve/test_chunked_body.pynew file mode 100644index 000000000..45428a949--- /dev/null+++ b/serve/test_chunked_body.py@@ -0,0 +1,111 @@+"""#893 / #894: a request body sent as Transfer-Encoding: chunked (a relay or proxy) is decoded, on every route that+reads a body; a malformed or oversized one is a 400 / 413, not an empty body.++ python -m unittest serve.test_chunked_body -v+"""+import json+import socket+import unittest+from pathlib import Path++from serve.frontend import ChatTemplate+from serve.server import ByteTokenizer, MockEngine, Service, serve+import serve.server as server++ROOT = Path(__file__).resolve().parent.parent+CRLF = b"\r\n"+++def chunked(data: bytes, size: int = 7, trailers: bytes = b"") -> bytes:+ out = b""+ for i in range(0, len(data), size):+ piece = data[i:i + size]+ out += b"%x;ext=1" % len(piece) + CRLF + piece + CRLF+ return out + b"0" + CRLF + trailers + CRLF+++class ChunkedBody(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ tok = ByteTokenizer()+ cls.engine = MockEngine(tok, "hello there", max_context=4096)+ cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))+ cls.httpd = serve(cls.svc, port=0)+ cls.port = cls.httpd.server_address[1]++ @classmethod+ def tearDownClass(cls):+ cls.httpd.shutdown()+ cls.httpd.server_close()++ def send(self, head: bytes, body: bytes):+ """-> (status, JSON body) of one raw request."""+ with socket.create_connection(("127.0.0.1", self.port), timeout=20) as s:+ s.sendall(b"POST " + head + b"Host: 127.0.0.1" + CRLF + b"Connection: close" + CRLF + CRLF + body)+ s.shutdown(socket.SHUT_WR)+ data = b""+ while True:+ piece = s.recv(65536)+ if not piece:+ break+ data += piece+ status = int(data.split(b" ", 2)[1])+ payload = data.split(CRLF + CRLF, 1)[1]+ return status, (json.loads(payload) if payload.strip().startswith(b"{") else payload)++ def chat(self, extra: bytes, body: bytes):+ return self.send(b"/v1/chat/completions HTTP/1.1" + CRLF + b"Content-Type: application/json" + CRLF + extra, body)++ def test_a_chunked_chat_request_is_read(self):+ req = json.dumps({"messages": [{"role": "user", "content": "hi"}], "max_tokens": 20}).encode()+ status, body = self.chat(b"Transfer-Encoding: chunked" + CRLF, chunked(req))+ self.assertEqual(status, 200, body)+ self.assertIn("choices", body)++ def test_chunked_wins_over_content_length(self):+ req = json.dumps({"messages": [{"role": "user", "content": "hi"}], "max_tokens": 20}).encode()+ status, body = self.chat(b"Transfer-Encoding: chunked" + CRLF + b"Content-Length: 3" + CRLF,+ chunked(req, trailers=b"X-Trailer: 1" + CRLF))+ self.assertEqual(status, 200, body)++ def test_a_content_length_request_is_unchanged(self):+ req = json.dumps({"messages": [{"role": "user", "content": "hi"}], "max_tokens": 20}).encode()+ status, body = self.chat(b"Content-Length: %d" % len(req) + CRLF, req)+ self.assertEqual(status, 200, body)++ def test_a_bad_chunk_size_is_a_400(self):+ status, body = self.chat(b"Transfer-Encoding: chunked" + CRLF, b"zz" + CRLF + b"{}" + CRLF + b"0" + CRLF + CRLF)+ self.assertEqual(status, 400, body)+ self.assertIn("chunk", body["error"]["message"])++ def test_a_truncated_chunked_body_is_a_400(self):+ status, body = self.chat(b"Transfer-Encoding: chunked" + CRLF, b"10" + CRLF + b"{}")+ self.assertEqual(status, 400, body)++ def test_an_oversized_chunked_body_is_a_413_and_is_never_allocated(self):+ old = server.CHUNKED_BODY_MAX+ server.CHUNKED_BODY_MAX = 1000+ try:+ status, body = self.chat(b"Transfer-Encoding: chunked" + CRLF, b"FFFFFFFF" + CRLF) # announces 4 GiB+ self.assertEqual(status, 413, body)+ status, body = self.chat(b"Transfer-Encoding: chunked" + CRLF, chunked(b"x" * 3000, size=500))+ self.assertEqual(status, 413, body)+ finally:+ server.CHUNKED_BODY_MAX = old++ def test_a_chunked_settings_body_is_read_too(self):+ body = json.dumps({"defaults": {"temperature": 0.5}}).encode()+ head = (b"/settings HTTP/1.1" + CRLF + b"Content-Type: application/json" + CRLF ++ b"Transfer-Encoding: chunked" + CRLF)+ status, got = self.send(head, chunked(body))+ self.assertEqual(status, 200, got)++ def test_a_chunked_control_body_is_consumed(self):+ head = (b"/unload HTTP/1.1" + CRLF + b"Content-Type: application/json" + CRLF ++ b"Transfer-Encoding: chunked" + CRLF)+ status, got = self.send(head, chunked(b"{}"))+ self.assertIn(status, (200, 409), got)+++if __name__ == "__main__":+ unittest.main()