| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package confighttp |
| 5 |
|
| 6 |
import ( |
| 7 |
"bytes" |
| 8 |
"compress/gzip" |
| 9 |
"compress/zlib" |
| 10 |
"context" |
| 11 |
"errors" |
| 12 |
"fmt" |
| 13 |
"io" |
| 14 |
"net/http" |
| 15 |
"net/http/httptest" |
| 16 |
"strings" |
| 17 |
"testing" |
| 18 |
"testing/iotest" |
| 19 |
|
| 20 |
"github.com/golang/snappy" |
| 21 |
"github.com/klauspost/compress/zstd" |
| 22 |
"github.com/pierrec/lz4/v4" |
| 23 |
"github.com/stretchr/testify/assert" |
| 24 |
"github.com/stretchr/testify/require" |
| 25 |
|
| 26 |
"go.opentelemetry.io/collector/component/componenttest" |
| 27 |
"go.opentelemetry.io/collector/config/configcompression" |
| 28 |
"go.opentelemetry.io/collector/featuregate" |
| 29 |
) |
| 30 |
|
| 31 |
func TestHTTPClientCompression(t *testing.T) { |
| 32 |
testBody := []byte("uncompressed_text") |
| 33 |
compressedGzipBody := compressGzip(t, testBody) |
| 34 |
compressedZlibBody := compressZlib(t, testBody) |
| 35 |
compressedDeflateBody := compressZlib(t, testBody) |
| 36 |
compressedSnappyFramedBody := compressSnappyFramed(t, testBody) |
| 37 |
compressedSnappyBody := compressSnappy(t, testBody) |
| 38 |
compressedZstdBody := compressZstd(t, testBody) |
| 39 |
compressedLz4Body := compressLz4(t, testBody) |
| 40 |
|
| 41 |
const invalidGzipLevel configcompression.Level = 100 |
| 42 |
|
| 43 |
tests := []struct { |
| 44 |
name string |
| 45 |
encoding configcompression.Type |
| 46 |
level configcompression.Level |
| 47 |
framedSnappyEnabled bool |
| 48 |
reqBody []byte |
| 49 |
shouldError bool |
| 50 |
}{ |
| 51 |
{ |
| 52 |
name: "ValidEmpty", |
| 53 |
encoding: "", |
| 54 |
reqBody: testBody, |
| 55 |
shouldError: false, |
| 56 |
}, |
| 57 |
{ |
| 58 |
name: "ValidNone", |
| 59 |
encoding: "none", |
| 60 |
reqBody: testBody, |
| 61 |
shouldError: false, |
| 62 |
}, |
| 63 |
{ |
| 64 |
name: "ValidGzip", |
| 65 |
encoding: configcompression.TypeGzip, |
| 66 |
level: gzip.DefaultCompression, |
| 67 |
reqBody: compressedGzipBody.Bytes(), |
| 68 |
shouldError: false, |
| 69 |
}, |
| 70 |
{ |
| 71 |
name: "ValidGzip-DefaultLevel", |
| 72 |
encoding: configcompression.TypeGzip, |
| 73 |
reqBody: compressedGzipBody.Bytes(), |
| 74 |
shouldError: false, |
| 75 |
}, |
| 76 |
{ |
| 77 |
name: "InvalidGzip", |
| 78 |
encoding: configcompression.TypeGzip, |
| 79 |
level: invalidGzipLevel, |
| 80 |
reqBody: compressedGzipBody.Bytes(), |
| 81 |
shouldError: true, |
| 82 |
}, |
| 83 |
{ |
| 84 |
name: "InvalidCompression", |
| 85 |
encoding: configcompression.Type("invalid"), |
| 86 |
level: invalidGzipLevel, |
| 87 |
reqBody: compressedGzipBody.Bytes(), |
| 88 |
shouldError: true, |
| 89 |
}, |
| 90 |
{ |
| 91 |
name: "ValidZlib", |
| 92 |
encoding: configcompression.TypeZlib, |
| 93 |
level: gzip.DefaultCompression, |
| 94 |
reqBody: compressedZlibBody.Bytes(), |
| 95 |
shouldError: false, |
| 96 |
}, |
| 97 |
{ |
| 98 |
name: "ValidDeflate", |
| 99 |
encoding: configcompression.TypeDeflate, |
| 100 |
level: gzip.DefaultCompression, |
| 101 |
reqBody: compressedDeflateBody.Bytes(), |
| 102 |
shouldError: false, |
| 103 |
}, |
| 104 |
{ |
| 105 |
name: "ValidSnappy", |
| 106 |
encoding: configcompression.TypeSnappy, |
| 107 |
framedSnappyEnabled: true, |
| 108 |
reqBody: compressedSnappyBody.Bytes(), |
| 109 |
shouldError: false, |
| 110 |
}, |
| 111 |
{ |
| 112 |
name: "InvalidSnappy", |
| 113 |
encoding: configcompression.TypeSnappy, |
| 114 |
level: gzip.DefaultCompression, |
| 115 |
reqBody: compressedSnappyBody.Bytes(), |
| 116 |
shouldError: true, |
| 117 |
}, |
| 118 |
{ |
| 119 |
name: "ValidSnappyFramed", |
| 120 |
encoding: configcompression.TypeSnappyFramed, |
| 121 |
framedSnappyEnabled: true, |
| 122 |
reqBody: compressedSnappyFramedBody.Bytes(), |
| 123 |
shouldError: false, |
| 124 |
}, |
| 125 |
{ |
| 126 |
name: "InvalidSnappyFramed", |
| 127 |
encoding: configcompression.TypeSnappyFramed, |
| 128 |
level: gzip.DefaultCompression, |
| 129 |
reqBody: compressedSnappyFramedBody.Bytes(), |
| 130 |
shouldError: true, |
| 131 |
}, |
| 132 |
{ |
| 133 |
name: "ValidZstd", |
| 134 |
encoding: configcompression.TypeZstd, |
| 135 |
level: 99, |
| 136 |
reqBody: compressedZstdBody.Bytes(), |
| 137 |
shouldError: false, |
| 138 |
}, |
| 139 |
{ |
| 140 |
name: "ValidLz4", |
| 141 |
encoding: configcompression.TypeLz4, |
| 142 |
reqBody: compressedLz4Body.Bytes(), |
| 143 |
shouldError: false, |
| 144 |
}, |
| 145 |
{ |
| 146 |
name: "InvalidLz4", |
| 147 |
encoding: configcompression.TypeLz4, |
| 148 |
level: gzip.DefaultCompression, |
| 149 |
reqBody: compressedLz4Body.Bytes(), |
| 150 |
shouldError: true, |
| 151 |
}, |
| 152 |
} |
| 153 |
for _, tt := range tests { |
| 154 |
t.Run(tt.name, func(t *testing.T) { |
| 155 |
require.NoError(t, featuregate.GlobalRegistry().Set(enableFramedSnappy.ID(), tt.framedSnappyEnabled)) |
| 156 |
|
| 157 |
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 158 |
body, err := io.ReadAll(r.Body) |
| 159 |
assert.NoError(t, err, "failed to read request body: %v", err) |
| 160 |
assert.Equal(t, tt.reqBody, body) |
| 161 |
w.WriteHeader(http.StatusOK) |
| 162 |
})) |
| 163 |
t.Cleanup(srv.Close) |
| 164 |
|
| 165 |
reqBody := bytes.NewBuffer(testBody) |
| 166 |
|
| 167 |
req, err := http.NewRequest(http.MethodGet, srv.URL, reqBody) |
| 168 |
require.NoError(t, err, "failed to create request to test handler") |
| 169 |
clientSettings := ClientConfig{ |
| 170 |
Endpoint: srv.URL, |
| 171 |
Compression: tt.encoding, |
| 172 |
CompressionParams: newCompressionParams(tt.level), |
| 173 |
} |
| 174 |
err = clientSettings.Validate() |
| 175 |
if tt.shouldError { |
| 176 |
require.Error(t, err) |
| 177 |
message := fmt.Sprintf("unsupported parameters {Level:%+v} for compression type %q", tt.level, tt.encoding) |
| 178 |
assert.Equal(t, message, err.Error()) |
| 179 |
return |
| 180 |
} |
| 181 |
require.NoError(t, err) |
| 182 |
client, err := clientSettings.ToClient(context.Background(), nil, componenttest.NewNopTelemetrySettings()) |
| 183 |
require.NoError(t, err) |
| 184 |
res, err := client.Do(req) |
| 185 |
if tt.shouldError { |
| 186 |
assert.Error(t, err) |
| 187 |
return |
| 188 |
} |
| 189 |
require.NoError(t, err) |
| 190 |
|
| 191 |
_, err = io.ReadAll(res.Body) |
| 192 |
require.NoError(t, err) |
| 193 |
require.NoError(t, res.Body.Close(), "failed to close request body: %v", err) |
| 194 |
}) |
| 195 |
} |
| 196 |
} |
| 197 |
|
| 198 |
func TestHTTPCustomDecompression(t *testing.T) { |
| 199 |
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 200 |
body, err := io.ReadAll(r.Body) |
| 201 |
if err != nil { |
| 202 |
w.WriteHeader(http.StatusBadRequest) |
| 203 |
_, _ = w.Write([]byte(err.Error())) |
| 204 |
return |
| 205 |
} |
| 206 |
|
| 207 |
assert.NoError(t, err, "failed to read request body: %v", err) |
| 208 |
assert.Equal(t, "decompressed body", string(body)) |
| 209 |
w.WriteHeader(http.StatusOK) |
| 210 |
}) |
| 211 |
decoders := map[string]func(io.ReadCloser) (io.ReadCloser, error){ |
| 212 |
"custom-encoding": func(io.ReadCloser) (io.ReadCloser, error) { //nolint:unparam |
| 213 |
return io.NopCloser(strings.NewReader("decompressed body")), nil |
| 214 |
}, |
| 215 |
} |
| 216 |
srv := httptest.NewServer(httpContentDecompressor(handler, defaultMaxRequestBodySize, defaultErrorHandler, defaultCompressionAlgorithms(), decoders)) |
| 217 |
|
| 218 |
t.Cleanup(srv.Close) |
| 219 |
|
| 220 |
req, err := http.NewRequest(http.MethodGet, srv.URL, bytes.NewBuffer([]byte("123decompressed body"))) |
| 221 |
require.NoError(t, err, "failed to create request to test handler") |
| 222 |
req.Header.Set("Content-Encoding", "custom-encoding") |
| 223 |
|
| 224 |
client := srv.Client() |
| 225 |
res, err := client.Do(req) |
| 226 |
require.NoError(t, err) |
| 227 |
|
| 228 |
assert.Equal(t, http.StatusOK, res.StatusCode, "test handler returned unexpected status code ") |
| 229 |
_, err = io.ReadAll(res.Body) |
| 230 |
require.NoError(t, res.Body.Close(), "failed to close request body: %v", err) |
| 231 |
} |
| 232 |
|
| 233 |
func TestHTTPContentDecompressionHandler(t *testing.T) { |
| 234 |
testBody := []byte("uncompressed_text") |
| 235 |
noDecoders := map[string]func(io.ReadCloser) (io.ReadCloser, error){} |
| 236 |
tests := []struct { |
| 237 |
name string |
| 238 |
encoding string |
| 239 |
reqBody *bytes.Buffer |
| 240 |
respCode int |
| 241 |
respBody string |
| 242 |
framedSnappyEnabled bool |
| 243 |
}{ |
| 244 |
{ |
| 245 |
name: "NoCompression", |
| 246 |
encoding: "", |
| 247 |
reqBody: bytes.NewBuffer(testBody), |
| 248 |
respCode: http.StatusOK, |
| 249 |
}, |
| 250 |
{ |
| 251 |
name: "ValidDeflate", |
| 252 |
encoding: "deflate", |
| 253 |
reqBody: compressZlib(t, testBody), |
| 254 |
respCode: http.StatusOK, |
| 255 |
}, |
| 256 |
{ |
| 257 |
name: "ValidGzip", |
| 258 |
encoding: "gzip", |
| 259 |
reqBody: compressGzip(t, testBody), |
| 260 |
respCode: http.StatusOK, |
| 261 |
}, |
| 262 |
{ |
| 263 |
name: "ValidZlib", |
| 264 |
encoding: "zlib", |
| 265 |
reqBody: compressZlib(t, testBody), |
| 266 |
respCode: http.StatusOK, |
| 267 |
}, |
| 268 |
{ |
| 269 |
name: "ValidZstd", |
| 270 |
encoding: "zstd", |
| 271 |
reqBody: compressZstd(t, testBody), |
| 272 |
respCode: http.StatusOK, |
| 273 |
}, |
| 274 |
{ |
| 275 |
name: "ValidSnappyFramed", |
| 276 |
encoding: "x-snappy-framed", |
| 277 |
framedSnappyEnabled: true, |
| 278 |
reqBody: compressSnappyFramed(t, testBody), |
| 279 |
respCode: http.StatusOK, |
| 280 |
}, |
| 281 |
{ |
| 282 |
name: "ValidSnappy", |
| 283 |
encoding: "snappy", |
| 284 |
reqBody: compressSnappy(t, testBody), |
| 285 |
respCode: http.StatusOK, |
| 286 |
}, |
| 287 |
{ |
| 288 |
// Should work even without the framed snappy feature gate enabled, |
| 289 |
// since during decompression we're peeking the compression header |
| 290 |
// and identifying which snappy encoding was used. |
| 291 |
name: "ValidSnappyFramedAsSnappy", |
| 292 |
encoding: "snappy", |
| 293 |
reqBody: compressSnappyFramed(t, testBody), |
| 294 |
respCode: http.StatusOK, |
| 295 |
}, |
| 296 |
{ |
| 297 |
name: "ValidLz4", |
| 298 |
encoding: "lz4", |
| 299 |
reqBody: compressLz4(t, testBody), |
| 300 |
respCode: http.StatusOK, |
| 301 |
}, |
| 302 |
{ |
| 303 |
name: "InvalidDeflate", |
| 304 |
encoding: "deflate", |
| 305 |
reqBody: bytes.NewBuffer(testBody), |
| 306 |
respCode: http.StatusBadRequest, |
| 307 |
respBody: "zlib: invalid header\n", |
| 308 |
}, |
| 309 |
{ |
| 310 |
name: "InvalidGzip", |
| 311 |
encoding: "gzip", |
| 312 |
reqBody: bytes.NewBuffer(testBody), |
| 313 |
respCode: http.StatusBadRequest, |
| 314 |
respBody: "gzip: invalid header\n", |
| 315 |
}, |
| 316 |
{ |
| 317 |
name: "InvalidZlib", |
| 318 |
encoding: "zlib", |
| 319 |
reqBody: bytes.NewBuffer(testBody), |
| 320 |
respCode: http.StatusBadRequest, |
| 321 |
respBody: "zlib: invalid header\n", |
| 322 |
}, |
| 323 |
{ |
| 324 |
name: "InvalidZstd", |
| 325 |
encoding: "zstd", |
| 326 |
reqBody: bytes.NewBuffer(testBody), |
| 327 |
respCode: http.StatusBadRequest, |
| 328 |
respBody: "invalid input: magic number mismatch", |
| 329 |
}, |
| 330 |
{ |
| 331 |
name: "InvalidSnappyFramed", |
| 332 |
encoding: "x-snappy-framed", |
| 333 |
framedSnappyEnabled: true, |
| 334 |
reqBody: bytes.NewBuffer(testBody), |
| 335 |
respCode: http.StatusBadRequest, |
| 336 |
respBody: "snappy: corrupt input", |
| 337 |
}, |
| 338 |
{ |
| 339 |
name: "InvalidSnappy", |
| 340 |
encoding: "snappy", |
| 341 |
reqBody: bytes.NewBuffer(testBody), |
| 342 |
respCode: http.StatusBadRequest, |
| 343 |
respBody: "snappy: corrupt input\n", |
| 344 |
}, |
| 345 |
{ |
| 346 |
name: "UnsupportedCompression", |
| 347 |
encoding: "nosuchcompression", |
| 348 |
reqBody: bytes.NewBuffer(testBody), |
| 349 |
respCode: http.StatusBadRequest, |
| 350 |
respBody: "unsupported Content-Encoding: nosuchcompression\n", |
| 351 |
}, |
| 352 |
} |
| 353 |
for _, tt := range tests { |
| 354 |
t.Run(tt.name, func(t *testing.T) { |
| 355 |
require.NoError(t, featuregate.GlobalRegistry().Set(enableFramedSnappy.ID(), tt.framedSnappyEnabled)) |
| 356 |
|
| 357 |
srv := httptest.NewServer(httpContentDecompressor(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 358 |
body, err := io.ReadAll(r.Body) |
| 359 |
if err != nil { |
| 360 |
w.WriteHeader(http.StatusBadRequest) |
| 361 |
_, _ = w.Write([]byte(err.Error())) |
| 362 |
return |
| 363 |
} |
| 364 |
|
| 365 |
assert.NoError(t, err, "failed to read request body: %v", err) |
| 366 |
assert.EqualValues(t, testBody, string(body)) |
| 367 |
w.WriteHeader(http.StatusOK) |
| 368 |
}), defaultMaxRequestBodySize, defaultErrorHandler, defaultCompressionAlgorithms(), noDecoders)) |
| 369 |
t.Cleanup(srv.Close) |
| 370 |
|
| 371 |
req, err := http.NewRequest(http.MethodGet, srv.URL, tt.reqBody) |
| 372 |
require.NoError(t, err, "failed to create request to test handler") |
| 373 |
req.Header.Set("Content-Encoding", tt.encoding) |
| 374 |
|
| 375 |
client := srv.Client() |
| 376 |
res, err := client.Do(req) |
| 377 |
require.NoError(t, err) |
| 378 |
|
| 379 |
assert.Equal(t, tt.respCode, res.StatusCode, "test handler returned unexpected status code ") |
| 380 |
if tt.respBody != "" { |
| 381 |
body, err := io.ReadAll(res.Body) |
| 382 |
require.NoError(t, res.Body.Close(), "failed to close request body: %v", err) |
| 383 |
assert.Equal(t, tt.respBody, string(body)) |
| 384 |
} |
| 385 |
}) |
| 386 |
} |
| 387 |
} |
| 388 |
|
| 389 |
// TestEmptyCompressionAlgorithmsAllowsUncompressed verifies that when CompressionAlgorithms |
| 390 |
// is set to an empty array, requests without Content-Encoding header are accepted. |
| 391 |
func TestEmptyCompressionAlgorithmsAllowsUncompressed(t *testing.T) { |
| 392 |
testBody := []byte(`{"message": "test data"}`) |
| 393 |
|
| 394 |
tests := []struct { |
| 395 |
name string |
| 396 |
compressionAlgorithms []string |
| 397 |
contentEncoding string // empty string means no header |
| 398 |
expectedStatus int |
| 399 |
expectedError string |
| 400 |
compressionBypassed bool // If true, don't compress the body (simulates bypass behavior) |
| 401 |
}{ |
| 402 |
// Case 1: Empty array should bypass decompression |
| 403 |
{ |
| 404 |
name: "EmptyArray_NoContentEncoding_Accepted", |
| 405 |
compressionAlgorithms: []string{}, |
| 406 |
contentEncoding: "", |
| 407 |
expectedStatus: http.StatusOK, |
| 408 |
}, |
| 409 |
{ |
| 410 |
name: "EmptyArray_Gzip_PassedThrough", |
| 411 |
compressionAlgorithms: []string{}, |
| 412 |
contentEncoding: "gzip", |
| 413 |
expectedStatus: http.StatusOK, |
| 414 |
compressionBypassed: true, // Empty array bypasses decompression |
| 415 |
}, |
| 416 |
|
| 417 |
{ |
| 418 |
name: "EmptyArray_RandomEncoding_Accepted", |
| 419 |
compressionAlgorithms: []string{}, |
| 420 |
contentEncoding: "randomstuff", |
| 421 |
expectedStatus: http.StatusOK, |
| 422 |
}, |
| 423 |
// Case 2: Explicit list with only compressed formats should reject uncompressed |
| 424 |
{ |
| 425 |
name: "OnlyZstd_NoContentEncoding_Rejected", |
| 426 |
compressionAlgorithms: []string{"zstd"}, |
| 427 |
contentEncoding: "", |
| 428 |
expectedStatus: http.StatusBadRequest, |
| 429 |
expectedError: "unsupported Content-Encoding", |
| 430 |
}, |
| 431 |
{ |
| 432 |
name: "OnlyZstd_Zstd_Accepted", |
| 433 |
compressionAlgorithms: []string{"zstd"}, |
| 434 |
contentEncoding: "zstd", |
| 435 |
expectedStatus: http.StatusOK, |
| 436 |
}, |
| 437 |
{ |
| 438 |
name: "OnlyZstd_GzipContentEncoding_Rejected", |
| 439 |
compressionAlgorithms: []string{"zstd"}, |
| 440 |
contentEncoding: "gzip", |
| 441 |
expectedStatus: http.StatusBadRequest, |
| 442 |
expectedError: "unsupported Content-Encoding", |
| 443 |
}, |
| 444 |
// Case 3: Explicit list including empty string should accept uncompressed |
| 445 |
{ |
| 446 |
name: "WithEmptyString_NoContentEncoding_Accepted", |
| 447 |
compressionAlgorithms: []string{"", "gzip", "zstd"}, |
| 448 |
contentEncoding: "", |
| 449 |
expectedStatus: http.StatusOK, |
| 450 |
}, |
| 451 |
{ |
| 452 |
name: "WithEmptyString_Gzip_Accepted", |
| 453 |
compressionAlgorithms: []string{"", "gzip"}, |
| 454 |
contentEncoding: "gzip", |
| 455 |
expectedStatus: http.StatusOK, |
| 456 |
}, |
| 457 |
} |
| 458 |
|
| 459 |
for _, tt := range tests { |
| 460 |
t.Run(tt.name, func(t *testing.T) { |
| 461 |
// Create handler that echoes back the request body |
| 462 |
// If there's an error reading, it returns 500 which the test will catch |
| 463 |
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 464 |
body, err := io.ReadAll(r.Body) |
| 465 |
if err != nil { |
| 466 |
http.Error(w, "failed to read body", http.StatusInternalServerError) |
| 467 |
return |
| 468 |
} |
| 469 |
w.WriteHeader(http.StatusOK) |
| 470 |
_, _ = w.Write(body) |
| 471 |
}) |
| 472 |
|
| 473 |
// Create ServerConfig with the specified CompressionAlgorithms |
| 474 |
serverConfig := &ServerConfig{ |
| 475 |
Endpoint: "localhost:0", |
| 476 |
CompressionAlgorithms: tt.compressionAlgorithms, |
| 477 |
} |
| 478 |
|
| 479 |
srv, err := serverConfig.ToServer( |
| 480 |
context.Background(), |
| 481 |
nil, |
| 482 |
componenttest.NewNopTelemetrySettings(), |
| 483 |
handler, |
| 484 |
) |
| 485 |
require.NoError(t, err) |
| 486 |
|
| 487 |
// Create test server |
| 488 |
testSrv := httptest.NewServer(srv.Handler) |
| 489 |
defer testSrv.Close() |
| 490 |
|
| 491 |
// Compress the body if needed for the test |
| 492 |
requestBody := testBody |
| 493 |
if !tt.compressionBypassed && tt.expectedStatus == http.StatusOK { |
| 494 |
switch tt.contentEncoding { |
| 495 |
case "gzip": |
| 496 |
requestBody = compressGzip(t, testBody).Bytes() |
| 497 |
case "zstd": |
| 498 |
requestBody = compressZstd(t, testBody).Bytes() |
| 499 |
} |
| 500 |
} |
| 501 |
|
| 502 |
// Create request |
| 503 |
req, err := http.NewRequest(http.MethodPost, testSrv.URL, bytes.NewReader(requestBody)) |
| 504 |
require.NoError(t, err) |
| 505 |
req.Header.Set("Content-Type", "application/json") |
| 506 |
|
| 507 |
// Set Content-Encoding header if specified |
| 508 |
if tt.contentEncoding != "" { |
| 509 |
req.Header.Set("Content-Encoding", tt.contentEncoding) |
| 510 |
} |
| 511 |
|
| 512 |
// Send request |
| 513 |
client := &http.Client{} |
| 514 |
resp, err := client.Do(req) |
| 515 |
require.NoError(t, err) |
| 516 |
defer resp.Body.Close() |
| 517 |
|
| 518 |
// Verify response |
| 519 |
assert.Equal(t, tt.expectedStatus, resp.StatusCode, "Unexpected status code") |
| 520 |
|
| 521 |
body, err := io.ReadAll(resp.Body) |
| 522 |
require.NoError(t, err) |
| 523 |
|
| 524 |
if tt.expectedError != "" { |
| 525 |
assert.Contains(t, string(body), tt.expectedError, "Expected error message not found") |
| 526 |
} else { |
| 527 |
// For successful requests, body should be echoed back |
| 528 |
assert.Equal(t, testBody, body, "Response body should match request body") |
| 529 |
} |
| 530 |
}) |
| 531 |
} |
| 532 |
} |
| 533 |
|
| 534 |
func TestHTTPContentCompressionRequestWithNilBody(t *testing.T) { |
| 535 |
compressedGzipBody := compressGzip(t, []byte{}) |
| 536 |
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 537 |
w.WriteHeader(http.StatusOK) |
| 538 |
body, err := io.ReadAll(r.Body) |
| 539 |
assert.NoError(t, err, "failed to read request body: %v", err) |
| 540 |
assert.Equal(t, compressedGzipBody.Bytes(), body) |
| 541 |
})) |
| 542 |
defer srv.Close() |
| 543 |
|
| 544 |
req, err := http.NewRequest(http.MethodGet, srv.URL, http.NoBody) |
| 545 |
require.NoError(t, err, "failed to create request to test handler") |
| 546 |
|
| 547 |
client := srv.Client() |
| 548 |
compressionParams := newCompressionParams(gzip.DefaultCompression) |
| 549 |
client.Transport, err = newCompressRoundTripper(http.DefaultTransport, configcompression.TypeGzip, compressionParams) |
| 550 |
require.NoError(t, err) |
| 551 |
res, err := client.Do(req) |
| 552 |
require.NoError(t, err) |
| 553 |
|
| 554 |
_, err = io.ReadAll(res.Body) |
| 555 |
require.NoError(t, err) |
| 556 |
require.NoError(t, res.Body.Close(), "failed to close request body: %v", err) |
| 557 |
} |
| 558 |
|
| 559 |
func TestHTTPContentCompressionCopyError(t *testing.T) { |
| 560 |
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 561 |
w.WriteHeader(http.StatusOK) |
| 562 |
})) |
| 563 |
t.Cleanup(srv.Close) |
| 564 |
|
| 565 |
req, err := http.NewRequest(http.MethodGet, srv.URL, iotest.ErrReader(errors.New("read failed"))) |
| 566 |
require.NoError(t, err) |
| 567 |
|
| 568 |
client := srv.Client() |
| 569 |
compressionParams := newCompressionParams(gzip.DefaultCompression) |
| 570 |
client.Transport, err = newCompressRoundTripper(http.DefaultTransport, configcompression.TypeGzip, compressionParams) |
| 571 |
require.NoError(t, err) |
| 572 |
_, err = client.Do(req) |
| 573 |
require.Error(t, err) |
| 574 |
} |
| 575 |
|
| 576 |
type closeFailBody struct { |
| 577 |
*bytes.Buffer |
| 578 |
} |
| 579 |
|
| 580 |
func (*closeFailBody) Close() error { |
| 581 |
return errors.New("close failed") |
| 582 |
} |
| 583 |
|
| 584 |
func TestHTTPContentCompressionRequestBodyCloseError(t *testing.T) { |
| 585 |
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 586 |
w.WriteHeader(http.StatusOK) |
| 587 |
})) |
| 588 |
t.Cleanup(srv.Close) |
| 589 |
|
| 590 |
req, err := http.NewRequest(http.MethodGet, srv.URL, &closeFailBody{Buffer: bytes.NewBuffer([]byte("blank"))}) |
| 591 |
require.NoError(t, err) |
| 592 |
|
| 593 |
client := srv.Client() |
| 594 |
compressionParams := newCompressionParams(gzip.DefaultCompression) |
| 595 |
client.Transport, err = newCompressRoundTripper(http.DefaultTransport, configcompression.TypeGzip, compressionParams) |
| 596 |
require.NoError(t, err) |
| 597 |
_, err = client.Do(req) |
| 598 |
require.Error(t, err) |
| 599 |
} |
| 600 |
|
| 601 |
func TestOverrideCompressionList(t *testing.T) { |
| 602 |
// prepare |
| 603 |
configuredDecoders := []string{"none", "zlib"} |
| 604 |
|
| 605 |
srv := httptest.NewServer(httpContentDecompressor(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 606 |
w.WriteHeader(http.StatusOK) |
| 607 |
}), defaultMaxRequestBodySize, defaultErrorHandler, configuredDecoders, nil)) |
| 608 |
t.Cleanup(srv.Close) |
| 609 |
|
| 610 |
req, err := http.NewRequest(http.MethodGet, srv.URL, compressSnappyFramed(t, []byte("123decompressed body"))) |
| 611 |
require.NoError(t, err, "failed to create request to test handler") |
| 612 |
req.Header.Set("Content-Encoding", "snappy") |
| 613 |
|
| 614 |
client := srv.Client() |
| 615 |
|
| 616 |
// test |
| 617 |
res, err := client.Do(req) |
| 618 |
require.NoError(t, err) |
| 619 |
|
| 620 |
// verify |
| 621 |
assert.Equal(t, http.StatusBadRequest, res.StatusCode, "test handler returned unexpected status code ") |
| 622 |
_, err = io.ReadAll(res.Body) |
| 623 |
require.NoError(t, res.Body.Close(), "failed to close request body: %v", err) |
| 624 |
} |
| 625 |
|
| 626 |
func TestDecompressorAvoidDecompressionBomb(t *testing.T) { |
| 627 |
t.Parallel() |
| 628 |
|
| 629 |
for _, tc := range []struct { |
| 630 |
name string |
| 631 |
encoding string |
| 632 |
compress func(tb testing.TB, payload []byte) *bytes.Buffer |
| 633 |
framedSnappyEnabled bool |
| 634 |
}{ |
| 635 |
// None encoding is ignored since it does not |
| 636 |
// enforce the max body size if content encoding header is not set |
| 637 |
{ |
| 638 |
name: "gzip", |
| 639 |
encoding: "gzip", |
| 640 |
compress: compressGzip, |
| 641 |
}, |
| 642 |
{ |
| 643 |
name: "zstd", |
| 644 |
encoding: "zstd", |
| 645 |
compress: compressZstd, |
| 646 |
}, |
| 647 |
{ |
| 648 |
name: "zlib", |
| 649 |
encoding: "zlib", |
| 650 |
compress: compressZlib, |
| 651 |
}, |
| 652 |
{ |
| 653 |
name: "x-snappy-framed", |
| 654 |
encoding: "x-snappy-framed", |
| 655 |
compress: compressSnappyFramed, |
| 656 |
}, |
| 657 |
{ |
| 658 |
name: "x-snappy-not-framed", |
| 659 |
encoding: "x-snappy-framed", |
| 660 |
compress: compressSnappyFramed, |
| 661 |
framedSnappyEnabled: false, |
| 662 |
}, |
| 663 |
{ |
| 664 |
name: "snappy", |
| 665 |
encoding: "snappy", |
| 666 |
compress: compressSnappy, |
| 667 |
}, |
| 668 |
{ |
| 669 |
name: "lz4", |
| 670 |
encoding: "lz4", |
| 671 |
compress: compressLz4, |
| 672 |
}, |
| 673 |
} { |
| 674 |
t.Run(tc.name, func(t *testing.T) { |
| 675 |
// t.Parallel() // TODO: Re-enable parallel tests once feature gate is removed. We can't parallelize since registry is shared. |
| 676 |
require.NoError(t, featuregate.GlobalRegistry().Set(enableFramedSnappy.ID(), tc.framedSnappyEnabled)) |
| 677 |
|
| 678 |
h := httpContentDecompressor( |
| 679 |
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 680 |
n, err := io.Copy(io.Discard, r.Body) |
| 681 |
assert.Equal(t, int64(1024), n, "Must have only read the limited value of bytes") |
| 682 |
assert.EqualError(t, err, "http: request body too large") |
| 683 |
w.WriteHeader(http.StatusBadRequest) |
| 684 |
}), |
| 685 |
1024, |
| 686 |
defaultErrorHandler, |
| 687 |
defaultCompressionAlgorithms(), |
| 688 |
availableDecoders, |
| 689 |
) |
| 690 |
|
| 691 |
payload := tc.compress(t, make([]byte, 2*1024)) // 2KB uncompressed payload |
| 692 |
assert.NotEmpty(t, payload.Bytes(), "Must have data available") |
| 693 |
|
| 694 |
req := httptest.NewRequest(http.MethodPost, "/", payload) |
| 695 |
req.Header.Set("Content-Encoding", tc.encoding) |
| 696 |
|
| 697 |
resp := httptest.NewRecorder() |
| 698 |
|
| 699 |
h.ServeHTTP(resp, req) |
| 700 |
|
| 701 |
assert.Equal(t, http.StatusBadRequest, resp.Code, "Must match the expected code") |
| 702 |
assert.Empty(t, resp.Body.String(), "Must match the returned string") |
| 703 |
}) |
| 704 |
} |
| 705 |
} |
| 706 |
|
| 707 |
func TestPooledZstdReadCloserReadAfterClose(t *testing.T) { |
| 708 |
h := httpContentDecompressor( |
| 709 |
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 710 |
buf := make([]byte, 1024) |
| 711 |
_, err := r.Body.Read(buf) |
| 712 |
assert.NoError(t, err) |
| 713 |
err = r.Body.Close() |
| 714 |
assert.NoError(t, err) |
| 715 |
_, err = r.Body.Read(buf) |
| 716 |
assert.ErrorIs(t, err, zstd.ErrDecoderClosed) |
| 717 |
w.WriteHeader(http.StatusBadRequest) |
| 718 |
}), |
| 719 |
defaultMaxRequestBodySize, |
| 720 |
defaultErrorHandler, |
| 721 |
defaultCompressionAlgorithms(), |
| 722 |
availableDecoders, |
| 723 |
) |
| 724 |
|
| 725 |
payload := compressZstd(t, make([]byte, 2*1024)) // 2KB uncompressed payload |
| 726 |
assert.NotEmpty(t, payload.Bytes(), "Must have data available") |
| 727 |
|
| 728 |
req := httptest.NewRequest(http.MethodPost, "/", payload) |
| 729 |
req.Header.Set("Content-Encoding", "zstd") |
| 730 |
|
| 731 |
resp := httptest.NewRecorder() |
| 732 |
|
| 733 |
h.ServeHTTP(resp, req) |
| 734 |
|
| 735 |
assert.Equal(t, http.StatusBadRequest, resp.Code, "Must match the expected code") |
| 736 |
assert.Empty(t, resp.Body.String(), "Must match the returned string") |
| 737 |
} |
| 738 |
|
| 739 |
func compressGzip(tb testing.TB, body []byte) *bytes.Buffer { |
| 740 |
var buf bytes.Buffer |
| 741 |
gw, _ := gzip.NewWriterLevel(&buf, gzip.DefaultCompression) |
| 742 |
_, err := gw.Write(body) |
| 743 |
require.NoError(tb, err) |
| 744 |
require.NoError(tb, gw.Close()) |
| 745 |
return &buf |
| 746 |
} |
| 747 |
|
| 748 |
func compressZlib(tb testing.TB, body []byte) *bytes.Buffer { |
| 749 |
var buf bytes.Buffer |
| 750 |
zw, _ := zlib.NewWriterLevel(&buf, zlib.DefaultCompression) |
| 751 |
_, err := zw.Write(body) |
| 752 |
require.NoError(tb, err) |
| 753 |
require.NoError(tb, zw.Close()) |
| 754 |
return &buf |
| 755 |
} |
| 756 |
|
| 757 |
func compressSnappyFramed(tb testing.TB, body []byte) *bytes.Buffer { |
| 758 |
var buf bytes.Buffer |
| 759 |
sw := snappy.NewBufferedWriter(&buf) |
| 760 |
_, err := sw.Write(body) |
| 761 |
require.NoError(tb, err) |
| 762 |
require.NoError(tb, sw.Close()) |
| 763 |
return &buf |
| 764 |
} |
| 765 |
|
| 766 |
func compressSnappy(tb testing.TB, body []byte) *bytes.Buffer { |
| 767 |
var buf bytes.Buffer |
| 768 |
compressed := snappy.Encode(nil, body) |
| 769 |
_, err := buf.Write(compressed) |
| 770 |
require.NoError(tb, err) |
| 771 |
return &buf |
| 772 |
} |
| 773 |
|
| 774 |
func compressZstd(tb testing.TB, body []byte) *bytes.Buffer { |
| 775 |
var buf bytes.Buffer |
| 776 |
compression := zstd.SpeedFastest |
| 777 |
encoderLevel := zstd.WithEncoderLevel(compression) |
| 778 |
zw, _ := zstd.NewWriter(&buf, encoderLevel) |
| 779 |
_, err := zw.Write(body) |
| 780 |
require.NoError(tb, err) |
| 781 |
require.NoError(tb, zw.Close()) |
| 782 |
return &buf |
| 783 |
} |
| 784 |
|
| 785 |
func compressLz4(tb testing.TB, body []byte) *bytes.Buffer { |
| 786 |
var buf bytes.Buffer |
| 787 |
lz := lz4.NewWriter(&buf) |
| 788 |
_, err := lz.Write(body) |
| 789 |
require.NoError(tb, err) |
| 790 |
require.NoError(tb, lz.Close()) |
| 791 |
return &buf |
| 792 |
} |