okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
407ea8192
main
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 4python -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 21def setUpClass (cls ): 22tok = ByteTokenizer () 23cls .svc = Service (MockEngine (tok ,"hello there" ,max_context = 4096 ),tok , 24ChatTemplate (ROOT / "serve/chat_template.jinja" )) 25cls .httpd = serve (cls .svc ,port = 0 ) 26cls .port = cls .httpd .server_address [1 ] 27 28@classmethod 29def tearDownClass (cls ): 30cls .httpd .shutdown () 31cls .httpd .server_close () 32 33def post (self ,path ,body ,headers = None ): 34c = http .client .HTTPConnection ("127.0.0.1" ,self .port ,timeout = 20 ) 35try : 36data = body if isinstance (body ,bytes )else json .dumps (body ).encode () 37c .request ("POST" ,path ,body = data ,headers = {"Content-Type" :"application/json" ,** (headers or {})}) 38r = c .getresponse () 39return r .status ,json .loads (r .read ()or b"{}" ) 40finally : 41c .close () 42 43def test_wrong_shapes_are_400 (self ): 44for 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 })): 50with mock .patch ("builtins.print" ): 51code ,out = self .post (path ,body ) 52self .assertEqual (code ,400 , (path ,body ,out )) 53self .assertIn ("error" ,out ) 54 55def test_not_json_is_400 (self ): 56with mock .patch ("builtins.print" ): 57code ,out = self .post ("/v1/chat/completions" ,b"{nope" ) 58self .assertEqual (code ,400 ,out ) 59 60def test_a_good_request_still_answers (self ): 61code ,out = self .post ("/v1/chat/completions" , {"messages" : [{"role" :"user" ,"content" :"hi" }],"max_tokens" :8 }) 62self .assertEqual (code ,200 ,out ) 63 64def test_oversized_content_length_is_413_unread (self ): 65with mock .patch .dict (os .environ , {"STRATA_MAX_BODY_MIB" :"1" }): 66self .assertEqual (body_limit (),1 << 20 ) 67c = http .client .HTTPConnection ("127.0.0.1" ,self .port ,timeout = 20 ) 68c .putrequest ("POST" ,"/v1/chat/completions" ) 69c .putheader ("Content-Type" ,"application/json" ) 70c .putheader ("Content-Length" ,str (10 << 40 ))# 10 TiB announced, nothing sent 71c .endheaders () 72r = c .getresponse () 73self .assertEqual (r .status ,413 ) 74self .assertIn ("STRATA_MAX_BODY_MIB" ,json .loads (r .read ())["error" ]["message" ]) 75c .close () 76 77def test_negative_or_bad_content_length_is_400 (self ): 78for value in ("-5" ,"abc" ): 79c = http .client .HTTPConnection ("127.0.0.1" ,self .port ,timeout = 20 ) 80c .putrequest ("POST" ,"/v1/chat/completions" ) 81c .putheader ("Content-Type" ,"application/json" ) 82c .putheader ("Content-Length" ,value ) 83c .endheaders () 84r = c .getresponse () 85self .assertEqual (r .status ,400 ,value ) 86c .close () 87 88def test_default_limit_is_generous (self ): 89with mock .patch .dict (os .environ , {},clear = False ): 90os .environ .pop ("STRATA_MAX_BODY_MIB" ,None ) 91self .assertEqual (body_limit (),256 << 20 ) 92with mock .patch .dict (os .environ , {"STRATA_MAX_BODY_MIB" :"junk" }): 93self .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. 97def test_a_wrong_type_is_a_400_that_names_the_field (self ): 98chat = {"messages" : [{"role" :"user" ,"content" :"hi" }],"max_tokens" :8 } 99responses = {"model" :"m" ,"input" :"hi" ,"store" :False ,"max_output_tokens" :8 } 100for 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" )): 112with self .subTest (path = path ,field = field ): 113with mock .patch ("builtins.print" ): 114code ,out = self .post (path ,body ) 115self .assertEqual (code ,400 , (path ,body ,out )) 116self .assertIn (field ,json .dumps (out )) 117 118def test_numeric_strings_are_read_and_used (self ): 119from serve .server import check_request_sampling 120req = {"temperature" :"0.7" ,"top_p" :" 1 " ,"top_k" :"40" ,"seed" :"7" ,"top_k_x" :"keep" ,"min_p" :"0" } 121check_request_sampling (req ) 122self .assertEqual ((req ["temperature" ],req ["top_p" ],req ["top_k" ],req ["seed" ],req ["min_p" ]), 123 (0.7 ,1 ,40 ,7 ,0 )) 124self .assertEqual (req ["top_k_x" ],"keep" ) 125for bad in ({"top_k" :"40.5" }, {"top_k" :"abc" }, {"temperature" :"nan" }, {"temperature" :"true" }, 126 {"seed" :"" }, {"temperature" : [1 ]}): 127with self .subTest (bad = bad ),self .assertRaises (ValueError ): 128check_request_sampling (dict (bad )) 129code ,out = self .post ("/v1/chat/completions" , {"messages" : [{"role" :"user" ,"content" :"hi" }], 130"max_tokens" :8 ,"temperature" :"0.7" ,"top_k" :"40" }) 131self .assertEqual (code ,200 ,out ) 132 133def 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.""" 135from serve .server import SAMPLING_ALIASES ,check_request_sampling ,sampling_defaults_from_config 136req = {"repeat_penalty" :1.1 ,"repeat_last_n" :128 } 137check_request_sampling (req ) 138self .assertEqual ((req ["repetition_penalty" ],req ["penalty_last_n" ]), (1.1 ,128 )) 139req = {"repeat_penalty" :1.3 ,"repetition_penalty" :1.05 ,"repeat_last_n" :9 ,"penalty_last_n" :32 } 140check_request_sampling (req ) 141self .assertEqual ((req ["repetition_penalty" ],req ["penalty_last_n" ]), (1.05 ,32 )) 142req = {"repeat_last_n" :0 }# off / -1: the engine's default window, nothing is set 143check_request_sampling (req ) 144self .assertNotIn ("penalty_last_n" ,req ) 145with self .assertRaises (ValueError ): 146check_request_sampling ({"repeat_penalty" :"abc" }) 147self .assertEqual (sampling_defaults_from_config ({"sampling" : {"repeat_penalty" :1.1 ,"repeat_last_n" :256 }}), 148 {"repetition_penalty" :1.1 ,"penalty_last_n" :256 }) 149self .assertEqual (sampling_defaults_from_config ({"sampling" : {"temperature" :0.6 }}), {"temperature" :0.6 }) 150with self .assertRaises (SystemExit ): 151sampling_defaults_from_config ({"sampling" : {"repeat_penalty" :1.1 ,"repetition_penalty" :1.2 }}) 152with self .assertRaises (SystemExit ): 153sampling_defaults_from_config ({"sampling" : {"repeat_penalty" :- 1 }}) 154self .assertEqual (set (SAMPLING_ALIASES .values ()), {"repetition_penalty" ,"penalty_last_n" }) 155code ,out = self .post ("/v1/chat/completions" , {"messages" : [{"role" :"user" ,"content" :"hi" }], 156"max_tokens" :8 ,"repeat_penalty" :1.1 ,"repeat_last_n" :64 }) 157self .assertEqual (code ,200 ,out ) 158 159def test_in_type_values_and_nulls_still_answer (self ): 160chat = {"messages" : [{"role" :"user" ,"content" :"hi" }],"max_tokens" :8 ,"temperature" :0 ,"top_k" :0 , 161"seed" :7 } 162code ,out = self .post ("/v1/chat/completions" ,chat ) 163self .assertEqual (code ,200 ,out ) 164code ,out = self .post ("/v1/messages" , {** chat ,"temperature" :- 1 ,"top_k" :100 ,"presence_penalty" :0.5 , 165"penalty_last_n" :64 }) 166self .assertEqual (code ,200 ,out ) 167code ,out = self .post ("/v1/responses" , {"model" :"m" ,"input" :"hi" ,"store" :False ,"max_output_tokens" :8 , 168"temperature" :None ,"top_p" :None ,"seed" :None }) 169self .assertEqual (code ,200 ,out ) 170code ,out = self .post ("/v1/messages/count_tokens" , {"messages" : [{"role" :"user" ,"content" :"hi" }], 171"temperature" :0.7 }) 172self .assertEqual (code ,200 ,out ) 173 174 175if __name__ == "__main__" : 176unittest .main ()