This is an automated email from the ASF dual-hosted git repository. LinkinStars pushed a commit to branch dev in repository https://gitbox.apache.org/repos/asf/answer.git
commit ea687941fd2343683aa22e9af58c8e8c2adf3971 Author: SiriusTL666 <[email protected]> AuthorDate: Fri Nov 6 13:20:30 2026 +0800 fix(branding): reject oversized favicon responses instead of truncating io.LimitReader silently truncates a body larger than the cap, so GetPicByUrl returned incomplete bytes as a successful image. Read up to fetchedPicMaxBytes+1 and return an empty result when the limit is exceeded. Add tests for the at-limit (accepted) and over-limit (rejected) cases. --- pkg/htmltext/htmltext.go | 7 ++++++- pkg/htmltext/htmltext_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/pkg/htmltext/htmltext.go b/pkg/htmltext/htmltext.go index 47daeef4..a6e9d64c 100644 --- a/pkg/htmltext/htmltext.go +++ b/pkg/htmltext/htmltext.go @@ -259,9 +259,14 @@ func GetPicByUrl(url string) string { if res.StatusCode != http.StatusOK { return "" } - pix, err := io.ReadAll(io.LimitReader(res.Body, fetchedPicMaxBytes)) + // Read one byte past the cap: LimitReader alone would silently truncate an + // oversized body and hand back a corrupt image as if the fetch succeeded. + pix, err := io.ReadAll(io.LimitReader(res.Body, fetchedPicMaxBytes+1)) if err != nil { return "" } + if len(pix) > fetchedPicMaxBytes { + return "" + } return string(pix) } diff --git a/pkg/htmltext/htmltext_test.go b/pkg/htmltext/htmltext_test.go index 781d5ff1..da32956e 100644 --- a/pkg/htmltext/htmltext_test.go +++ b/pkg/htmltext/htmltext_test.go @@ -20,6 +20,7 @@ package htmltext import ( + "bytes" "fmt" "net/http" "net/http/httptest" @@ -383,6 +384,32 @@ func TestGetPicByUrlTimesOut(t *testing.T) { } } +// A body at the cap is still a complete image and must be served. +func TestGetPicByUrlAcceptsBodyAtSizeLimit(t *testing.T) { + body := bytes.Repeat([]byte("a"), fetchedPicMaxBytes) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write(body) + })) + defer srv.Close() + + got := GetPicByUrl(srv.URL) + assert.Len(t, got, fetchedPicMaxBytes) +} + +// One byte past the cap means the response was truncated, so the bytes are not +// a usable image. Handing them back as a success would serve a corrupt favicon. +func TestGetPicByUrlRejectsBodyOverSizeLimit(t *testing.T) { + body := bytes.Repeat([]byte("a"), fetchedPicMaxBytes+1) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write(body) + })) + defer srv.Close() + + assert.Equal(t, "", GetPicByUrl(srv.URL)) +} + func TestPicClientHasTimeout(t *testing.T) { // Guards against regressing to a bare &http.Client{}, which has no timeout. assert.NotZero(t, picClient.Timeout)
