okami.mom/strata

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

Niko1221Merge f-142c-small into f-142407ea8192

main
9.6 KiB176 linesraw
1"""0.1.41 server hardening: a JSON body of the wrong shape is a 400 (not a dropped connection), an oversized body is a
2413 before it is read, a bad Content-Length is a 400, and a sampling field of the wrong type is a 400 that names it.
3
4    python -m unittest serve.test_request_hardening -v
5"""
6import http.client
7import json
8import os
9import unittest
10from pathlib import Path
11from unittest import mock
12
13from serve.frontend import ChatTemplate
14from serve.server import ByteTokenizer, MockEngine, Service, body_limit, serve
15
16ROOT = Path(__file__).resolve().parent.parent
17
18
19class Hardening(unittest.TestCase):
20    @classmethod
21    def setUpClass(cls):
22        tok = ByteTokenizer()
23        cls.svc = Service(MockEngine(tok, "hello there", max_context=4096), tok,
24                          ChatTemplate(ROOT / "serve/chat_template.jinja"))
25        cls.httpd = serve(cls.svc, port=0)
26        cls.port = cls.httpd.server_address[1]
27
28    @classmethod
29    def tearDownClass(cls):
30        cls.httpd.shutdown()
31        cls.httpd.server_close()
32
33    def post(self, path, body, headers=None):
34        c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20)
35        try:
36            data = body if isinstance(body, bytes) else json.dumps(body).encode()
37            c.request("POST", path, body=data, headers={"Content-Type": "application/json", **(headers or {})})
38            r = c.getresponse()
39            return r.status, json.loads(r.read() or b"{}")
40        finally:
41            c.close()
42
43    def test_wrong_shapes_are_400(self):
44        for path, body in (("/v1/chat/completions", {"messages": 5}),
45                           ("/v1/chat/completions", {"messages": [7]}),
46                           ("/v1/chat/completions", {"messages": [{"role": "user", "content": 5}]}),
47                           ("/v1/messages", {"messages": [None], "max_tokens": 4}),
48                           ("/v1/messages", {"messages": "hi", "max_tokens": 4}),
49                           ("/v1/chat/completions", {"messages": [{"role": "user", "content": "x"}], "tools": 3})):
50            with mock.patch("builtins.print"):
51                code, out = self.post(path, body)
52            self.assertEqual(code, 400, (path, body, out))
53            self.assertIn("error", out)
54
55    def test_not_json_is_400(self):
56        with mock.patch("builtins.print"):
57            code, out = self.post("/v1/chat/completions", b"{nope")
58        self.assertEqual(code, 400, out)
59
60    def test_a_good_request_still_answers(self):
61        code, out = self.post("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 8})
62        self.assertEqual(code, 200, out)
63
64    def test_oversized_content_length_is_413_unread(self):
65        with mock.patch.dict(os.environ, {"STRATA_MAX_BODY_MIB": "1"}):
66            self.assertEqual(body_limit(), 1 << 20)
67            c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20)
68            c.putrequest("POST", "/v1/chat/completions")
69            c.putheader("Content-Type", "application/json")
70            c.putheader("Content-Length", str(10 << 40))          # 10 TiB announced, nothing sent
71            c.endheaders()
72            r = c.getresponse()
73            self.assertEqual(r.status, 413)
74            self.assertIn("STRATA_MAX_BODY_MIB", json.loads(r.read())["error"]["message"])
75            c.close()
76
77    def test_negative_or_bad_content_length_is_400(self):
78        for value in ("-5", "abc"):
79            c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20)
80            c.putrequest("POST", "/v1/chat/completions")
81            c.putheader("Content-Type", "application/json")
82            c.putheader("Content-Length", value)
83            c.endheaders()
84            r = c.getresponse()
85            self.assertEqual(r.status, 400, value)
86            c.close()
87
88    def test_default_limit_is_generous(self):
89        with mock.patch.dict(os.environ, {}, clear=False):
90            os.environ.pop("STRATA_MAX_BODY_MIB", None)
91            self.assertEqual(body_limit(), 256 << 20)
92        with mock.patch.dict(os.environ, {"STRATA_MAX_BODY_MIB": "junk"}):
93            self.assertEqual(body_limit(), 256 << 20)
94
95    # A request whose sampling field has the wrong JSON type is a 400 that names the field, not a greedy reply.
96    # Only types are checked: in-type values of any range, and null fields, answer as before.
97    def test_a_wrong_type_is_a_400_that_names_the_field(self):
98        chat = {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 8}
99        responses = {"model": "m", "input": "hi", "store": False, "max_output_tokens": 8}
100        for path, body, field in (
101                ("/v1/chat/completions", {**chat, "temperature": "abc"}, "temperature"),
102                ("/v1/chat/completions", {**chat, "top_k": 40.0}, "top_k"),
103                ("/v1/chat/completions", {**chat, "seed": "x7"}, "seed"),
104                ("/v1/messages", {**chat, "top_k": [40]}, "top_k"),
105                ("/v1/messages", {**chat, "repetition_penalty": {"a": 1}}, "repetition_penalty"),
106                ("/v1/messages", {**chat, "presence_penalty": True}, "presence_penalty"),
107                ("/v1/responses", {**responses, "top_p": True}, "top_p"),
108                ("/v1/responses", {**responses, "temperature": "hot"}, "temperature"),
109                ("/v1/responses", {**responses, "seed": 7.5}, "seed"),
110                ("/v1/messages/count_tokens", {"messages": chat["messages"], "temperature": "abc"},
111                 "temperature")):
112            with self.subTest(path=path, field=field):
113                with mock.patch("builtins.print"):
114                    code, out = self.post(path, body)
115                self.assertEqual(code, 400, (path, body, out))
116                self.assertIn(field, json.dumps(out))
117
118    def test_numeric_strings_are_read_and_used(self):
119        from serve.server import check_request_sampling
120        req = {"temperature": "0.7", "top_p": " 1 ", "top_k": "40", "seed": "7", "top_k_x": "keep", "min_p": "0"}
121        check_request_sampling(req)
122        self.assertEqual((req["temperature"], req["top_p"], req["top_k"], req["seed"], req["min_p"]),
123                         (0.7, 1, 40, 7, 0))
124        self.assertEqual(req["top_k_x"], "keep")
125        for bad in ({"top_k": "40.5"}, {"top_k": "abc"}, {"temperature": "nan"}, {"temperature": "true"},
126                    {"seed": ""}, {"temperature": [1]}):
127            with self.subTest(bad=bad), self.assertRaises(ValueError):
128                check_request_sampling(dict(bad))
129        code, out = self.post("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}],
130                                                       "max_tokens": 8, "temperature": "0.7", "top_k": "40"})
131        self.assertEqual(code, 200, out)
132
133    def test_llama_cpp_names_for_the_repetition_penalty(self):
134        """#1819: repeat_penalty / repeat_last_n are repetition_penalty / penalty_last_n; the OpenAI-style name wins."""
135        from serve.server import SAMPLING_ALIASES, check_request_sampling, sampling_defaults_from_config
136        req = {"repeat_penalty": 1.1, "repeat_last_n": 128}
137        check_request_sampling(req)
138        self.assertEqual((req["repetition_penalty"], req["penalty_last_n"]), (1.1, 128))
139        req = {"repeat_penalty": 1.3, "repetition_penalty": 1.05, "repeat_last_n": 9, "penalty_last_n": 32}
140        check_request_sampling(req)
141        self.assertEqual((req["repetition_penalty"], req["penalty_last_n"]), (1.05, 32))
142        req = {"repeat_last_n": 0}                      # off / -1: the engine's default window, nothing is set
143        check_request_sampling(req)
144        self.assertNotIn("penalty_last_n", req)
145        with self.assertRaises(ValueError):
146            check_request_sampling({"repeat_penalty": "abc"})
147        self.assertEqual(sampling_defaults_from_config({"sampling": {"repeat_penalty": 1.1, "repeat_last_n": 256}}),
148                         {"repetition_penalty": 1.1, "penalty_last_n": 256})
149        self.assertEqual(sampling_defaults_from_config({"sampling": {"temperature": 0.6}}), {"temperature": 0.6})
150        with self.assertRaises(SystemExit):
151            sampling_defaults_from_config({"sampling": {"repeat_penalty": 1.1, "repetition_penalty": 1.2}})
152        with self.assertRaises(SystemExit):
153            sampling_defaults_from_config({"sampling": {"repeat_penalty": -1}})
154        self.assertEqual(set(SAMPLING_ALIASES.values()), {"repetition_penalty", "penalty_last_n"})
155        code, out = self.post("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}],
156                                                       "max_tokens": 8, "repeat_penalty": 1.1, "repeat_last_n": 64})
157        self.assertEqual(code, 200, out)
158
159    def test_in_type_values_and_nulls_still_answer(self):
160        chat = {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 8, "temperature": 0, "top_k": 0,
161                "seed": 7}
162        code, out = self.post("/v1/chat/completions", chat)
163        self.assertEqual(code, 200, out)
164        code, out = self.post("/v1/messages", {**chat, "temperature": -1, "top_k": 100, "presence_penalty": 0.5,
165                                               "penalty_last_n": 64})
166        self.assertEqual(code, 200, out)
167        code, out = self.post("/v1/responses", {"model": "m", "input": "hi", "store": False, "max_output_tokens": 8,
168                                                "temperature": None, "top_p": None, "seed": None})
169        self.assertEqual(code, 200, out)
170        code, out = self.post("/v1/messages/count_tokens", {"messages": [{"role": "user", "content": "hi"}],
171                                                            "temperature": 0.7})
172        self.assertEqual(code, 200, out)
173
174
175if __name__ == "__main__":
176    unittest.main()