From 039f9e9018e579e46d4924e4d8aff4cde7fd15b8 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 7 Oct 2026 21:08:03 +0200 Subject: [PATCH] serve: malformed-shape bodies get a 400 with the traceback logged, a body-size cap (256 MiB, STRATA_MAX_BODY_MIB) and a bad Content-Length are answered before the read; engine warns on --batch-groups with --batch-mtp (#1413) --- serve/server.py | 44 ++++++++++++++- serve/test_request_hardening.py | 97 +++++++++++++++++++++++++++++++++ src/program/generate.cpp | 5 ++ 3 files changed, 143 insertions(+), 3 deletions(-) create mode 100644 serve/test_request_hardening.py diff --git a/serve/server.py b/serve/server.py index eae53927..2bb5e8a2 100644 --- a/serve/server.py +++ b/serve/server.py @@ -4022,6 +4022,17 @@ def anthropic_collect(events) -> dict: CHUNKED_BODY_MAX = 256 << 20 # #893: the most a Transfer-Encoding: chunked body may hold (read into memory) +def body_limit() -> int: + """The most a request body may hold, in bytes (read into memory): 256 MiB, which is a million-token conversation + with room to spare; STRATA_MAX_BODY_MIB changes it (0 or an unreadable value: the default). A larger one is + answered 413 before it is read (a Content-Length of 10 TB used to be read until the client gave up).""" + try: + mib = int(os.environ.get("STRATA_MAX_BODY_MIB", "0")) + except ValueError: + mib = 0 + return mib << 20 if mib > 0 else CHUNKED_BODY_MAX + + class BadBody(Exception): """A request body that cannot be read (a malformed or oversized chunked body): the status and the sentence.""" @@ -4043,9 +4054,14 @@ def make_handler(svc: Service): pass def handle_one_request(self): + self.answer_started = False super().handle_one_request() self._drain_body() + def send_response(self, code, message=None): + self.answer_started = True # a malformed-request answer can only replace one not yet begun + super().send_response(code, message) + 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.""" @@ -4094,9 +4110,20 @@ def make_handler(svc: Service): def _body(self) -> bytes: self.body_read = True + limit = body_limit() if self._chunked(): - return self._read_chunked(CHUNKED_BODY_MAX) - return self.rfile.read(int(self.headers.get("Content-Length", 0))) + return self._read_chunked(limit) + try: + length = int(self.headers.get("Content-Length", 0)) + except ValueError: + raise BadBody(400, "invalid Content-Length") from None + if length < 0: + raise BadBody(400, "invalid Content-Length") + if length > limit: + self.close_connection = True # the body is not read: the connection ends with the answer + raise BadBody(413, f"the request body is larger than {limit >> 20} MiB " + "(STRATA_MAX_BODY_MIB raises the limit)") + return self.rfile.read(length) def _drain_body(self): """An answer sent before the body was read (a 401, a 403, /load, a method with no handler) must not close @@ -4110,7 +4137,7 @@ def make_handler(svc: Service): return if self._chunked(): try: - self._read_chunked(CHUNKED_BODY_MAX, keep=False, deadline=time.monotonic() + self.DRAIN_SECONDS) + self._read_chunked(body_limit(), keep=False, deadline=time.monotonic() + self.DRAIN_SECONDS) except (BadBody, OSError): self.close_connection = True return @@ -4522,6 +4549,17 @@ def make_handler(svc: Service): "message": str(e)}}) except (GpuBusy, EngineStarting) as e: self._json(503, {"error": {"type": "server_error", "message": str(e)}}) + except (TypeError, KeyError, AttributeError, IndexError, UnicodeError) as e: + # a body that is JSON but the wrong shape ("messages": 5, a content part that is a number): a 400 that + # says so, with the traceback in the log, instead of a dropped connection - unless the answer began + if getattr(self, "answer_started", False): + raise + import traceback + print(f"[strata] 400 malformed request ({type(e).__name__}: {e}):\n" + traceback.format_exc(), + flush=True) + body = {"error": {"type": "invalid_request_error", + "message": f"the request is malformed ({type(e).__name__}: {e})"}} + self._json(400, responses_error_body(body["error"]["message"]) if path == "/v1/responses" else body) except EngineDied as e: # before the answer started (not streamed) self._json(503, {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}}) except EngineStuck as e: # an unload or restart that could not end the engine diff --git a/serve/test_request_hardening.py b/serve/test_request_hardening.py new file mode 100644 index 00000000..93278034 --- /dev/null +++ b/serve/test_request_hardening.py @@ -0,0 +1,97 @@ +"""0.1.41 server hardening: a JSON body of the wrong shape is a 400 (not a dropped connection), an oversized body is a +413 before it is read, a bad Content-Length is a 400. + + python -m unittest serve.test_request_hardening -v +""" +import http.client +import json +import os +import unittest +from pathlib import Path +from unittest import mock + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, MockEngine, Service, body_limit, serve + +ROOT = Path(__file__).resolve().parent.parent + + +class Hardening(unittest.TestCase): + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.svc = Service(MockEngine(tok, "hello there", max_context=4096), 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 post(self, path, body, headers=None): + c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20) + try: + data = body if isinstance(body, bytes) else json.dumps(body).encode() + c.request("POST", path, body=data, headers={"Content-Type": "application/json", **(headers or {})}) + r = c.getresponse() + return r.status, json.loads(r.read() or b"{}") + finally: + c.close() + + def test_wrong_shapes_are_400(self): + for path, body in (("/v1/chat/completions", {"messages": 5}), + ("/v1/chat/completions", {"messages": [7]}), + ("/v1/chat/completions", {"messages": [{"role": "user", "content": 5}]}), + ("/v1/messages", {"messages": [None], "max_tokens": 4}), + ("/v1/messages", {"messages": "hi", "max_tokens": 4}), + ("/v1/chat/completions", {"messages": [{"role": "user", "content": "x"}], "tools": 3})): + with mock.patch("builtins.print"): + code, out = self.post(path, body) + self.assertEqual(code, 400, (path, body, out)) + self.assertIn("error", out) + + def test_not_json_is_400(self): + with mock.patch("builtins.print"): + code, out = self.post("/v1/chat/completions", b"{nope") + self.assertEqual(code, 400, out) + + def test_a_good_request_still_answers(self): + code, out = self.post("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 8}) + self.assertEqual(code, 200, out) + + def test_oversized_content_length_is_413_unread(self): + with mock.patch.dict(os.environ, {"STRATA_MAX_BODY_MIB": "1"}): + self.assertEqual(body_limit(), 1 << 20) + c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20) + c.putrequest("POST", "/v1/chat/completions") + c.putheader("Content-Type", "application/json") + c.putheader("Content-Length", str(10 << 40)) # 10 TiB announced, nothing sent + c.endheaders() + r = c.getresponse() + self.assertEqual(r.status, 413) + self.assertIn("STRATA_MAX_BODY_MIB", json.loads(r.read())["error"]["message"]) + c.close() + + def test_negative_or_bad_content_length_is_400(self): + for value in ("-5", "abc"): + c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20) + c.putrequest("POST", "/v1/chat/completions") + c.putheader("Content-Type", "application/json") + c.putheader("Content-Length", value) + c.endheaders() + r = c.getresponse() + self.assertEqual(r.status, 400, value) + c.close() + + def test_default_limit_is_generous(self): + with mock.patch.dict(os.environ, {}, clear=False): + os.environ.pop("STRATA_MAX_BODY_MIB", None) + self.assertEqual(body_limit(), 256 << 20) + with mock.patch.dict(os.environ, {"STRATA_MAX_BODY_MIB": "junk"}): + self.assertEqual(body_limit(), 256 << 20) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/program/generate.cpp b/src/program/generate.cpp index e408b93f..312f4cec 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -8326,6 +8326,11 @@ int main(int argc, char** argv) { // ---- --batch-groups: the slot groups pipelined through the stages (--batch-groups G > 1 with a layer split) const int n_pipe = (int) stages.size() + 1; const bool piped = o.batch > 0 && o.batch_groups > 1 && n_pipe > 1; + if (piped && batch_mtp) // #1413: said, not silent + std::fprintf(stderr, + "strata generate: WARNING: --batch-groups %d runs the pipelined path, which builds one row per slot: " + "--batch-mtp's per-slot MTP drafts do not run there (their drafters still hold VRAM, about 0.9 GB per " + "slot). Drop --batch-mtp, or use --batch-groups 1.\n", o.batch_groups); const int GS = piped ? o.batch / o.batch_groups : o.batch; struct PGroup { bool inflight = false;