Debian Codegraph @

pkg/endpoints/filters/authentication_test.go

raw
1 /*
2 Copyright 2014 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package filters
18
19 import (
20 "context"
21 "crypto/tls"
22 "crypto/x509"
23 "errors"
24 "io"
25 "net"
26 "net/http"
27 "net/http/httptest"
28 "sync/atomic"
29 "testing"
30 "time"
31
32 "github.com/google/go-cmp/cmp"
33 "github.com/stretchr/testify/assert"
34 "golang.org/x/net/http2"
35
36 "k8s.io/apiserver/pkg/authentication/authenticator"
37 "k8s.io/apiserver/pkg/authentication/authenticatorfactory"
38 "k8s.io/apiserver/pkg/authentication/request/anonymous"
39 "k8s.io/apiserver/pkg/authentication/request/headerrequest"
40 "k8s.io/apiserver/pkg/authentication/user"
41 genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
42 "k8s.io/apiserver/pkg/features"
43 utilfeature "k8s.io/apiserver/pkg/util/feature"
44 "k8s.io/client-go/kubernetes/scheme"
45 featuregatetesting "k8s.io/component-base/featuregate/testing"
46 )
47
48 func TestAuthenticateRequestWithAud(t *testing.T) {
49 success, failed := 0, 0
50 testcases := []struct {
51 name string
52 apiAuds []string
53 respAuds []string
54 expectSuccess bool
55 }{
56 {
57 name: "no api audience and no audience in response",
58 apiAuds: nil,
59 respAuds: nil,
60 expectSuccess: true,
61 },
62 {
63 name: "audience in response",
64 apiAuds: nil,
65 respAuds: []string{"other"},
66 expectSuccess: true,
67 },
68 {
69 name: "with api audience",
70 apiAuds: authenticator.Audiences([]string{"other"}),
71 respAuds: nil,
72 expectSuccess: true,
73 },
74 {
75 name: "api audience matching response audience",
76 apiAuds: authenticator.Audiences([]string{"other"}),
77 respAuds: []string{"other"},
78 expectSuccess: true,
79 },
80 {
81 name: "api audience non-matching response audience",
82 apiAuds: authenticator.Audiences([]string{"other"}),
83 respAuds: []string{"some"},
84 expectSuccess: false,
85 },
86 }
87 for _, tc := range testcases {
88 t.Run(tc.name, func(t *testing.T) {
89 success, failed = 0, 0
90 auth := WithAuthentication(
91 http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) {
92 if tc.expectSuccess {
93 success = 1
94 } else {
95 t.Errorf("unexpected call to handler")
96 }
97 }),
98 authenticator.RequestFunc(func(req *http.Request) (*authenticator.Response, bool, error) {
99 if req.Header.Get("Authorization") == "Something" {
100 return &authenticator.Response{User: &user.DefaultInfo{Name: "user"}, Audiences: authenticator.Audiences(tc.respAuds)}, true, nil
101 }
102 return nil, false, errors.New("Authorization header is missing.")
103 }),
104 http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
105 if tc.expectSuccess {
106 t.Errorf("unexpected call to failed")
107 } else {
108 failed = 1
109 }
110 }),
111 tc.apiAuds,
112 nil,
113 )
114 auth.ServeHTTP(httptest.NewRecorder(), &http.Request{Header: map[string][]string{"Authorization": {"Something"}}})
115 if tc.expectSuccess {
116 assert.Equal(t, 1, success)
117 assert.Equal(t, 0, failed)
118 } else {
119 assert.Equal(t, 0, success)
120 assert.Equal(t, 1, failed)
121 }
122 })
123 }
124 }
125
126 func TestAuthenticateMetrics(t *testing.T) {
127 testcases := []struct {
128 name string
129 header bool
130 apiAuds []string
131 respAuds []string
132 expectMetric bool
133 expectOk bool
134 expectError bool
135 }{
136 {
137 name: "no api audience and no audience in response",
138 header: true,
139 apiAuds: nil,
140 respAuds: nil,
141 expectOk: true,
142 expectError: false,
143 },
144 {
145 name: "api audience matching response audience",
146 header: true,
147 apiAuds: authenticator.Audiences([]string{"other"}),
148 respAuds: []string{"other"},
149 expectOk: true,
150 expectError: false,
151 },
152 {
153 name: "no intersection results in error",
154 header: true,
155 apiAuds: authenticator.Audiences([]string{"other"}),
156 respAuds: []string{"some"},
157 expectOk: true,
158 expectError: true,
159 },
160 {
161 name: "no header results in error",
162 header: false,
163 apiAuds: authenticator.Audiences([]string{"other"}),
164 respAuds: []string{"some"},
165 expectOk: false,
166 expectError: true,
167 },
168 }
169 for _, tc := range testcases {
170 t.Run(tc.name, func(t *testing.T) {
171 called := 0
172 auth := withAuthentication(
173 http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) {
174 }),
175 authenticator.RequestFunc(func(req *http.Request) (*authenticator.Response, bool, error) {
176 if req.Header.Get("Authorization") == "Something" {
177 return &authenticator.Response{User: &user.DefaultInfo{Name: "user"}, Audiences: authenticator.Audiences(tc.respAuds)}, true, nil
178 }
179 return nil, false, errors.New("Authorization header is missing.")
180 }),
181 http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
182 }),
183 tc.apiAuds,
184 nil,
185 func(ctx context.Context, resp *authenticator.Response, ok bool, err error, apiAudiences authenticator.Audiences, authStart time.Time, authFinish time.Time) {
186 called = 1
187 if tc.expectOk != ok {
188 t.Errorf("unexpected value of ok argument: %t", ok)
189 }
190 if tc.expectError {
191 if err == nil {
192 t.Errorf("unexpected value of err argument: %s", err)
193 }
194 } else {
195 if err != nil {
196 t.Errorf("unexpected value of err argument: %s", err)
197 }
198 }
199 },
200 )
201 if tc.header {
202 auth.ServeHTTP(httptest.NewRecorder(), &http.Request{Header: map[string][]string{"Authorization": {"Something"}}})
203 } else {
204 auth.ServeHTTP(httptest.NewRecorder(), &http.Request{})
205 }
206 assert.Equal(t, 1, called)
207 })
208 }
209 }
210
211 func TestAuthenticateRequest(t *testing.T) {
212 success := make(chan struct{})
213 auth := WithAuthentication(
214 http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) {
215 ctx := req.Context()
216 user, ok := genericapirequest.UserFrom(ctx)
217 if user == nil || !ok {
218 t.Errorf("no user stored in context: %#v", ctx)
219 }
220 if req.Header.Get("Authorization") != "" {
221 t.Errorf("Authorization header should be removed from request on success: %#v", req)
222 }
223 close(success)
224 }),
225 authenticator.RequestFunc(func(req *http.Request) (*authenticator.Response, bool, error) {
226 if req.Header.Get("Authorization") == "Something" {
227 return &authenticator.Response{User: &user.DefaultInfo{Name: "user"}}, true, nil
228 }
229 return nil, false, errors.New("Authorization header is missing.")
230 }),
231 http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
232 t.Errorf("unexpected call to failed")
233 }),
234 nil,
235 nil,
236 )
237
238 auth.ServeHTTP(httptest.NewRecorder(), &http.Request{Header: map[string][]string{"Authorization": {"Something"}}})
239
240 <-success
241 }
242
243 func TestAuthenticateRequestFailed(t *testing.T) {
244 failed := make(chan struct{})
245 auth := WithAuthentication(
246 http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) {
247 t.Errorf("unexpected call to handler")
248 }),
249 authenticator.RequestFunc(func(req *http.Request) (*authenticator.Response, bool, error) {
250 return nil, false, nil
251 }),
252 http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
253 close(failed)
254 }),
255 nil,
256 nil,
257 )
258
259 auth.ServeHTTP(httptest.NewRecorder(), &http.Request{})
260
261 <-failed
262 }
263
264 func TestAuthenticateRequestError(t *testing.T) {
265 failed := make(chan struct{})
266 auth := WithAuthentication(
267 http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) {
268 t.Errorf("unexpected call to handler")
269 }),
270 authenticator.RequestFunc(func(req *http.Request) (*authenticator.Response, bool, error) {
271 return nil, false, errors.New("failure")
272 }),
273 http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
274 close(failed)
275 }),
276 nil,
277 nil,
278 )
279
280 auth.ServeHTTP(httptest.NewRecorder(), &http.Request{})
281
282 <-failed
283 }
284
285 func TestAuthenticateRequestClearHeaders(t *testing.T) {
286 testcases := map[string]struct {
287 nameHeaders []string
288 uidHeaders []string
289 groupHeaders []string
290 extraPrefixHeaders []string
291 requestHeaders http.Header
292 finalHeaders http.Header
293 }{
294 "user match": {
295 nameHeaders: []string{"X-Remote-User"},
296 requestHeaders: http.Header{"X-Remote-User": {"Bob"}},
297 },
298 "user first match": {
299 nameHeaders: []string{
300 "X-Remote-User",
301 "A-Second-X-Remote-User",
302 "Another-X-Remote-User",
303 },
304 requestHeaders: http.Header{
305 "X-Remote-User": {"", "First header, second value"},
306 "A-Second-X-Remote-User": {"Second header, first value", "Second header, second value"},
307 "Another-X-Remote-User": {"Third header, first value"}},
308 },
309 "user case-insensitive": {
310 nameHeaders: []string{"x-REMOTE-user"}, // configured headers can be case-insensitive
311 requestHeaders: http.Header{"X-Remote-User": {"Bob"}}, // the parsed headers are normalized by the http package
312 },
313
314 "groups none": {
315 nameHeaders: []string{"X-Remote-User"},
316 groupHeaders: []string{"X-Remote-Group"},
317 requestHeaders: http.Header{
318 "X-Remote-User": {"Bob"},
319 },
320 },
321 "groups all matches": {
322 nameHeaders: []string{"X-Remote-User"},
323 groupHeaders: []string{"X-Remote-Group-1", "X-Remote-Group-2"},
324 requestHeaders: http.Header{
325 "X-Remote-User": {"Bob"},
326 "X-Remote-Group-1": {"one-a", "one-b"},
327 "X-Remote-Group-2": {"two-a", "two-b"},
328 },
329 },
330 "groups case-insensitive": {
331 nameHeaders: []string{"X-REMOTE-User"},
332 groupHeaders: []string{"X-REMOTE-Group"},
333 requestHeaders: http.Header{
334 "X-Remote-User": {"Bob"},
335 "X-Remote-Group": {"Users"},
336 },
337 },
338 "uid none": {
339 nameHeaders: []string{"X-Remote-User"},
340 uidHeaders: []string{"X-Remote-Uid"},
341 requestHeaders: http.Header{
342 "X-Remote-User": {"Alice"},
343 },
344 },
345 "uid all matches": {
346 nameHeaders: []string{"X-Remote-User"},
347 uidHeaders: []string{"X-Remote-Uid-1", "X-Remote-Uid-2"},
348 requestHeaders: http.Header{
349 "X-Remote-User": {"Alice"},
350 "X-Remote-Uid-1": {"one"},
351 "X-Remote-Uid-2": {"two", "three"},
352 },
353 },
354 "uid case-insensitive": {
355 nameHeaders: []string{"X-Remote-USER"},
356 uidHeaders: []string{"X-REMOTE-UID-1"},
357 requestHeaders: http.Header{
358 "X-Remote-User": {"Alice"},
359 "X-Remote-Uid-1": {"one"},
360 },
361 },
362
363 "extra prefix matches case-insensitive": {
364 nameHeaders: []string{"X-Remote-User"},
365 uidHeaders: []string{"X-Remote-Uid-1"},
366 groupHeaders: []string{"X-Remote-Group-1", "X-Remote-Group-2"},
367 extraPrefixHeaders: []string{"X-Remote-Extra-1-", "X-Remote-Extra-2-"},
368 requestHeaders: http.Header{
369 "X-Remote-User": {"Bob"},
370 "X-Remote-Uid-1": {"bobs-uid"},
371 "X-Remote-Group-1": {"one-a", "one-b"},
372 "X-Remote-Group-2": {"two-a", "two-b"},
373 "X-Remote-extra-1-key1": {"alfa", "bravo"},
374 "X-Remote-Extra-1-Key2": {"charlie", "delta"},
375 "X-Remote-Extra-1-": {"india", "juliet"},
376 "X-Remote-extra-2-": {"kilo", "lima"},
377 "X-Remote-extra-2-Key1": {"echo", "foxtrot"},
378 "X-Remote-Extra-2-key2": {"golf", "hotel"},
379 },
380 },
381
382 "extra prefix matches case-insensitive with unrelated headers": {
383 nameHeaders: []string{"X-Remote-User"},
384 uidHeaders: []string{"X-Remote-Uid"},
385 groupHeaders: []string{"X-Remote-Group-1", "X-Remote-Group-2"},
386 extraPrefixHeaders: []string{"X-Remote-Extra-1-", "X-Remote-Extra-2-"},
387 requestHeaders: http.Header{
388 "X-Group-Remote": {"snorlax"}, // unrelated header
389 "X-Group-Bear": {"panda"}, // another unrelated header
390 "X-Uid-Remote": {"bobs-unrelated-uid"},
391 "X-Remote-User": {"Bob"},
392 "X-Remote-Uid": {"bobs-uid"},
393 "X-Remote-Group-1": {"one-a", "one-b"},
394 "X-Remote-Group-2": {"two-a", "two-b"},
395 "X-Remote-extra-1-key1": {"alfa", "bravo"},
396 "X-Remote-Extra-1-Key2": {"charlie", "delta"},
397 "X-Remote-Extra-1-": {"india", "juliet"},
398 "X-Remote-extra-2-": {"kilo", "lima"},
399 "X-Remote-extra-2-Key1": {"echo", "foxtrot"},
400 "X-Remote-Extra-2-key2": {"golf", "hotel"},
401 },
402 finalHeaders: http.Header{
403 "X-Group-Remote": {"snorlax"},
404 "X-Group-Bear": {"panda"},
405 "X-Uid-Remote": {"bobs-unrelated-uid"},
406 },
407 },
408
409 "custom config but request contains standard headers": {
410 nameHeaders: []string{"foo"},
411 uidHeaders: []string{"footoo"},
412 groupHeaders: []string{"bar"},
413 extraPrefixHeaders: []string{"baz"},
414 requestHeaders: http.Header{
415 "X-Remote-User": {"Bob"},
416 "X-Remote-Uid": {"bobs-uid"},
417 "X-Remote-Group-1": {"one-a", "one-b"},
418 "X-Remote-Group-2": {"two-a", "two-b"},
419 "X-Remote-extra-1-key1": {"alfa", "bravo"},
420 "X-Remote-Extra-1-Key2": {"charlie", "delta"},
421 "X-Remote-Extra-1-": {"india", "juliet"},
422 "X-Remote-extra-2-": {"kilo", "lima"},
423 "X-Remote-extra-2-Key1": {"echo", "foxtrot"},
424 "X-Remote-Extra-2-key2": {"golf", "hotel"},
425 },
426 finalHeaders: http.Header{
427 "X-Remote-Group-1": {"one-a", "one-b"},
428 "X-Remote-Group-2": {"two-a", "two-b"},
429 },
430 },
431
432 "custom config but request contains standard and custom headers": {
433 nameHeaders: []string{"one"},
434 uidHeaders: []string{"onetoo"},
435 groupHeaders: []string{"two"},
436 extraPrefixHeaders: []string{"three-"},
437 requestHeaders: http.Header{
438 "X-Remote-User": {"Bob"},
439 "X-Remote-Uid": {"bobs-uid"},
440 "X-Remote-Group-3": {"one-a", "one-b"},
441 "X-Remote-Group-4": {"two-a", "two-b"},
442 "X-Remote-extra-1-key1": {"alfa", "bravo"},
443 "X-Remote-Extra-1-Key2": {"charlie", "delta"},
444 "X-Remote-Extra-1-": {"india", "juliet"},
445 "X-Remote-extra-2-": {"kilo", "lima"},
446 "X-Remote-extra-2-Key1": {"echo", "foxtrot"},
447 "X-Remote-Extra-2-key2": {"golf", "hotel"},
448 "One": {"echo", "foxtrot"},
449 "Two": {"golf", "hotel"},
450 "Three-Four": {"india", "juliet"},
451 },
452 finalHeaders: http.Header{
453 "X-Remote-Group-3": {"one-a", "one-b"},
454 "X-Remote-Group-4": {"two-a", "two-b"},
455 },
456 },
457
458 "escaped extra keys": {
459 nameHeaders: []string{"X-Remote-User"},
460 uidHeaders: []string{"X-Remote-Uid"},
461 groupHeaders: []string{"X-Remote-Group"},
462 extraPrefixHeaders: []string{"X-Remote-Extra-"},
463 requestHeaders: http.Header{
464 "X-Remote-User": {"Bob"},
465 "X-Remote-Uid": {"bobs-uid"},
466 "X-Remote-Group": {"one-a", "one-b"},
467 "X-Remote-Extra-Alpha": {"alphabetical"},
468 "X-Remote-Extra-Alph4num3r1c": {"alphanumeric"},
469 "X-Remote-Extra-Percent%20encoded": {"percent encoded"},
470 "X-Remote-Extra-Almost%zzpercent%xxencoded": {"not quite percent encoded"},
471 "X-Remote-Extra-Example.com%2fpercent%2520encoded": {"url with double percent encoding"},
472 "X-Remote-Extra-Example.com%2F%E4%BB%8A%E6%97%A5%E3%81%AF": {"url with unicode"},
473 "X-Remote-Extra-Abc123!#$+.-_*\\^`~|'": {"header key legal characters"},
474 },
475 },
476 }
477
478 for k, testcase := range testcases {
479 t.Run(k, func(t *testing.T) {
480 var handlerCalls, authnCalls int
481 auth := WithAuthentication(
482 http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) {
483 handlerCalls++
484 }),
485 authenticator.RequestFunc(func(req *http.Request) (*authenticator.Response, bool, error) {
486 authnCalls++
487 return &authenticator.Response{User: &user.DefaultInfo{Name: "panda"}}, true, nil
488 }),
489 http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
490 t.Errorf("unexpected call to handler")
491 }),
492 nil,
493 &authenticatorfactory.RequestHeaderConfig{
494 UsernameHeaders: headerrequest.StaticStringSlice(testcase.nameHeaders),
495 UIDHeaders: headerrequest.StaticStringSlice(testcase.uidHeaders),
496 GroupHeaders: headerrequest.StaticStringSlice(testcase.groupHeaders),
497 ExtraHeaderPrefixes: headerrequest.StaticStringSlice(testcase.extraPrefixHeaders),
498 },
499 )
500
501 auth.ServeHTTP(httptest.NewRecorder(), &http.Request{Header: testcase.requestHeaders})
502
503 if handlerCalls != 1 || authnCalls != 1 {
504 t.Errorf("unexpected calls: handlerCalls=%d, authnCalls=%d", handlerCalls, authnCalls)
505 }
506
507 want := testcase.finalHeaders
508 if want == nil && testcase.requestHeaders != nil {
509 want = http.Header{}
510 }
511 if diff := cmp.Diff(want, testcase.requestHeaders); len(diff) > 0 {
512 t.Errorf("unexpected final headers (-want +got):\n%s", diff)
513 }
514 })
515 }
516 }
517
518 func TestUnauthenticatedHTTP2ClientConnectionClose(t *testing.T) {
519 s := httptest.NewUnstartedServer(WithAuthentication(
520 http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) }),
521 authenticator.RequestFunc(func(r *http.Request) (*authenticator.Response, bool, error) {
522 switch r.Header.Get("Authorization") {
523 case "known":
524 return &authenticator.Response{User: &user.DefaultInfo{Name: "panda"}}, true, nil
525 case "error":
526 return nil, false, errors.New("authn err")
527 case "anonymous":
528 return anonymous.NewAuthenticator(nil).AuthenticateRequest(r)
529 case "anonymous_group":
530 return &authenticator.Response{User: &user.DefaultInfo{Groups: []string{user.AllUnauthenticated}}}, true, nil
531 default:
532 return nil, false, nil
533 }
534 }),
535 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
536 r = r.WithContext(genericapirequest.WithRequestInfo(r.Context(), &genericapirequest.RequestInfo{}))
537 Unauthorized(scheme.Codecs).ServeHTTP(w, r)
538 }),
539 nil,
540 nil,
541 ))
542
543 http2Options := &http2.Server{}
544
545 if err := http2.ConfigureServer(s.Config, http2Options); err != nil {
546 t.Fatal(err)
547 }
548
549 s.TLS = s.Config.TLSConfig
550
551 s.StartTLS()
552 t.Cleanup(s.Close)
553
554 const reqs = 4
555
556 cases := []struct {
557 name string
558 authorizationHeader string
559 skipHTTP2DOSMitigation bool
560 expectConnections uint64
561 }{
562 {
563 name: "known",
564 authorizationHeader: "known",
565 skipHTTP2DOSMitigation: false,
566 expectConnections: 1,
567 },
568 {
569 name: "error",
570 authorizationHeader: "error",
571 skipHTTP2DOSMitigation: false,
572 expectConnections: reqs,
573 },
574 {
575 name: "anonymous",
576 authorizationHeader: "anonymous",
577 skipHTTP2DOSMitigation: false,
578 expectConnections: reqs,
579 },
580 {
581 name: "anonymous_group",
582 authorizationHeader: "anonymous_group",
583 skipHTTP2DOSMitigation: false,
584 expectConnections: reqs,
585 },
586 {
587 name: "other",
588 authorizationHeader: "other",
589 skipHTTP2DOSMitigation: false,
590 expectConnections: reqs,
591 },
592
593 {
594 name: "known skip=true",
595 authorizationHeader: "known",
596 skipHTTP2DOSMitigation: true,
597 expectConnections: 1,
598 },
599 {
600 name: "error skip=true",
601 authorizationHeader: "error",
602 skipHTTP2DOSMitigation: true,
603 expectConnections: 1,
604 },
605 {
606 name: "anonymous skip=true",
607 authorizationHeader: "anonymous",
608 skipHTTP2DOSMitigation: true,
609 expectConnections: 1,
610 },
611 {
612 name: "anonymous_group skip=true",
613 authorizationHeader: "anonymous_group",
614 skipHTTP2DOSMitigation: true,
615 expectConnections: 1,
616 },
617 {
618 name: "other skip=true",
619 authorizationHeader: "other",
620 skipHTTP2DOSMitigation: true,
621 expectConnections: 1,
622 },
623 }
624
625 rootCAs := x509.NewCertPool()
626 rootCAs.AddCert(s.Certificate())
627
628 for _, tc := range cases {
629 t.Run(tc.name, func(t *testing.T) {
630 f := func(t *testing.T, nextProto string, expectConnections uint64) {
631 featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.UnauthenticatedHTTP2DOSMitigation, !tc.skipHTTP2DOSMitigation)
632
633 var localAddrs atomic.Uint64 // indicates how many TCP connection set up
634
635 tlsConfig := &tls.Config{
636 RootCAs: rootCAs,
637 NextProtos: []string{nextProto},
638 }
639
640 dailer := tls.Dialer{
641 Config: tlsConfig,
642 }
643
644 tr := &http.Transport{
645 TLSHandshakeTimeout: 10 * time.Second,
646 TLSClientConfig: tlsConfig,
647 DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
648 conn, err := dailer.DialContext(ctx, network, addr)
649 if err != nil {
650 return nil, err
651 }
652
653 localAddrs.Add(1)
654
655 return conn, nil
656 },
657 }
658
659 tr.MaxIdleConnsPerHost = 1 // allow http1 to have keep alive connections open
660 if nextProto == http2.NextProtoTLS {
661 // Disable connection pooling to avoid additional connections
662 // that cause the test to flake
663 tr.MaxIdleConnsPerHost = -1
664 if err := http2.ConfigureTransport(tr); err != nil {
665 t.Fatal(err)
666 }
667 }
668
669 client := &http.Client{
670 Transport: tr,
671 }
672
673 for i := 0; i < reqs; i++ {
674 req, err := http.NewRequest(http.MethodGet, s.URL, nil)
675 if err != nil {
676 t.Fatal(err)
677 }
678 if len(tc.authorizationHeader) > 0 {
679 req.Header.Set("Authorization", tc.authorizationHeader)
680 }
681
682 resp, err := client.Do(req)
683 if err != nil {
684 t.Fatal(err)
685 }
686 _, _ = io.Copy(io.Discard, resp.Body)
687 _ = resp.Body.Close()
688 }
689
690 if expectConnections != localAddrs.Load() {
691 t.Fatalf("expect TCP connection: %d, actual: %d", expectConnections, localAddrs.Load())
692 }
693 }
694
695 t.Run(http2.NextProtoTLS, func(t *testing.T) {
696 f(t, http2.NextProtoTLS, tc.expectConnections)
697 })
698
699 // http1 connection reuse occasionally flakes on CI, skipping for now
700 // t.Run("http/1.1", func(t *testing.T) {
701 // f(t, "http/1.1", 1)
702 // })
703 })
704 }
705 }