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