From 1236aa4901143e0af068aaaa31505b99c7257ff5 Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Tue, 3 Nov 2026 00:25:38 +0000 Subject: [PATCH] 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. --- resp.go | 38 ++++++++++++++++++++++++++++++++++++-- resp_test.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 2 deletions(-) diff --git a/resp.go b/resp.go index a5fb236..c1d168f 100644 --- a/resp.go +++ b/resp.go @@ -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 "$" 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 diff --git a/resp_test.go b/resp_test.go index 2570763..12d19c1 100644 --- a/resp_test.go +++ b/resp_test.go @@ -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) + } + } + }) + } +}