Skip to content

Commit 814c5e7

Browse files
truncate but still send binary
1 parent 5309fec commit 814c5e7

File tree

1 file changed

+25
-18
lines changed

1 file changed

+25
-18
lines changed

checks/http.go

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -162,18 +162,24 @@ func prettyPrintHTTPTest(test api.HTTPRequestTest, variables map[string]string)
162162
return ""
163163
}
164164

165-
// in some lessons we yeet the entire body up to the server, but we really shouldn't ever care
166-
// about more than 1 MiB of UTF-8 data, so this protects against giant bodies
165+
// Return a capped string representation of the response body.
166+
//
167+
// Text-like responses are allowed up to ~1 MiB, while likely-binary responses are
168+
// capped more aggressively (~16 KiB) to avoid large payloads when serialized to JSON.
169+
//
170+
// We intentionally stringify raw bytes, even for binary data, so that ASCII markers
171+
// embedded in binary (e.g. "moov" in MP4 files) remain searchable by downstream checks.
172+
// The result is not guaranteed to be valid UTF-8 or lossless.
167173
func truncateAndStringifyBody(body []byte) string {
174+
maxBodyLength := 1024 * 1024 // 1 MiB
168175
if likelyBinary(body) {
169-
return fmt.Sprintf("<likely binary data: %d bytes>", len(body))
176+
maxBodyLength = 16 * 1024 // 16 KiB
170177
}
171-
bodyString := string(body)
172-
const maxBodyLength = 1024 * 1024
173-
if len(bodyString) > maxBodyLength {
174-
bodyString = bodyString[:maxBodyLength]
178+
if len(body) > maxBodyLength {
179+
body = body[:maxBodyLength]
180+
body = trimIncompleteUTF8(body)
175181
}
176-
return bodyString
182+
return string(body)
177183
}
178184

179185
func parseVariables(body []byte, vardefs []api.HTTPRequestResponseVariable, variables map[string]string) error {
@@ -203,19 +209,20 @@ func likelyBinary(b []byte) bool {
203209
if len(b) == 0 {
204210
return false
205211
}
206-
207212
if len(b) > 8000 {
208213
b = b[:8000]
214+
b = trimIncompleteUTF8(b) // in case we broke a multi-byte char
215+
}
216+
return slices.Contains(b, 0) || !utf8.Valid(b)
217+
}
209218

210-
// In case we sliced in the middle of a UTF-8 char
211-
for i := 0; i < 3 && len(b) > 0; i++ {
212-
r, size := utf8.DecodeLastRune(b)
213-
if r != utf8.RuneError || size != 1 {
214-
break
215-
}
216-
b = b[:len(b)-1]
219+
func trimIncompleteUTF8(b []byte) []byte {
220+
for i := 0; i < 3 && len(b) > 0; i++ {
221+
r, size := utf8.DecodeLastRune(b)
222+
if r != utf8.RuneError || size != 1 {
223+
break
217224
}
225+
b = b[:len(b)-1]
218226
}
219-
220-
return slices.Contains(b, 0) || !utf8.Valid(b)
227+
return b
221228
}

0 commit comments

Comments
 (0)