okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-142-small' into f-142f5aa356f1

main
7.3 KiB154 linesraw
1"""#893 / #894: a request body sent as Transfer-Encoding: chunked (a relay or proxy) is decoded, on every route that
2reads a body; a malformed or oversized one is a 400 / 413, not an empty body. Incomplete chunked framing must not
3apply an otherwise valid JSON body.
4
5    python -m unittest serve.test_chunked_body -v
6"""
7import json
8import socket
9import unittest
10from pathlib import Path
11
12from serve.frontend import ChatTemplate
13from serve.server import ByteTokenizer, MockEngine, Service, serve
14import serve.server as server
15
16ROOT = Path(__file__).resolve().parent.parent
17CRLF = b"\r\n"
18
19
20def chunked(data: bytes, size: int = 7, trailers: bytes = b"") -> bytes:
21    out = b""
22    for i in range(0, len(data), size):
23        piece = data[i:i + size]
24        out += b"%x;ext=1" % len(piece) + CRLF + piece + CRLF
25    return out + b"0" + CRLF + trailers + CRLF
26
27
28class ChunkedBody(unittest.TestCase):
29    @classmethod
30    def setUpClass(cls):
31        tok = ByteTokenizer()
32        cls.engine = MockEngine(tok, "hello there", max_context=4096)
33        cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
34        cls.httpd = serve(cls.svc, port=0)
35        cls.port = cls.httpd.server_address[1]
36
37    @classmethod
38    def tearDownClass(cls):
39        cls.httpd.shutdown()
40        cls.httpd.server_close()
41
42    def send(self, head: bytes, body: bytes):
43        """-> (status, JSON body) of one raw request."""
44        with socket.create_connection(("127.0.0.1", self.port), timeout=20) as s:
45            s.sendall(b"POST " + head + b"Host: 127.0.0.1" + CRLF + b"Connection: close" + CRLF + CRLF + body)
46            s.shutdown(socket.SHUT_WR)
47            data = b""
48            while True:
49                piece = s.recv(65536)
50                if not piece:
51                    break
52                data += piece
53        status = int(data.split(b" ", 2)[1])
54        payload = data.split(CRLF + CRLF, 1)[1]
55        return status, (json.loads(payload) if payload.strip().startswith(b"{") else payload)
56
57    def chat(self, extra: bytes, body: bytes):
58        return self.send(b"/v1/chat/completions HTTP/1.1" + CRLF + b"Content-Type: application/json" + CRLF + extra, body)
59
60    def test_a_chunked_chat_request_is_read(self):
61        req = json.dumps({"messages": [{"role": "user", "content": "hi"}], "max_tokens": 20}).encode()
62        status, body = self.chat(b"Transfer-Encoding: chunked" + CRLF, chunked(req))
63        self.assertEqual(status, 200, body)
64        self.assertIn("choices", body)
65
66    def test_chunked_wins_over_content_length(self):
67        req = json.dumps({"messages": [{"role": "user", "content": "hi"}], "max_tokens": 20}).encode()
68        status, body = self.chat(b"Transfer-Encoding: chunked" + CRLF + b"Content-Length: 3" + CRLF,
69                                 chunked(req, trailers=b"X-Trailer: 1" + CRLF))
70        self.assertEqual(status, 200, body)
71
72    def test_a_content_length_request_is_unchanged(self):
73        req = json.dumps({"messages": [{"role": "user", "content": "hi"}], "max_tokens": 20}).encode()
74        status, body = self.chat(b"Content-Length: %d" % len(req) + CRLF, req)
75        self.assertEqual(status, 200, body)
76
77    def test_a_bad_chunk_size_is_a_400(self):
78        status, body = self.chat(b"Transfer-Encoding: chunked" + CRLF, b"zz" + CRLF + b"{}" + CRLF + b"0" + CRLF + CRLF)
79        self.assertEqual(status, 400, body)
80        self.assertIn("chunk", body["error"]["message"])
81
82    def test_a_truncated_chunked_body_is_a_400(self):
83        status, body = self.chat(b"Transfer-Encoding: chunked" + CRLF, b"10" + CRLF + b"{}")
84        self.assertEqual(status, 400, body)
85
86    def test_an_oversized_chunked_body_is_a_413_and_is_never_allocated(self):
87        old = server.CHUNKED_BODY_MAX
88        server.CHUNKED_BODY_MAX = 1000
89        try:
90            status, body = self.chat(b"Transfer-Encoding: chunked" + CRLF, b"FFFFFFFF" + CRLF)   # announces 4 GiB
91            self.assertEqual(status, 413, body)
92            status, body = self.chat(b"Transfer-Encoding: chunked" + CRLF, chunked(b"x" * 3000, size=500))
93            self.assertEqual(status, 413, body)
94        finally:
95            server.CHUNKED_BODY_MAX = old
96
97    def test_a_chunked_settings_body_is_read_too(self):
98        body = json.dumps({"defaults": {"temperature": 0.5}}).encode()
99        head = (b"/settings HTTP/1.1" + CRLF + b"Content-Type: application/json" + CRLF +
100                b"Transfer-Encoding: chunked" + CRLF)
101        status, got = self.send(head, chunked(body))
102        self.assertEqual(status, 200, got)
103
104    def assert_settings_body_rejected(self, extra: bytes, body: bytes):
105        previous = dict(self.svc.shared)
106        self.addCleanup(self.svc.set_shared, previous)
107        before = self.svc.set_shared({"temperature": 0.7})
108        head = b"/settings HTTP/1.1" + CRLF + b"Content-Type: application/json" + CRLF + extra
109        status, got = self.send(head, body)
110        self.assertEqual((status, self.svc.shared), (400, before), got)
111
112    def test_incomplete_chunked_trailers_do_not_change_settings(self):
113        body = json.dumps({"defaults": {"temperature": 0.5}}).encode()
114        prefix = chunked(body)[:-len(CRLF)]                 # the zero chunk, without the terminating blank line
115        for tail in (b"", b"X-Trailer: 1", b"X-Trailer: 1" + CRLF, b"\r", b"\n", b" " + CRLF):
116            with self.subTest(tail=tail):
117                self.assert_settings_body_rejected(b"Transfer-Encoding: chunked" + CRLF, prefix + tail)
118
119    def test_chunked_trailer_limit_does_not_change_settings(self):
120        body = json.dumps({"defaults": {"temperature": 0.5}}).encode()
121        prefix = chunked(body)[:-len(CRLF)]
122        for end in (b"", CRLF):
123            with self.subTest(end=end):
124                trailers = (b"X-Trailer: 1" + CRLF) * 64 + end
125                self.assert_settings_body_rejected(b"Transfer-Encoding: chunked" + CRLF, prefix + trailers)
126
127    def test_an_overlong_chunked_trailer_does_not_change_settings(self):
128        body = json.dumps({"defaults": {"temperature": 0.5}}).encode()
129        trailers = b"X-Trailer: " + b"x" * 8193 + CRLF
130        self.assert_settings_body_rejected(b"Transfer-Encoding: chunked" + CRLF, chunked(body, trailers=trailers))
131
132    def test_complete_settings_bodies_still_apply(self):
133        previous = dict(self.svc.shared)
134        self.addCleanup(self.svc.set_shared, previous)
135        body = json.dumps({"defaults": {"temperature": 0.5}}).encode()
136        for extra, framed in ((b"Content-Length: %d" % len(body) + CRLF, body),
137                              (b"Transfer-Encoding: chunked" + CRLF, chunked(body)),
138                              (b"Transfer-Encoding: chunked" + CRLF,
139                               chunked(body, trailers=(b"X-Trailer: 1" + CRLF) * 63))):
140            with self.subTest(extra=extra, size=len(framed)):
141                self.svc.set_shared({"temperature": 0.7})
142                head = b"/settings HTTP/1.1" + CRLF + b"Content-Type: application/json" + CRLF + extra
143                status, got = self.send(head, framed)
144                self.assertEqual((status, self.svc.shared), (200, {"temperature": 0.5}), got)
145
146    def test_a_chunked_control_body_is_consumed(self):
147        head = (b"/unload HTTP/1.1" + CRLF + b"Content-Type: application/json" + CRLF +
148                b"Transfer-Encoding: chunked" + CRLF)
149        status, got = self.send(head, chunked(b"{}"))
150        self.assertIn(status, (200, 409), got)
151
152
153if __name__ == "__main__":
154    unittest.main()