fix(resp): size a bulk reply buffer by bytes received

The parser allocated the full declared bulk length before any payload arrived, so a stalled peer could pin 64 MiB per connection. The buffer now starts at 64 KiB and doubles only after the previous capacity has fully arrived. A test measures the allocation.
This commit is contained in:
2026-11-03 00:25:38 +00:00
parent 1a2cea3417
commit 1236aa4901
2 changed files with 81 additions and 2 deletions
+36 -2
View File
@@ -716,8 +716,8 @@ func decodeBulk(r *bufio.Reader, lenField string) (any, error) {
return nil, fmt.Errorf("resp: bulk length %d out of range (max %d)", n, respMaxBulkLen)
}
buf := make([]byte, n+2) // payload plus trailing CRLF; n is bounded above, so n+2 cannot overflow
if _, err := io.ReadFull(r, buf); err != nil {
buf, err := readBulkBody(r, n+2) // payload plus trailing CRLF; n is bounded above, so n+2 cannot overflow
if err != nil {
return nil, fmt.Errorf("resp: read bulk body: %w", err)
}
if buf[n] != '\r' || buf[n+1] != '\n' {
@@ -726,6 +726,40 @@ func decodeBulk(r *bufio.Reader, lenField string) (any, error) {
return buf[:n], nil
}
// respBulkEagerBytes is the largest bulk body allocated up front. Larger
// declared bodies grow with the bytes that arrive, so a stalled or hostile
// peer cannot pin respMaxBulkLen of memory with a bare "$<len>" line.
const respBulkEagerBytes = 64 << 10
// readBulkBody reads exactly total bytes from r. The buffer doubles only
// after the previous capacity has fully arrived, so memory held is at most
// about twice the bytes received plus respBulkEagerBytes.
func readBulkBody(r io.Reader, total int) ([]byte, error) {
capNow := respBulkEagerBytes
if total < capNow {
capNow = total
}
buf := make([]byte, capNow)
got := 0
for {
n, err := io.ReadFull(r, buf[got:])
got += n
if err != nil {
return nil, err
}
if got == total {
return buf, nil
}
capNow *= 2
if capNow > total {
capNow = total
}
grown := make([]byte, capNow)
copy(grown, buf)
buf = grown
}
}
// decodeArray reads n elements given the already-parsed "*" length field
// lenField, returning nil for a null array ("*-1"). It rejects a negative
// length other than -1 and a length exceeding respMaxArrayLen before
+45
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"io"
"net"
"runtime"
"strconv"
"strings"
"sync"
@@ -1438,3 +1439,47 @@ func TestRESPClient_Close_EmptyPool_ReturnsNilImmediately(t *testing.T) {
t.Errorf("len(free) after Close = %d, want 0", got)
}
}
// TestDecodeBulk_AllocationFollowsBytesReceived pins that a declared bulk
// length does not allocate its full size before the payload arrives, and
// that a complete large reply still decodes intact. It is deliberately not
// parallel: it reads the process-wide allocation counter.
func TestDecodeBulk_AllocationFollowsBytesReceived(t *testing.T) {
const slackBytes = 1 << 20
tests := []struct {
name string
declared int
payload int
wantErr bool
}{
{name: "stalled huge declaration", declared: respMaxBulkLen, payload: 0, wantErr: true},
{name: "truncated mid payload", declared: respMaxBulkLen, payload: 1 << 20, wantErr: true},
{name: "small complete reply", declared: 100, payload: 100, wantErr: false},
{name: "large complete reply", declared: 2 << 20, payload: 2 << 20, wantErr: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
wire := strings.Repeat("x", tt.payload)
if !tt.wantErr {
wire += "\r\n"
}
r := bufio.NewReader(strings.NewReader(wire))
var before, after runtime.MemStats
runtime.ReadMemStats(&before)
got, err := decodeBulk(r, strconv.Itoa(tt.declared))
runtime.ReadMemStats(&after)
if (err != nil) != tt.wantErr {
t.Fatalf("decodeBulk err = %v, wantErr %v", err, tt.wantErr)
}
maxAlloc := uint64(4*tt.payload + slackBytes) //nolint:gosec // small non-negative test constants
if delta := after.TotalAlloc - before.TotalAlloc; delta > maxAlloc {
t.Errorf("decodeBulk allocated %d bytes for %d received, want <= %d", delta, tt.payload, maxAlloc)
}
if !tt.wantErr {
if b, _ := got.([]byte); len(b) != tt.declared {
t.Errorf("decoded %d bytes, want %d", len(b), tt.declared)
}
}
})
}
}