Debian Codegraph @

config/confighttp/server_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package confighttp
5
6 import (
7 "bytes"
8 "context"
9 "errors"
10 "fmt"
11 "io"
12 "net/http"
13 "net/http/httptest"
14 "path/filepath"
15 "strconv"
16 "strings"
17 "testing"
18 "time"
19
20 "github.com/stretchr/testify/assert"
21 "github.com/stretchr/testify/require"
22
23 "go.opentelemetry.io/collector/component"
24 "go.opentelemetry.io/collector/component/componenttest"
25 "go.opentelemetry.io/collector/config/configauth"
26 "go.opentelemetry.io/collector/config/configmiddleware"
27 "go.opentelemetry.io/collector/config/configopaque"
28 "go.opentelemetry.io/collector/config/configoptional"
29 "go.opentelemetry.io/collector/config/configtls"
30 "go.opentelemetry.io/collector/confmap/confmaptest"
31 "go.opentelemetry.io/collector/confmap/xconfmap"
32 "go.opentelemetry.io/collector/extension"
33 "go.opentelemetry.io/collector/extension/extensionauth"
34 )
35
36 var (
37 _ extension.Extension = (*mockAuthServer)(nil)
38 _ extensionauth.Server = (*mockAuthServer)(nil)
39 )
40
41 type mockAuthServer struct {
42 component.StartFunc
43 component.ShutdownFunc
44 extensionauth.ServerAuthenticateFunc
45 }
46
47 func newMockAuthServer(auth func(ctx context.Context, sources map[string][]string) (context.Context, error)) extension.Extension {
48 return &mockAuthServer{ServerAuthenticateFunc: auth}
49 }
50
51 func TestHTTPServerSettingsError(t *testing.T) {
52 tests := []struct {
53 settings ServerConfig
54 err string
55 }{
56 {
57 err: "^failed to load TLS config: failed to load CA CertPool File: failed to load cert /doesnt/exist:",
58 settings: ServerConfig{
59 Endpoint: "localhost:0",
60 TLS: configoptional.Some(configtls.ServerConfig{
61 Config: configtls.Config{
62 CAFile: "/doesnt/exist",
63 },
64 }),
65 },
66 },
67 {
68 err: "^failed to load TLS config: failed to load TLS cert and key: for auth via TLS, provide both certificate and key, or neither",
69 settings: ServerConfig{
70 Endpoint: "localhost:0",
71 TLS: configoptional.Some(configtls.ServerConfig{
72 Config: configtls.Config{
73 CertFile: "/doesnt/exist",
74 },
75 }),
76 },
77 },
78 {
79 err: "failed to load client CA CertPool: failed to load CA /doesnt/exist:",
80 settings: ServerConfig{
81 Endpoint: "localhost:0",
82 TLS: configoptional.Some(configtls.ServerConfig{
83 ClientCAFile: "/doesnt/exist",
84 }),
85 },
86 },
87 }
88 for _, tt := range tests {
89 t.Run(tt.err, func(t *testing.T) {
90 _, err := tt.settings.ToListener(context.Background())
91 assert.Regexp(t, tt.err, err)
92 })
93 }
94 }
95
96 func TestHttpReception(t *testing.T) {
97 tests := []struct {
98 name string
99 tlsServerCreds configoptional.Optional[configtls.ServerConfig]
100 tlsClientCreds *configtls.ClientConfig
101 hasError bool
102 forceHTTP1 bool
103 }{
104 {
105 name: "noTLS",
106 tlsServerCreds: configoptional.None[configtls.ServerConfig](),
107 tlsClientCreds: &configtls.ClientConfig{
108 Insecure: true,
109 },
110 },
111 {
112 name: "TLS",
113 tlsServerCreds: configoptional.Some(configtls.ServerConfig{
114 Config: configtls.Config{
115 CAFile: filepath.Join("testdata", "ca.crt"),
116 CertFile: filepath.Join("testdata", "server.crt"),
117 KeyFile: filepath.Join("testdata", "server.key"),
118 },
119 }),
120 tlsClientCreds: &configtls.ClientConfig{
121 Config: configtls.Config{
122 CAFile: filepath.Join("testdata", "ca.crt"),
123 },
124 ServerName: "localhost",
125 },
126 },
127 {
128 name: "TLS (HTTP/1.1)",
129 tlsServerCreds: configoptional.Some(configtls.ServerConfig{
130 Config: configtls.Config{
131 CAFile: filepath.Join("testdata", "ca.crt"),
132 CertFile: filepath.Join("testdata", "server.crt"),
133 KeyFile: filepath.Join("testdata", "server.key"),
134 },
135 }),
136 tlsClientCreds: &configtls.ClientConfig{
137 Config: configtls.Config{
138 CAFile: filepath.Join("testdata", "ca.crt"),
139 },
140 ServerName: "localhost",
141 },
142 forceHTTP1: true,
143 },
144 {
145 name: "NoServerCertificates",
146 tlsServerCreds: configoptional.Some(configtls.ServerConfig{
147 Config: configtls.Config{
148 CAFile: filepath.Join("testdata", "ca.crt"),
149 },
150 }),
151 tlsClientCreds: &configtls.ClientConfig{
152 Config: configtls.Config{
153 CAFile: filepath.Join("testdata", "ca.crt"),
154 },
155 ServerName: "localhost",
156 },
157 hasError: true,
158 },
159 {
160 name: "mTLS",
161 tlsServerCreds: configoptional.Some(configtls.ServerConfig{
162 Config: configtls.Config{
163 CAFile: filepath.Join("testdata", "ca.crt"),
164 CertFile: filepath.Join("testdata", "server.crt"),
165 KeyFile: filepath.Join("testdata", "server.key"),
166 },
167 ClientCAFile: filepath.Join("testdata", "ca.crt"),
168 }),
169 tlsClientCreds: &configtls.ClientConfig{
170 Config: configtls.Config{
171 CAFile: filepath.Join("testdata", "ca.crt"),
172 CertFile: filepath.Join("testdata", "client.crt"),
173 KeyFile: filepath.Join("testdata", "client.key"),
174 },
175 ServerName: "localhost",
176 },
177 },
178 {
179 name: "NoClientCertificate",
180 tlsServerCreds: configoptional.Some(configtls.ServerConfig{
181 Config: configtls.Config{
182 CAFile: filepath.Join("testdata", "ca.crt"),
183 CertFile: filepath.Join("testdata", "server.crt"),
184 KeyFile: filepath.Join("testdata", "server.key"),
185 },
186 ClientCAFile: filepath.Join("testdata", "ca.crt"),
187 }),
188 tlsClientCreds: &configtls.ClientConfig{
189 Config: configtls.Config{
190 CAFile: filepath.Join("testdata", "ca.crt"),
191 },
192 ServerName: "localhost",
193 },
194 hasError: true,
195 },
196 {
197 name: "WrongClientCA",
198 tlsServerCreds: configoptional.Some(configtls.ServerConfig{
199 Config: configtls.Config{
200 CAFile: filepath.Join("testdata", "ca.crt"),
201 CertFile: filepath.Join("testdata", "server.crt"),
202 KeyFile: filepath.Join("testdata", "server.key"),
203 },
204 ClientCAFile: filepath.Join("testdata", "server.crt"),
205 }),
206 tlsClientCreds: &configtls.ClientConfig{
207 Config: configtls.Config{
208 CAFile: filepath.Join("testdata", "ca.crt"),
209 CertFile: filepath.Join("testdata", "client.crt"),
210 KeyFile: filepath.Join("testdata", "client.key"),
211 },
212 ServerName: "localhost",
213 },
214 hasError: true,
215 },
216 }
217 // prepare
218
219 for _, tt := range tests {
220 t.Run(tt.name, func(t *testing.T) {
221 sc := &ServerConfig{
222 Endpoint: "localhost:0",
223 TLS: tt.tlsServerCreds,
224 }
225 ln, err := sc.ToListener(context.Background())
226 require.NoError(t, err)
227
228 s, err := sc.ToServer(
229 context.Background(),
230 nil,
231 componenttest.NewNopTelemetrySettings(),
232 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
233 _, errWrite := fmt.Fprint(w, "tt")
234 assert.NoError(t, errWrite)
235 }))
236 require.NoError(t, err)
237
238 go func() {
239 _ = s.Serve(ln)
240 }()
241
242 prefix := "https://"
243 expectedProto := "HTTP/2.0"
244 if tt.tlsClientCreds.Insecure {
245 prefix = "http://"
246 expectedProto = "HTTP/1.1"
247 }
248
249 cc := &ClientConfig{
250 Endpoint: prefix + ln.Addr().String(),
251 TLS: *tt.tlsClientCreds,
252 ForceAttemptHTTP2: true,
253 }
254
255 client, errClient := cc.ToClient(context.Background(), nil, nilProvidersSettings)
256 require.NoError(t, errClient)
257
258 if tt.forceHTTP1 {
259 expectedProto = "HTTP/1.1"
260 client.Transport.(*http.Transport).ForceAttemptHTTP2 = false
261 }
262
263 resp, errResp := client.Get(cc.Endpoint)
264 if tt.hasError {
265 require.Error(t, errResp)
266 } else {
267 require.NoError(t, errResp)
268 body, errRead := io.ReadAll(resp.Body)
269 require.NoError(t, errRead)
270 assert.Equal(t, "tt", string(body))
271 assert.Equal(t, expectedProto, resp.Proto)
272 }
273 require.NoError(t, s.Close())
274 })
275 }
276 }
277
278 func TestHttpCors(t *testing.T) {
279 tests := []struct {
280 name string
281
282 CORSConfig configoptional.Optional[CORSConfig]
283
284 allowedWorks bool
285 disallowedWorks bool
286 extraHeaderWorks bool
287 }{
288 {
289 name: "noCORS",
290 allowedWorks: false,
291 disallowedWorks: false,
292 extraHeaderWorks: false,
293 },
294 {
295 name: "emptyCORS",
296 CORSConfig: configoptional.Some(NewDefaultCORSConfig()),
297 allowedWorks: false,
298 disallowedWorks: false,
299 extraHeaderWorks: false,
300 },
301 {
302 name: "OriginCORS",
303 CORSConfig: configoptional.Some(CORSConfig{
304 AllowedOrigins: []string{"allowed-*.com"},
305 }),
306 allowedWorks: true,
307 disallowedWorks: false,
308 extraHeaderWorks: false,
309 },
310 {
311 name: "CacheableCORS",
312 CORSConfig: configoptional.Some(CORSConfig{
313 AllowedOrigins: []string{"allowed-*.com"},
314 MaxAge: 360,
315 }),
316 allowedWorks: true,
317 disallowedWorks: false,
318 extraHeaderWorks: false,
319 },
320 {
321 name: "HeaderCORS",
322 CORSConfig: configoptional.Some(CORSConfig{
323 AllowedOrigins: []string{"allowed-*.com"},
324 AllowedHeaders: []string{"ExtraHeader"},
325 }),
326 allowedWorks: true,
327 disallowedWorks: false,
328 extraHeaderWorks: true,
329 },
330 }
331
332 for _, tt := range tests {
333 t.Run(tt.name, func(t *testing.T) {
334 sc := &ServerConfig{
335 Endpoint: "localhost:0",
336 CORS: tt.CORSConfig,
337 }
338
339 ln, err := sc.ToListener(context.Background())
340 require.NoError(t, err)
341
342 s, err := sc.ToServer(
343 context.Background(),
344 nil,
345 componenttest.NewNopTelemetrySettings(),
346 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
347 w.WriteHeader(http.StatusOK)
348 }))
349 require.NoError(t, err)
350
351 go func() {
352 _ = s.Serve(ln)
353 }()
354
355 url := "http://" + ln.Addr().String()
356
357 expectedStatus := http.StatusNoContent
358 if !tt.CORSConfig.HasValue() || len(tt.CORSConfig.Get().AllowedOrigins) == 0 {
359 expectedStatus = http.StatusOK
360 }
361
362 // Verify allowed domain gets responses that allow CORS.
363 verifyCorsResp(t, url, "allowed-origin.com", tt.CORSConfig, false, expectedStatus, tt.allowedWorks)
364
365 // Verify allowed domain and extra headers gets responses that allow CORS.
366 verifyCorsResp(t, url, "allowed-origin.com", tt.CORSConfig, true, expectedStatus, tt.extraHeaderWorks)
367
368 // Verify disallowed domain gets responses that disallow CORS.
369 verifyCorsResp(t, url, "disallowed-origin.com", tt.CORSConfig, false, expectedStatus, tt.disallowedWorks)
370
371 require.NoError(t, s.Close())
372 })
373 }
374 }
375
376 func TestHttpCorsInvalidSettings(t *testing.T) {
377 sc := &ServerConfig{
378 Endpoint: "localhost:0",
379 CORS: configoptional.Some(CORSConfig{AllowedHeaders: []string{"some-header"}}),
380 }
381
382 // This effectively does not enable CORS but should also not cause an error
383 s, err := sc.ToServer(
384 context.Background(),
385 nil,
386 componenttest.NewNopTelemetrySettings(),
387 http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
388 require.NoError(t, err)
389 require.NotNil(t, s)
390 require.NoError(t, s.Close())
391 }
392
393 func TestHttpCorsWithSettings(t *testing.T) {
394 sc := &ServerConfig{
395 Endpoint: "localhost:0",
396 CORS: configoptional.Some(CORSConfig{
397 AllowedOrigins: []string{"*"},
398 }),
399 Auth: configoptional.Some(AuthConfig{
400 Config: configauth.Config{
401 AuthenticatorID: mockID,
402 },
403 }),
404 }
405
406 extensions := map[component.ID]component.Component{
407 mockID: newMockAuthServer(func(ctx context.Context, _ map[string][]string) (context.Context, error) {
408 return ctx, errors.New("Settings failed")
409 }),
410 }
411
412 srv, err := sc.ToServer(context.Background(), extensions, componenttest.NewNopTelemetrySettings(), nil)
413 require.NoError(t, err)
414 require.NotNil(t, srv)
415
416 rec := httptest.NewRecorder()
417 req := httptest.NewRequest(http.MethodOptions, "/", http.NoBody)
418 req.Header.Set("Origin", "http://localhost")
419 req.Header.Set("Access-Control-Request-Method", http.MethodPost)
420 srv.Handler.ServeHTTP(rec, req)
421
422 assert.Equal(t, http.StatusNoContent, rec.Result().StatusCode)
423 assert.Equal(t, "*", rec.Header().Get("Access-Control-Allow-Origin"))
424 }
425
426 func TestHttpServerHeaders(t *testing.T) {
427 tests := []struct {
428 name string
429 headers configopaque.MapList
430 }{
431 {
432 name: "noHeaders",
433 headers: nil,
434 },
435 {
436 name: "withHeaders",
437 headers: configopaque.MapList{
438 {Name: "x-new-header-1", Value: "value1"},
439 {Name: "x-new-header-2", Value: "value2"},
440 },
441 },
442 }
443
444 for _, tt := range tests {
445 t.Run(tt.name, func(t *testing.T) {
446 sc := &ServerConfig{
447 Endpoint: "localhost:0",
448 ResponseHeaders: tt.headers,
449 }
450
451 ln, err := sc.ToListener(context.Background())
452 require.NoError(t, err)
453
454 s, err := sc.ToServer(
455 context.Background(),
456 nil,
457 componenttest.NewNopTelemetrySettings(),
458 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
459 w.WriteHeader(http.StatusOK)
460 }))
461 require.NoError(t, err)
462
463 go func() {
464 _ = s.Serve(ln)
465 }()
466
467 url := "http://" + ln.Addr().String()
468
469 // Verify allowed domain gets responses that allow CORS.
470 verifyHeadersResp(t, url, tt.headers)
471
472 require.NoError(t, s.Close())
473 })
474 }
475 }
476
477 func verifyCorsResp(t *testing.T, url, origin string, set configoptional.Optional[CORSConfig], extraHeader bool, wantStatus int, wantAllowed bool) {
478 req, err := http.NewRequest(http.MethodOptions, url, http.NoBody)
479 require.NoError(t, err, "Error creating trace OPTIONS request: %v", err)
480 req.Header.Set("Origin", origin)
481 if extraHeader {
482 req.Header.Set("ExtraHeader", "foo")
483 req.Header.Set("Access-Control-Request-Headers", "extraheader")
484 }
485 req.Header.Set("Access-Control-Request-Method", "POST")
486
487 resp, err := http.DefaultClient.Do(req)
488 require.NoError(t, err, "Error sending OPTIONS to http server")
489 require.NotNil(t, resp.Body)
490 require.NoError(t, resp.Body.Close(), "Error closing OPTIONS response body")
491
492 assert.Equal(t, wantStatus, resp.StatusCode)
493
494 gotAllowOrigin := resp.Header.Get("Access-Control-Allow-Origin")
495 gotAllowMethods := resp.Header.Get("Access-Control-Allow-Methods")
496
497 wantAllowOrigin := ""
498 wantAllowMethods := ""
499 wantMaxAge := ""
500 if wantAllowed {
501 wantAllowOrigin = origin
502 wantAllowMethods = "POST"
503 if set.HasValue() && set.Get().MaxAge != 0 {
504 wantMaxAge = strconv.Itoa(set.Get().MaxAge)
505 }
506 }
507 assert.Equal(t, wantAllowOrigin, gotAllowOrigin)
508 assert.Equal(t, wantAllowMethods, gotAllowMethods)
509 assert.Equal(t, wantMaxAge, resp.Header.Get("Access-Control-Max-Age"))
510 }
511
512 func verifyHeadersResp(t *testing.T, url string, expected configopaque.MapList) {
513 req, err := http.NewRequest(http.MethodGet, url, http.NoBody)
514 require.NoError(t, err, "Error creating request")
515
516 resp, err := http.DefaultClient.Do(req)
517 require.NoError(t, err, "Error sending request to http server")
518 require.NotNil(t, resp.Body)
519 require.NoError(t, resp.Body.Close(), "Error closing response body")
520
521 assert.Equal(t, http.StatusOK, resp.StatusCode)
522
523 for k, v := range expected.Iter {
524 assert.Equal(t, string(v), resp.Header.Get(k))
525 }
526 }
527
528 func TestServerAuth(t *testing.T) {
529 // prepare
530 authCalled := false
531 sc := ServerConfig{
532 Endpoint: "localhost:0",
533 Auth: configoptional.Some(AuthConfig{
534 Config: configauth.Config{
535 AuthenticatorID: mockID,
536 },
537 }),
538 }
539
540 extensions := map[component.ID]component.Component{
541 mockID: newMockAuthServer(func(ctx context.Context, _ map[string][]string) (context.Context, error) {
542 authCalled = true
543 return ctx, nil
544 }),
545 }
546
547 handlerCalled := false
548 handler := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
549 handlerCalled = true
550 })
551
552 srv, err := sc.ToServer(context.Background(), extensions, componenttest.NewNopTelemetrySettings(), handler)
553 require.NoError(t, err)
554
555 // tt
556 srv.Handler.ServeHTTP(&httptest.ResponseRecorder{}, httptest.NewRequest(http.MethodGet, "/", http.NoBody))
557
558 // verify
559 assert.True(t, handlerCalled)
560 assert.True(t, authCalled)
561 }
562
563 func TestInvalidServerAuth(t *testing.T) {
564 sc := ServerConfig{
565 Auth: configoptional.Some(AuthConfig{
566 Config: configauth.Config{
567 AuthenticatorID: nonExistingID,
568 },
569 }),
570 }
571
572 srv, err := sc.ToServer(context.Background(), nil, componenttest.NewNopTelemetrySettings(), http.NewServeMux())
573 require.Error(t, err)
574 require.Nil(t, srv)
575 }
576
577 func TestFailedServerAuth(t *testing.T) {
578 // prepare
579 sc := ServerConfig{
580 Endpoint: "localhost:0",
581 Auth: configoptional.Some(AuthConfig{
582 Config: configauth.Config{
583 AuthenticatorID: mockID,
584 },
585 }),
586 }
587 extensions := map[component.ID]component.Component{
588 mockID: newMockAuthServer(func(ctx context.Context, _ map[string][]string) (context.Context, error) {
589 return ctx, errors.New("invalid authorization")
590 }),
591 }
592
593 srv, err := sc.ToServer(context.Background(), extensions, componenttest.NewNopTelemetrySettings(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
594 require.NoError(t, err)
595
596 // tt
597 response := &httptest.ResponseRecorder{}
598 srv.Handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", http.NoBody))
599
600 // verify
601 assert.Equal(t, http.StatusUnauthorized, response.Result().StatusCode)
602 assert.Equal(t, fmt.Sprintf("%v %s", http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized)), response.Result().Status)
603 }
604
605 func TestFailedServerAuthWithErrorHandler(t *testing.T) {
606 // prepare
607 sc := ServerConfig{
608 Endpoint: "localhost:0",
609 Auth: configoptional.Some(AuthConfig{
610 Config: configauth.Config{
611 AuthenticatorID: mockID,
612 },
613 }),
614 }
615 extensions := map[component.ID]component.Component{
616 mockID: newMockAuthServer(func(ctx context.Context, _ map[string][]string) (context.Context, error) {
617 return ctx, errors.New("invalid authorization")
618 }),
619 }
620
621 eh := func(w http.ResponseWriter, _ *http.Request, err string, statusCode int) {
622 assert.Equal(t, http.StatusUnauthorized, statusCode)
623 // custom error handler uses real error string
624 assert.Equal(t, "invalid authorization", err)
625 // custom error handler changes returned status code
626 http.Error(w, err, http.StatusInternalServerError)
627 }
628
629 srv, err := sc.ToServer(context.Background(), extensions, componenttest.NewNopTelemetrySettings(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), WithErrorHandler(eh))
630 require.NoError(t, err)
631
632 // tt
633 response := &httptest.ResponseRecorder{}
634 srv.Handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", http.NoBody))
635
636 // verify
637 assert.Equal(t, http.StatusInternalServerError, response.Result().StatusCode)
638 assert.Equal(t, fmt.Sprintf("%v %s", http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)), response.Result().Status)
639 }
640
641 func TestServerWithErrorHandler(t *testing.T) {
642 // prepare
643 sc := ServerConfig{
644 Endpoint: "localhost:0",
645 }
646 eh := func(w http.ResponseWriter, _ *http.Request, _ string, statusCode int) {
647 assert.Equal(t, http.StatusBadRequest, statusCode)
648 // custom error handler changes returned status code
649 http.Error(w, "invalid request", http.StatusInternalServerError)
650 }
651
652 srv, err := sc.ToServer(
653 context.Background(),
654 nil,
655 componenttest.NewNopTelemetrySettings(),
656 http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}),
657 WithErrorHandler(eh),
658 )
659 require.NoError(t, err)
660 // tt
661 response := &httptest.ResponseRecorder{}
662
663 req, err := http.NewRequest(http.MethodGet, srv.Addr, http.NoBody)
664 require.NoError(t, err, "Error creating request: %v", err)
665 req.Header.Set("Content-Encoding", "something-invalid")
666
667 srv.Handler.ServeHTTP(response, req)
668 // verify
669 assert.Equal(t, http.StatusInternalServerError, response.Result().StatusCode)
670 }
671
672 func TestServerWithDecoder(t *testing.T) {
673 // prepare
674 sc := NewDefaultServerConfig()
675 sc.Endpoint = "localhost:0"
676 decoder := func(body io.ReadCloser) (io.ReadCloser, error) {
677 return body, nil
678 }
679
680 srv, err := sc.ToServer(
681 context.Background(),
682 nil,
683 componenttest.NewNopTelemetrySettings(),
684 http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}),
685 WithDecoder("something-else", decoder),
686 )
687 require.NoError(t, err)
688 // tt
689 response := &httptest.ResponseRecorder{}
690
691 req, err := http.NewRequest(http.MethodGet, srv.Addr, bytes.NewBuffer([]byte("something")))
692 require.NoError(t, err, "Error creating request: %v", err)
693 req.Header.Set("Content-Encoding", "something-else")
694
695 srv.Handler.ServeHTTP(response, req)
696 // verify
697 assert.Equal(t, http.StatusOK, response.Result().StatusCode)
698 }
699
700 func TestServerWithDecompression(t *testing.T) {
701 // prepare
702 sc := ServerConfig{
703 MaxRequestBodySize: 1000, // 1 KB
704 }
705 body := []byte(strings.Repeat("a", 1000*1000)) // 1 MB
706
707 srv, err := sc.ToServer(
708 context.Background(),
709 nil,
710 componenttest.NewNopTelemetrySettings(),
711 http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
712 actualBody, err := io.ReadAll(req.Body)
713 assert.ErrorContains(t, err, "http: request body too large")
714 assert.Len(t, actualBody, 1000)
715
716 if err != nil {
717 resp.WriteHeader(http.StatusBadRequest)
718 } else {
719 resp.WriteHeader(http.StatusOK)
720 }
721 }),
722 )
723 require.NoError(t, err)
724
725 testSrv := httptest.NewServer(srv.Handler)
726 defer testSrv.Close()
727
728 req, err := http.NewRequest(http.MethodGet, testSrv.URL, compressZstd(t, body))
729 require.NoError(t, err, "Error creating request: %v", err)
730
731 req.Header.Set("Content-Encoding", "zstd")
732
733 // tt
734 c := http.Client{}
735 resp, err := c.Do(req)
736 require.NoError(t, err, "Error sending request: %v", err)
737
738 _, err = io.ReadAll(resp.Body)
739 require.NoError(t, err, "Error reading response body: %v", err)
740
741 // verifications is done mostly within the tt, but this is only a sanity check
742 // that we got into the tt handler
743 assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
744 }
745
746 func TestDefaultMaxRequestBodySize(t *testing.T) {
747 tests := []struct {
748 name string
749 settings ServerConfig
750 expected int64
751 }{
752 {
753 name: "default",
754 settings: ServerConfig{},
755 expected: defaultMaxRequestBodySize,
756 },
757 {
758 name: "zero",
759 settings: ServerConfig{MaxRequestBodySize: 0},
760 expected: defaultMaxRequestBodySize,
761 },
762 {
763 name: "negative",
764 settings: ServerConfig{MaxRequestBodySize: -1},
765 expected: defaultMaxRequestBodySize,
766 },
767 {
768 name: "custom",
769 settings: ServerConfig{MaxRequestBodySize: 100},
770 expected: 100,
771 },
772 }
773 for _, tt := range tests {
774 t.Run(tt.name, func(t *testing.T) {
775 _, err := tt.settings.ToServer(
776 context.Background(),
777 nil,
778 componenttest.NewNopTelemetrySettings(),
779 http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}),
780 )
781 require.NoError(t, err)
782 assert.Equal(t, tt.expected, tt.settings.MaxRequestBodySize)
783 })
784 }
785 }
786
787 func TestAuthWithQueryParams(t *testing.T) {
788 // prepare
789 authCalled := false
790 sc := ServerConfig{
791 Endpoint: "localhost:0",
792 Auth: configoptional.Some(AuthConfig{
793 RequestParameters: []string{"auth"},
794 Config: configauth.Config{
795 AuthenticatorID: mockID,
796 },
797 }),
798 }
799
800 extensions := map[component.ID]component.Component{
801 mockID: newMockAuthServer(func(ctx context.Context, sources map[string][]string) (context.Context, error) {
802 require.Len(t, sources, 1)
803 assert.Equal(t, "1", sources["auth"][0])
804 authCalled = true
805 return ctx, nil
806 }),
807 }
808
809 handlerCalled := false
810 handler := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
811 handlerCalled = true
812 })
813
814 srv, err := sc.ToServer(context.Background(), extensions, componenttest.NewNopTelemetrySettings(), handler)
815 require.NoError(t, err)
816
817 // tt
818 srv.Handler.ServeHTTP(&httptest.ResponseRecorder{}, httptest.NewRequest(http.MethodGet, "/?auth=1", http.NoBody))
819
820 // verify
821 assert.True(t, handlerCalled)
822 assert.True(t, authCalled)
823 }
824
825 func BenchmarkHttpRequest(b *testing.B) {
826 tests := []struct {
827 name string
828 forceHTTP1 bool
829 clientPerThread bool
830 }{
831 {
832 name: "HTTP/2.0, shared client (like load balancer)",
833 forceHTTP1: false,
834 clientPerThread: false,
835 },
836 {
837 name: "HTTP/1.1, shared client (like load balancer)",
838 forceHTTP1: true,
839 clientPerThread: false,
840 },
841 {
842 name: "HTTP/2.0, client per thread (like single app)",
843 forceHTTP1: false,
844 clientPerThread: true,
845 },
846 {
847 name: "HTTP/1.1, client per thread (like single app)",
848 forceHTTP1: true,
849 clientPerThread: true,
850 },
851 }
852
853 tlsServerCreds := configoptional.Some(configtls.ServerConfig{
854 Config: configtls.Config{
855 CAFile: filepath.Join("testdata", "ca.crt"),
856 CertFile: filepath.Join("testdata", "server.crt"),
857 KeyFile: filepath.Join("testdata", "server.key"),
858 },
859 })
860 tlsClientCreds := &configtls.ClientConfig{
861 Config: configtls.Config{
862 CAFile: filepath.Join("testdata", "ca.crt"),
863 },
864 ServerName: "localhost",
865 }
866
867 sc := &ServerConfig{
868 Endpoint: "localhost:0",
869 TLS: tlsServerCreds,
870 }
871
872 s, err := sc.ToServer(
873 context.Background(),
874 nil,
875 componenttest.NewNopTelemetrySettings(),
876 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
877 _, errWrite := fmt.Fprint(w, "tt")
878 assert.NoError(b, errWrite)
879 }))
880 require.NoError(b, err)
881 ln, err := sc.ToListener(context.Background())
882 require.NoError(b, err)
883
884 go func() {
885 _ = s.Serve(ln)
886 }()
887 defer func() {
888 _ = s.Close()
889 }()
890
891 for _, bb := range tests {
892 cc := &ClientConfig{
893 Endpoint: "https://" + ln.Addr().String(),
894 TLS: *tlsClientCreds,
895 }
896
897 b.Run(bb.name, func(b *testing.B) {
898 var c *http.Client
899 if !bb.clientPerThread {
900 c, err = cc.ToClient(context.Background(), nil, nilProvidersSettings)
901 require.NoError(b, err)
902 }
903 b.RunParallel(func(pb *testing.PB) {
904 if c == nil {
905 c, err = cc.ToClient(context.Background(), nil, nilProvidersSettings)
906 require.NoError(b, err)
907 }
908 if bb.forceHTTP1 {
909 c.Transport.(*http.Transport).ForceAttemptHTTP2 = false
910 }
911
912 for pb.Next() {
913 resp, errResp := c.Get(cc.Endpoint)
914 require.NoError(b, errResp)
915 body, errRead := io.ReadAll(resp.Body)
916 _ = resp.Body.Close()
917 require.NoError(b, errRead)
918 require.Equal(b, "tt", string(body))
919 }
920 c.CloseIdleConnections()
921 })
922 // Wait for connections to close before closing server to prevent log spam
923 <-time.After(10 * time.Millisecond)
924 })
925 }
926 }
927
928 func TestDefaultHTTPServerSettings(t *testing.T) {
929 httpServerSettings := NewDefaultServerConfig()
930 assert.NotNil(t, httpServerSettings.CORS)
931 assert.NotNil(t, httpServerSettings.TLS)
932 assert.Equal(t, 1*time.Minute, httpServerSettings.IdleTimeout)
933 assert.Equal(t, 30*time.Second, httpServerSettings.WriteTimeout)
934 assert.Equal(t, time.Duration(0), httpServerSettings.ReadTimeout)
935 assert.Equal(t, 1*time.Minute, httpServerSettings.ReadHeaderTimeout)
936 assert.True(t, httpServerSettings.KeepAlivesEnabled) // Default should be true (keep-alives enabled by default)
937 }
938
939 func TestHTTPServerKeepAlives(t *testing.T) {
940 tests := []struct {
941 name string
942 keepAlivesEnabled bool
943 expectedKeepAlives bool
944 }{
945 {
946 name: "KeepAlives enabled",
947 keepAlivesEnabled: true,
948 expectedKeepAlives: true,
949 },
950 {
951 name: "KeepAlives disabled",
952 keepAlivesEnabled: false,
953 expectedKeepAlives: false,
954 },
955 }
956
957 for _, tt := range tests {
958 t.Run(tt.name, func(t *testing.T) {
959 sc := &ServerConfig{
960 Endpoint: "localhost:0",
961 KeepAlivesEnabled: tt.keepAlivesEnabled,
962 }
963
964 server, err := sc.ToServer(
965 context.Background(),
966 nil,
967 componenttest.NewNopTelemetrySettings(),
968 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
969 w.WriteHeader(http.StatusOK)
970 }))
971
972 require.NoError(t, err)
973 require.NotNil(t, server)
974
975 // Since http.Server.disableKeepAlives is a private field and difficult to test directly,
976 // we'll verify the configuration was set by testing the server behavior.
977 // The main verification is that ToServer() succeeds without error when DisableKeepAlives is set.
978
979 ln, err := sc.ToListener(context.Background())
980 require.NoError(t, err)
981
982 go func() {
983 _ = server.Serve(ln)
984 }()
985 defer func() {
986 _ = server.Close()
987 }()
988
989 resp, err := http.Get("http://" + ln.Addr().String())
990 require.NoError(t, err)
991 require.NotNil(t, resp)
992 _ = resp.Body.Close()
993 assert.Equal(t, http.StatusOK, resp.StatusCode)
994
995 assert.Equal(t, tt.keepAlivesEnabled, sc.KeepAlivesEnabled)
996 })
997 }
998 }
999
1000 func TestHTTPServerTelemetry_Tracing(t *testing.T) {
1001 // Create a pattern route. The server name the span after the
1002 // pattern rather than the client-specified path.
1003 mux := http.NewServeMux()
1004 mux.HandleFunc("/b/{bucket}/o/{objectname...}", func(http.ResponseWriter, *http.Request) {})
1005
1006 type testcase struct {
1007 handler http.Handler
1008 expectedSpanName string
1009 }
1010
1011 for name, testcase := range map[string]testcase{
1012 "pattern": {
1013 handler: mux,
1014 expectedSpanName: "GET /b/{bucket}/o/{objectname...}",
1015 },
1016 "no_pattern": {
1017 handler: http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}),
1018 expectedSpanName: "GET",
1019 },
1020 } {
1021 t.Run(name, func(t *testing.T) {
1022 telemetry := componenttest.NewTelemetry()
1023 config := NewDefaultServerConfig()
1024 config.Endpoint = "localhost:0"
1025 srv, err := config.ToServer(
1026 context.Background(),
1027 nil,
1028 telemetry.NewTelemetrySettings(),
1029 testcase.handler,
1030 )
1031 require.NoError(t, err)
1032
1033 done := make(chan struct{})
1034 lis, err := config.ToListener(context.Background())
1035 require.NoError(t, err)
1036 go func() {
1037 defer close(done)
1038 _ = srv.Serve(lis)
1039 }()
1040 defer func() {
1041 assert.NoError(t, srv.Close())
1042 <-done
1043 }()
1044
1045 resp, err := http.Get(fmt.Sprintf("http://%s/b/bucket123/o/object456/segment", lis.Addr()))
1046 require.NoError(t, err)
1047 require.Equal(t, http.StatusOK, resp.StatusCode)
1048 resp.Body.Close()
1049
1050 spans := telemetry.SpanRecorder.Ended()
1051 require.Len(t, spans, 1)
1052 assert.Equal(t, testcase.expectedSpanName, spans[0].Name())
1053 })
1054 }
1055 }
1056
1057 // TestUnmarshalYAMLWithMiddlewares tests that the "middlewares" field is correctly
1058 // parsed from YAML configurations (fixing the bug where "middleware" was used instead)
1059 func TestServerUnmarshalYAMLWithMiddlewares(t *testing.T) {
1060 cm, err := confmaptest.LoadConf(filepath.Join("testdata", "middlewares.yaml"))
1061 require.NoError(t, err)
1062
1063 // Test server configuration
1064 var serverConfig ServerConfig
1065 serverSub, err := cm.Sub("server")
1066 require.NoError(t, err)
1067 require.NoError(t, serverSub.Unmarshal(&serverConfig))
1068
1069 // Validate the server configuration using reflection-based validation
1070 require.NoError(t, xconfmap.Validate(&serverConfig), "Server configuration should be valid")
1071
1072 assert.Equal(t, "0.0.0.0:4318", serverConfig.Endpoint)
1073 require.Len(t, serverConfig.Middlewares, 2)
1074 assert.Equal(t, component.MustNewID("careful_middleware"), serverConfig.Middlewares[0].ID)
1075 assert.Equal(t, component.MustNewID("support_middleware"), serverConfig.Middlewares[1].ID)
1076 }
1077
1078 // TestUnmarshalYAMLComprehensiveConfig tests the complete configuration example
1079 // to ensure all fields including middlewares are parsed correctly
1080 func TestServerUnmarshalYAMLComprehensiveConfig(t *testing.T) {
1081 cm, err := confmaptest.LoadConf(filepath.Join("testdata", "config.yaml"))
1082 require.NoError(t, err)
1083
1084 // Test server configuration
1085 var serverConfig ServerConfig
1086 serverSub, err := cm.Sub("server")
1087 require.NoError(t, err)
1088 require.NoError(t, serverSub.Unmarshal(&serverConfig))
1089
1090 // Validate the server configuration using reflection-based validation
1091 require.NoError(t, xconfmap.Validate(&serverConfig), "Server configuration should be valid")
1092
1093 // Verify basic fields
1094 assert.Equal(t, "0.0.0.0:4318", serverConfig.Endpoint)
1095 assert.Equal(t, 30*time.Second, serverConfig.ReadTimeout)
1096 assert.Equal(t, 10*time.Second, serverConfig.ReadHeaderTimeout)
1097 assert.Equal(t, 30*time.Second, serverConfig.WriteTimeout)
1098 assert.Equal(t, 120*time.Second, serverConfig.IdleTimeout)
1099 assert.True(t, serverConfig.KeepAlivesEnabled) // Should be true as configured in config.yaml
1100 assert.Equal(t, int64(33554432), serverConfig.MaxRequestBodySize)
1101 assert.True(t, serverConfig.IncludeMetadata)
1102
1103 // Verify TLS configuration
1104 assert.Equal(t, "/path/to/server.crt", serverConfig.TLS.Get().CertFile)
1105 assert.Equal(t, "/path/to/server.key", serverConfig.TLS.Get().KeyFile)
1106 assert.Equal(t, "/path/to/ca.crt", serverConfig.TLS.Get().CAFile)
1107 assert.Equal(t, "/path/to/client-ca.crt", serverConfig.TLS.Get().ClientCAFile)
1108
1109 // Verify CORS configuration
1110 expectedOrigins := []string{"https://example.com", "https://*.test.com"}
1111 assert.Equal(t, expectedOrigins, serverConfig.CORS.Get().AllowedOrigins)
1112 corsHeaders := []string{"Content-Type", "Accept"}
1113 assert.Equal(t, corsHeaders, serverConfig.CORS.Get().AllowedHeaders)
1114 assert.Equal(t, 7200, serverConfig.CORS.Get().MaxAge)
1115
1116 // Verify response headers
1117 expectedResponseHeaders := configopaque.MapList{
1118 {Name: "Server", Value: "OpenTelemetry-Collector"},
1119 {Name: "X-Flavor", Value: "apple"},
1120 }
1121 assert.Equal(t, expectedResponseHeaders, serverConfig.ResponseHeaders)
1122
1123 // Verify compression algorithms
1124 expectedAlgorithms := []string{"", "gzip", "zstd", "zlib", "snappy", "deflate"}
1125 assert.Equal(t, expectedAlgorithms, serverConfig.CompressionAlgorithms)
1126
1127 // Verify middlewares
1128 require.Len(t, serverConfig.Middlewares, 3)
1129 assert.Equal(t, component.MustNewID("server_middleware1"), serverConfig.Middlewares[0].ID)
1130 assert.Equal(t, component.MustNewID("server_middleware2"), serverConfig.Middlewares[1].ID)
1131 assert.Equal(t, component.MustNewID("server_middleware3"), serverConfig.Middlewares[2].ID)
1132 }
1133
1134 // TestMiddlewaresFieldCompatibility tests that the new "middlewares" field name
1135 // is used instead of the old "middleware" name, ensuring the bug is fixed
1136 func TestServerMiddlewaresFieldCompatibility(t *testing.T) {
1137 // Test that we can create a config with middlewares using the new field name
1138 serverConfig := ServerConfig{
1139 Endpoint: "0.0.0.0:4318",
1140 Middlewares: []configmiddleware.Config{
1141 {ID: component.MustNewID("server_middleware")},
1142 },
1143 }
1144 assert.Equal(t, "0.0.0.0:4318", serverConfig.Endpoint)
1145 assert.Len(t, serverConfig.Middlewares, 1)
1146 assert.Equal(t, component.MustNewID("server_middleware"), serverConfig.Middlewares[0].ID)
1147 }