Skip to content

Commit ff2edc3

Browse files
don't send stringified binary response body
1 parent 3944136 commit ff2edc3

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

checks/http.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@ import (
88
"net/http"
99
"net/url"
1010
"regexp"
11+
"slices"
1112
"strings"
13+
"unicode/utf8"
1214

1315
api "github.com/bootdotdev/bootdev/client"
1416
"github.com/goccy/go-json"
@@ -163,6 +165,9 @@ func prettyPrintHTTPTest(test api.HTTPRequestTest, variables map[string]string)
163165
// in some lessons we yeet the entire body up to the server, but we really shouldn't ever care
164166
// about more than 100,000 stringified characters of it, so this protects against giant bodies
165167
func truncateAndStringifyBody(body []byte) string {
168+
if likelyBinary(body) {
169+
return fmt.Sprintf("<likely binary data: %d bytes>", len(body))
170+
}
166171
bodyString := string(body)
167172
const maxBodyLength = 1000000
168173
if len(bodyString) > maxBodyLength {
@@ -193,3 +198,24 @@ func InterpolateVariables(template string, vars map[string]string) string {
193198
return m
194199
})
195200
}
201+
202+
func likelyBinary(b []byte) bool {
203+
if len(b) == 0 {
204+
return false
205+
}
206+
207+
if len(b) > 8000 {
208+
b = b[:8000]
209+
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]
217+
}
218+
}
219+
220+
return slices.Contains(b, 0) || !utf8.Valid(b)
221+
}

0 commit comments

Comments
 (0)