diff --git a/util/httputil/compression.go b/util/httputil/compression.go index 9a8a666453..d5bedb7fa9 100644 --- a/util/httputil/compression.go +++ b/util/httputil/compression.go @@ -56,8 +56,13 @@ func (c *compressedResponseWriter) Close() { // Constructs a new compressedResponseWriter based on client request headers. func newCompressedResponseWriter(writer http.ResponseWriter, req *http.Request) *compressedResponseWriter { - encodings := strings.Split(req.Header.Get(acceptEncodingHeader), ",") - for _, encoding := range encodings { + raw := req.Header.Get(acceptEncodingHeader) + var ( + encoding string + commaFound bool + ) + for { + encoding, raw, commaFound = strings.Cut(raw, ",") switch strings.TrimSpace(encoding) { case gzipEncoding: writer.Header().Set(contentEncodingHeader, gzipEncoding) @@ -72,6 +77,9 @@ func newCompressedResponseWriter(writer http.ResponseWriter, req *http.Request) writer: zlib.NewWriter(writer), } } + if !commaFound { + break + } } return &compressedResponseWriter{ ResponseWriter: writer, diff --git a/util/httputil/compression_test.go b/util/httputil/compression_test.go index e166c7de79..fd3f1f66d4 100644 --- a/util/httputil/compression_test.go +++ b/util/httputil/compression_test.go @@ -18,6 +18,7 @@ import ( "io" "net/http" "net/http/httptest" + "strings" "testing" "github.com/klauspost/compress/gzip" @@ -72,6 +73,17 @@ func TestCompressionHandler_PlainText(t *testing.T) { require.Equal(t, expected, actual, "expected response with content") } +func BenchmarkNewCompressionHandler_MaliciousAcceptEncoding(b *testing.B) { + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/whatever", nil) + req.Header.Set("Accept-Encoding", strings.Repeat(",", http.DefaultMaxHeaderBytes)) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + newCompressedResponseWriter(rec, req) + } +} + func TestCompressionHandler_Gzip(t *testing.T) { tearDown := setup() defer tearDown()