@@ -1182,3 +1182,48 @@ func TestLimitedBuffer_Pool(t *testing.T) {
11821182 require .Equal (t , len (data ), buf .Len ())
11831183 require .Equal (t , data , buf .Bytes ())
11841184}
1185+
1186+ func TestResponseChain_StringSafety (t * testing.T ) {
1187+ bodyContent := "Original Body Content That Should Be Preserved Yeah Okay LOL"
1188+ headerKey := "X-Safety-Test"
1189+ headerValue := "Original Header Value"
1190+
1191+ resp := & http.Response {
1192+ StatusCode : 200 ,
1193+ Body : io .NopCloser (strings .NewReader (bodyContent )),
1194+ Header : http.Header {headerKey : []string {headerValue }},
1195+ Proto : "HTTP/1.1" ,
1196+ ProtoMajor : 1 ,
1197+ ProtoMinor : 1 ,
1198+ }
1199+
1200+ rc := NewResponseChain (resp , - 1 )
1201+ err := rc .Fill ()
1202+ require .NoError (t , err )
1203+
1204+ bodyStr := rc .BodyString ()
1205+ headersStr := rc .HeadersString ()
1206+
1207+ assert .Equal (t , bodyContent , bodyStr )
1208+ assert .Contains (t , headersStr , headerValue )
1209+
1210+ rc .Close ()
1211+
1212+ // Now attempt to pollute the pool and overwrite the memory.
1213+ // We get a bunch of buffers and write garbage to them.
1214+ var buffers []* bytes.Buffer
1215+ for i := 0 ; i < 100 ; i ++ {
1216+ buf := getBuffer ()
1217+ buffers = append (buffers , buf )
1218+
1219+ buf .Reset ()
1220+ buf .WriteString ("ALERTA_GARBAGE_DATA_OVERWRITING_MEMORY_ALERTA_GARBAGE_DATA_OVERWRITING_MEMORY" )
1221+ }
1222+
1223+ for _ , buf := range buffers {
1224+ putBuffer (buf )
1225+ }
1226+
1227+ assert .Equal (t , bodyContent , bodyStr , "BodyString() content changed after buffer reuse - unsafe memory sharing detected" )
1228+ assert .Contains (t , headersStr , headerValue , "HeadersString() content changed after buffer reuse - unsafe memory sharing detected" )
1229+ }
0 commit comments