Skip to content

Commit 32c1a90

Browse files
authored
fix(screenshot): bound base64 decoding memory (#242)
* fix(screenshot): bound base64 decoding memory * test(screenshot): gofmt regression tests
1 parent ce7841b commit 32c1a90

2 files changed

Lines changed: 33 additions & 1 deletion

File tree

‎internal/service/screenshot_download.go‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"encoding/base64"
55
"errors"
66
"fmt"
7+
"io"
78
"strings"
89
)
910

@@ -17,7 +18,10 @@ const screenshotDownloadMaxBytes = 8 << 20
1718
// a real http(s) response, so the client posts the preview it is already
1819
// showing and the browser saves exactly that image.
1920
func DecodeScreenshotDownload(encoded string) ([]byte, error) {
20-
data, err := base64.StdEncoding.DecodeString(strings.TrimSpace(encoded))
21+
// Decode at most one byte over the limit. DecodeString would allocate
22+
// based on the entire input before checking the maximum size.
23+
decoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(strings.TrimSpace(encoded)))
24+
data, err := io.ReadAll(io.LimitReader(decoder, screenshotDownloadMaxBytes+1))
2125
if err != nil {
2226
return nil, errors.New("screenshot data is not valid base64")
2327
}

‎internal/service/screenshot_download_test.go‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,34 @@ func TestDecodeScreenshotDownloadRejectsInvalidPayloads(t *testing.T) {
5050
}
5151
}
5252

53+
func TestDecodeScreenshotDownloadRejectsOversizedBeforeDecoding(t *testing.T) {
54+
// An oversized malformed upload should hit the size cap, not be decoded
55+
// in full before reporting an invalid base64 payload.
56+
encoded := strings.Repeat("A", base64.StdEncoding.EncodedLen(screenshotDownloadMaxBytes)+4) + "!"
57+
_, err := DecodeScreenshotDownload(encoded)
58+
if err == nil || !strings.Contains(err.Error(), "too large") {
59+
t.Fatalf("error = %v, want size limit error", err)
60+
}
61+
}
62+
63+
func TestDecodeScreenshotDownloadAcceptsMaximumSize(t *testing.T) {
64+
encoded := base64.StdEncoding.EncodeToString(jpegFixture(screenshotDownloadMaxBytes))
65+
got, err := DecodeScreenshotDownload(encoded)
66+
if err != nil || len(got) != screenshotDownloadMaxBytes {
67+
t.Fatalf("decoded size = %d, error = %v", len(got), err)
68+
}
69+
}
70+
71+
func TestDecodeScreenshotDownloadAcceptsLineWrappedBase64(t *testing.T) {
72+
data := jpegFixture(128)
73+
encoded := base64.StdEncoding.EncodeToString(data)
74+
encoded = encoded[:64] + "\r\n" + encoded[64:]
75+
got, err := DecodeScreenshotDownload(encoded)
76+
if err != nil || !bytes.Equal(got, data) {
77+
t.Fatalf("wrapped base64 round trip error = %v", err)
78+
}
79+
}
80+
5381
func TestIsJPEG(t *testing.T) {
5482
if !isJPEG(jpegFixture(8)) {
5583
t.Fatal("expected the JPEG fixture to be recognized")

0 commit comments

Comments
 (0)
⌂ 换网址