Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions config/confighttp/compression.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"bytes"
"compress/gzip"
"compress/zlib"
"encoding/binary"
"errors"
"fmt"
"io"
Expand Down Expand Up @@ -152,19 +153,25 @@ func newSnappyHandler(maxRequestBodySize int64) func(io.ReadCloser) (io.ReadClos
}, nil
}

compressed, err := io.ReadAll(br)
if err != nil {
return nil, err
}
if maxRequestBodySize > 0 {
decodedLen, decErr := snappy.DecodedLen(compressed)
// Peek MaxVarintLen64 bytes so we can read the decoded length
// before reading the full compressed request body.
lenBytes, peakErr := br.Peek(binary.MaxVarintLen64)
if peakErr != nil && !errors.Is(peakErr, io.EOF) {
return nil, peakErr
}
decodedLen, decErr := snappy.DecodedLen(lenBytes)
if decErr != nil {
return nil, decErr
}
if int64(decodedLen) > maxRequestBodySize {
return nil, errors.New("snappy: decoded size exceeds max request body size")
}
}
compressed, err := io.ReadAll(br)
if err != nil {
return nil, err
}
decoded, err := snappy.Decode(nil, compressed)
if err != nil {
return nil, err
Expand Down
36 changes: 36 additions & 0 deletions config/confighttp/compression_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"compress/gzip"
"compress/zlib"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
Expand Down Expand Up @@ -961,6 +962,41 @@ func TestSnappyBlockRejectsOversizedDecodedLen(t *testing.T) {
assert.False(t, downstreamCalled, "downstream handler must not run when request is rejected")
}

func TestSnappyBlockRejectsOversizedDecodedLenBeforeCompressedBodyLimit(t *testing.T) {
t.Parallel()

const maxBody = 1024

payload := make([]byte, binary.MaxVarintLen64+maxBody+1)
n := binary.PutUvarint(payload, maxBody+1)
payload = payload[:n+maxBody+1]
require.Greater(t, len(payload), maxBody)

downstreamCalled := false
h := maxRequestBodySizeInterceptor(
httpContentDecompressor(
http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
downstreamCalled = true
}),
maxBody,
defaultErrorHandler,
defaultCompressionAlgorithms(),
nil,
),
maxBody,
)

req := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(payload))
req.Header.Set("Content-Encoding", "snappy")

resp := httptest.NewRecorder()
h.ServeHTTP(resp, req)

assert.Equal(t, http.StatusBadRequest, resp.Code)
assert.Contains(t, resp.Body.String(), "decoded size exceeds max request body size")
assert.False(t, downstreamCalled, "downstream handler must not run when request is rejected")
}

func TestPooledZstdReadCloserReadAfterClose(t *testing.T) {
h := httpContentDecompressor(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand Down
Loading