Debian Codegraph @

transport/round_trippers_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 transport
18
19 import (
20 "bytes"
21 "context"
22 "flag"
23 "fmt"
24 "net/http"
25 "net/url"
26 "reflect"
27 "regexp"
28 "strings"
29 "testing"
30
31 "github.com/go-logr/logr/funcr"
32
33 "k8s.io/klog/v2"
34 )
35
36 type testRoundTripper struct {
37 Request *http.Request
38 Response *http.Response
39 Err error
40 }
41
42 func (rt *testRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
43 rt.Request = req
44 return rt.Response, rt.Err
45 }
46
47 func TestMaskValue(t *testing.T) {
48 tcs := []struct {
49 key string
50 value string
51 expected string
52 }{
53 {
54 key: "Authorization",
55 value: "Basic YWxhZGRpbjpvcGVuc2VzYW1l",
56 expected: "Basic <masked>",
57 },
58 {
59 key: "Authorization",
60 value: "basic",
61 expected: "basic",
62 },
63 {
64 key: "Authorization",
65 value: "Basic",
66 expected: "Basic",
67 },
68 {
69 key: "Authorization",
70 value: "Bearer cn389ncoiwuencr",
71 expected: "Bearer <masked>",
72 },
73 {
74 key: "Authorization",
75 value: "Bearer",
76 expected: "Bearer",
77 },
78 {
79 key: "Authorization",
80 value: "bearer",
81 expected: "bearer",
82 },
83 {
84 key: "Authorization",
85 value: "bearer ",
86 expected: "bearer",
87 },
88 {
89 key: "Authorization",
90 value: "Negotiate cn389ncoiwuencr",
91 expected: "Negotiate <masked>",
92 },
93 {
94 key: "ABC",
95 value: "Negotiate cn389ncoiwuencr",
96 expected: "Negotiate cn389ncoiwuencr",
97 },
98 {
99 key: "Authorization",
100 value: "Negotiate",
101 expected: "Negotiate",
102 },
103 {
104 key: "Authorization",
105 value: "Negotiate ",
106 expected: "Negotiate",
107 },
108 {
109 key: "Authorization",
110 value: "negotiate",
111 expected: "negotiate",
112 },
113 {
114 key: "Authorization",
115 value: "abc cn389ncoiwuencr",
116 expected: "<masked>",
117 },
118 {
119 key: "Authorization",
120 value: "",
121 expected: "",
122 },
123 }
124 for _, tc := range tcs {
125 maskedValue := maskValue(tc.key, tc.value)
126 if tc.expected != maskedValue {
127 t.Errorf("unexpected value %s, given %s.", maskedValue, tc.value)
128 }
129 }
130 }
131
132 func TestBearerAuthRoundTripper(t *testing.T) {
133 rt := &testRoundTripper{}
134 req := &http.Request{}
135 NewBearerAuthRoundTripper("test", rt).RoundTrip(req)
136 if rt.Request == nil {
137 t.Fatalf("unexpected nil request: %v", rt)
138 }
139 if rt.Request == req {
140 t.Fatalf("round tripper should have copied request object: %#v", rt.Request)
141 }
142 if rt.Request.Header.Get("Authorization") != "Bearer test" {
143 t.Errorf("unexpected authorization header: %#v", rt.Request)
144 }
145 }
146
147 func TestBasicAuthRoundTripper(t *testing.T) {
148 for n, tc := range map[string]struct {
149 user string
150 pass string
151 }{
152 "basic": {user: "user", pass: "pass"},
153 "no pass": {user: "user"},
154 } {
155 rt := &testRoundTripper{}
156 req := &http.Request{}
157 NewBasicAuthRoundTripper(tc.user, tc.pass, rt).RoundTrip(req)
158 if rt.Request == nil {
159 t.Fatalf("%s: unexpected nil request: %v", n, rt)
160 }
161 if rt.Request == req {
162 t.Fatalf("%s: round tripper should have copied request object: %#v", n, rt.Request)
163 }
164 if user, pass, found := rt.Request.BasicAuth(); !found || user != tc.user || pass != tc.pass {
165 t.Errorf("%s: unexpected authorization header: %#v", n, rt.Request)
166 }
167 }
168 }
169
170 func TestUserAgentRoundTripper(t *testing.T) {
171 rt := &testRoundTripper{}
172 req := &http.Request{
173 Header: make(http.Header),
174 }
175 req.Header.Set("User-Agent", "other")
176 NewUserAgentRoundTripper("test", rt).RoundTrip(req)
177 if rt.Request == nil {
178 t.Fatalf("unexpected nil request: %v", rt)
179 }
180 if rt.Request != req {
181 t.Fatalf("round tripper should not have copied request object: %#v", rt.Request)
182 }
183 if rt.Request.Header.Get("User-Agent") != "other" {
184 t.Errorf("unexpected user agent header: %#v", rt.Request)
185 }
186
187 req = &http.Request{}
188 NewUserAgentRoundTripper("test", rt).RoundTrip(req)
189 if rt.Request == nil {
190 t.Fatalf("unexpected nil request: %v", rt)
191 }
192 if rt.Request == req {
193 t.Fatalf("round tripper should have copied request object: %#v", rt.Request)
194 }
195 if rt.Request.Header.Get("User-Agent") != "test" {
196 t.Errorf("unexpected user agent header: %#v", rt.Request)
197 }
198 }
199
200 func TestImpersonationRoundTripper(t *testing.T) {
201 tcs := []struct {
202 name string
203 impersonationConfig ImpersonationConfig
204 expected map[string][]string
205 }{
206 {
207 name: "all",
208 impersonationConfig: ImpersonationConfig{
209 UserName: "user",
210 UID: "uid-a",
211 Groups: []string{"one", "two"},
212 Extra: map[string][]string{
213 "first": {"A", "a"},
214 "second": {"B", "b"},
215 },
216 },
217 expected: map[string][]string{
218 ImpersonateUserHeader: {"user"},
219 ImpersonateUIDHeader: {"uid-a"},
220 ImpersonateGroupHeader: {"one", "two"},
221 ImpersonateUserExtraHeaderPrefix + "First": {"A", "a"},
222 ImpersonateUserExtraHeaderPrefix + "Second": {"B", "b"},
223 },
224 },
225 {
226 name: "username, groups and extra",
227 impersonationConfig: ImpersonationConfig{
228 UserName: "user",
229 Groups: []string{"one", "two"},
230 Extra: map[string][]string{
231 "first": {"A", "a"},
232 "second": {"B", "b"},
233 },
234 },
235 expected: map[string][]string{
236 ImpersonateUserHeader: {"user"},
237 ImpersonateGroupHeader: {"one", "two"},
238 ImpersonateUserExtraHeaderPrefix + "First": {"A", "a"},
239 ImpersonateUserExtraHeaderPrefix + "Second": {"B", "b"},
240 },
241 },
242 {
243 name: "username and uid",
244 impersonationConfig: ImpersonationConfig{
245 UserName: "user",
246 UID: "uid-a",
247 },
248 expected: map[string][]string{
249 ImpersonateUserHeader: {"user"},
250 ImpersonateUIDHeader: {"uid-a"},
251 },
252 },
253 {
254 name: "escape handling",
255 impersonationConfig: ImpersonationConfig{
256 UserName: "user",
257 Extra: map[string][]string{
258 "test.example.com/thing.thing": {"A", "a"},
259 },
260 },
261 expected: map[string][]string{
262 ImpersonateUserHeader: {"user"},
263 ImpersonateUserExtraHeaderPrefix + `Test.example.com%2fthing.thing`: {"A", "a"},
264 },
265 },
266 {
267 name: "double escape handling",
268 impersonationConfig: ImpersonationConfig{
269 UserName: "user",
270 Extra: map[string][]string{
271 "test.example.com/thing.thing%20another.thing": {"A", "a"},
272 },
273 },
274 expected: map[string][]string{
275 ImpersonateUserHeader: {"user"},
276 ImpersonateUserExtraHeaderPrefix + `Test.example.com%2fthing.thing%2520another.thing`: {"A", "a"},
277 },
278 },
279 }
280
281 for _, tc := range tcs {
282 rt := &testRoundTripper{}
283 req := &http.Request{
284 Header: make(http.Header),
285 }
286 NewImpersonatingRoundTripper(tc.impersonationConfig, rt).RoundTrip(req)
287
288 for k, v := range rt.Request.Header {
289 expected, ok := tc.expected[k]
290 if !ok {
291 t.Errorf("%v missing %v=%v", tc.name, k, v)
292 continue
293 }
294 if !reflect.DeepEqual(expected, v) {
295 t.Errorf("%v expected %v: %v, got %v", tc.name, k, expected, v)
296 }
297 }
298 for k, v := range tc.expected {
299 expected, ok := rt.Request.Header[k]
300 if !ok {
301 t.Errorf("%v missing %v=%v", tc.name, k, v)
302 continue
303 }
304 if !reflect.DeepEqual(expected, v) {
305 t.Errorf("%v expected %v: %v, got %v", tc.name, k, expected, v)
306 }
307 }
308 }
309 }
310
311 func TestAuthProxyRoundTripper(t *testing.T) {
312 for n, tc := range map[string]struct {
313 username string
314 uid string
315 groups []string
316 extra map[string][]string
317 expectedExtra map[string][]string
318 }{
319 "allfields": {
320 username: "user",
321 uid: "7db46926-e803-4337-9a29-f9c1fab7d34a",
322 groups: []string{"groupA", "groupB"},
323 extra: map[string][]string{
324 "one": {"alpha", "bravo"},
325 "two": {"charlie", "delta"},
326 },
327 expectedExtra: map[string][]string{
328 "one": {"alpha", "bravo"},
329 "two": {"charlie", "delta"},
330 },
331 },
332 "escaped extra": {
333 username: "user",
334 uid: "7db46926-e803-4337-9a29-f9c1fab7d34a",
335 groups: []string{"groupA", "groupB"},
336 extra: map[string][]string{
337 "one": {"alpha", "bravo"},
338 "example.com/two": {"charlie", "delta"},
339 },
340 expectedExtra: map[string][]string{
341 "one": {"alpha", "bravo"},
342 "example.com%2ftwo": {"charlie", "delta"},
343 },
344 },
345 "double escaped extra": {
346 username: "user",
347 uid: "7db46926-e803-4337-9a29-f9c1fab7d34a",
348 groups: []string{"groupA", "groupB"},
349 extra: map[string][]string{
350 "one": {"alpha", "bravo"},
351 "example.com/two%20three": {"charlie", "delta"},
352 },
353 expectedExtra: map[string][]string{
354 "one": {"alpha", "bravo"},
355 "example.com%2ftwo%2520three": {"charlie", "delta"},
356 },
357 },
358 } {
359 rt := &testRoundTripper{}
360 req := &http.Request{}
361 _, _ = NewAuthProxyRoundTripper(tc.username, tc.uid, tc.groups, tc.extra, rt).RoundTrip(req)
362 if rt.Request == nil {
363 t.Errorf("%s: unexpected nil request: %v", n, rt)
364 continue
365 }
366 if rt.Request == req {
367 t.Errorf("%s: round tripper should have copied request object: %#v", n, rt.Request)
368 continue
369 }
370
371 actualUsernames, ok := rt.Request.Header["X-Remote-User"]
372 if !ok {
373 t.Errorf("%s missing value", n)
374 continue
375 }
376 if e, a := []string{tc.username}, actualUsernames; !reflect.DeepEqual(e, a) {
377 t.Errorf("%s expected %v, got %v", n, e, a)
378 continue
379 }
380 actualUID, ok := rt.Request.Header["X-Remote-Uid"]
381 if !ok {
382 t.Errorf("%s missing value", n)
383 continue
384 }
385 if e, a := []string{tc.uid}, actualUID; !reflect.DeepEqual(e, a) {
386 t.Errorf("%s expected %v, got %v", n, e, a)
387 continue
388 }
389 actualGroups, ok := rt.Request.Header["X-Remote-Group"]
390 if !ok {
391 t.Errorf("%s missing value", n)
392 continue
393 }
394 if e, a := tc.groups, actualGroups; !reflect.DeepEqual(e, a) {
395 t.Errorf("%s expected %v, got %v", n, e, a)
396 continue
397 }
398
399 actualExtra := map[string][]string{}
400 for key, values := range rt.Request.Header {
401 if strings.HasPrefix(strings.ToLower(key), strings.ToLower("X-Remote-Extra-")) {
402 extraKey := strings.ToLower(key[len("X-Remote-Extra-"):])
403 actualExtra[extraKey] = append(actualExtra[key], values...)
404 }
405 }
406 if e, a := tc.expectedExtra, actualExtra; !reflect.DeepEqual(e, a) {
407 t.Errorf("%s expected %v, got %v", n, e, a)
408 continue
409 }
410 }
411 }
412
413 // TestHeaderEscapeRoundTrip tests to see if foo == url.PathUnescape(headerEscape(foo))
414 // This behavior is important for client -> API server transmission of extra values.
415 func TestHeaderEscapeRoundTrip(t *testing.T) {
416 t.Parallel()
417 testCases := []struct {
418 name string
419 key string
420 }{
421 {
422 name: "alpha",
423 key: "alphabetical",
424 },
425 {
426 name: "alphanumeric",
427 key: "alph4num3r1c",
428 },
429 {
430 name: "percent encoded",
431 key: "percent%20encoded",
432 },
433 {
434 name: "almost percent encoded",
435 key: "almost%zzpercent%xxencoded",
436 },
437 {
438 name: "illegal char & percent encoding",
439 key: "example.com/percent%20encoded",
440 },
441 {
442 name: "weird unicode stuff",
443 key: "example.com/ᛒᚥᛏᛖᚥᚢとロビン",
444 },
445 {
446 name: "header legal chars",
447 key: "abc123!#$+.-_*\\^`~|'",
448 },
449 {
450 name: "legal path, illegal header",
451 key: "@=:",
452 },
453 }
454 for _, tc := range testCases {
455 t.Run(tc.name, func(t *testing.T) {
456 escaped := headerKeyEscape(tc.key)
457 unescaped, err := url.PathUnescape(escaped)
458 if err != nil {
459 t.Fatalf("url.PathUnescape(%q) returned error: %v", escaped, err)
460 }
461 if tc.key != unescaped {
462 t.Errorf("url.PathUnescape(headerKeyEscape(%q)) returned %q, wanted %q", tc.key, unescaped, tc.key)
463 }
464 })
465 }
466 }
467
468 //nolint:logcheck // Intentionally tests with global logging.
469 func TestDebuggingRoundTripper(t *testing.T) {
470 rawURL := "https://127.0.0.1:12345/api/v1/pods?limit=500"
471 parsedURL, err := url.Parse(rawURL)
472 if err != nil {
473 t.Fatalf("url.Parse(%q) returned error: %v", rawURL, err)
474 }
475 method := http.MethodGet
476 header := map[string][]string{
477 "Authorization": {"bearer secretauthtoken"},
478 "X-Test-Request": {"test"},
479 }
480 reqHeaderText := `headers=<
481 Authorization: bearer <masked>
482 X-Test-Request: test
483 >`
484 // Both can be written by funcr.
485 reqHeaderJSON := `"headers":{"Authorization":["bearer <masked>"],"X-Test-Request":["test"]}`
486 reqHeaderJSONReversed := `"headers":{"X-Test-Request":["test"],"Authorization":["bearer <masked>"]}`
487
488 res := &http.Response{
489 Status: "OK",
490 StatusCode: http.StatusOK,
491 Header: map[string][]string{
492 "X-Test-Response": {"a", "b"},
493 },
494 }
495
496 resHeaderText := `headers=<
497 X-Test-Response: a
498 X-Test-Response: b
499 >`
500 resHeaderJSON := `"headers":{"X-Test-Response":["a","b"]}`
501
502 tcs := []struct {
503 levels []DebugLevel
504 v int
505 expectedTextLines []string
506 expectedJSONLines []string
507 }{
508 {
509 levels: []DebugLevel{DebugJustURL},
510 expectedTextLines: []string{fmt.Sprintf(`"Request" verb=%q url=%q`, method, rawURL)},
511 expectedJSONLines: []string{fmt.Sprintf(`"msg":"Request","verb":%q,"url":%q`, method, rawURL)},
512 },
513 {
514 levels: []DebugLevel{DebugRequestHeaders},
515 expectedTextLines: []string{`"Request" ` + reqHeaderText},
516 expectedJSONLines: []string{`"msg":"Request",` + reqHeaderJSON},
517 },
518 {
519 levels: []DebugLevel{DebugResponseHeaders},
520 expectedTextLines: []string{`"Response" ` + resHeaderText},
521 expectedJSONLines: []string{`"msg":"Response",` + resHeaderJSON},
522 },
523 {
524 levels: []DebugLevel{DebugURLTiming},
525 expectedTextLines: []string{fmt.Sprintf(`"Response" verb=%q url=%q status=%q`, method, rawURL, res.Status)},
526 expectedJSONLines: []string{fmt.Sprintf(`"msg":"Response","verb":%q,"url":%q,"status":%q`, method, rawURL, res.Status)},
527 },
528 {
529 levels: []DebugLevel{DebugResponseStatus},
530 expectedTextLines: []string{fmt.Sprintf(`"Response" status=%q`, res.Status)},
531 expectedJSONLines: []string{fmt.Sprintf(`"msg":"Response","status":%q`, res.Status)},
532 },
533 {
534 levels: []DebugLevel{DebugCurlCommand},
535 expectedTextLines: []string{`curlCommand=<
536 curl -v -X`},
537 expectedJSONLines: []string{`"curlCommand":"curl -v -X`},
538 },
539 {
540 levels: []DebugLevel{DebugURLTiming, DebugResponseStatus},
541 expectedTextLines: []string{fmt.Sprintf(`"Response" verb=%q url=%q status=%q milliseconds=`, method, rawURL, res.Status)},
542 expectedJSONLines: []string{fmt.Sprintf(`"msg":"Response","verb":%q,"url":%q,"status":%q,"milliseconds":`, method, rawURL, res.Status)},
543 },
544 {
545 levels: []DebugLevel{DebugByContext},
546 v: 5,
547 },
548 {
549 levels: []DebugLevel{DebugByContext, DebugURLTiming},
550 v: 5,
551 expectedTextLines: []string{
552 fmt.Sprintf(`"Response" verb=%q url=%q status=%q milliseconds=`, method, rawURL, res.Status),
553 },
554 expectedJSONLines: []string{
555 fmt.Sprintf(`"msg":"Response","verb":%q,"url":%q,"status":%q,"milliseconds":`, method, rawURL, res.Status),
556 },
557 },
558 {
559 levels: []DebugLevel{DebugByContext},
560 v: 6,
561 expectedTextLines: []string{
562 fmt.Sprintf(`"Response" verb=%q url=%q status=%q milliseconds=`, method, rawURL, res.Status),
563 },
564 expectedJSONLines: []string{
565 fmt.Sprintf(`"msg":"Response","verb":%q,"url":%q,"status":%q,"milliseconds":`, method, rawURL, res.Status),
566 },
567 },
568 {
569 levels: []DebugLevel{DebugByContext},
570 v: 7,
571 expectedTextLines: []string{
572 fmt.Sprintf(`"Request" verb=%q url=%q %s
573 `, method, rawURL, reqHeaderText),
574 fmt.Sprintf(`"Response" status=%q milliseconds=`, res.Status),
575 },
576 expectedJSONLines: []string{
577 fmt.Sprintf(`"msg":"Request","verb":%q,"url":%q,%s`, method, rawURL, reqHeaderJSON),
578 fmt.Sprintf(`"msg":"Response","status":%q,"milliseconds":`, res.Status),
579 },
580 },
581 {
582 levels: []DebugLevel{DebugByContext},
583 v: 8,
584 expectedTextLines: []string{
585 fmt.Sprintf(`"Request" verb=%q url=%q %s
586 `, method, rawURL, reqHeaderText),
587 fmt.Sprintf(`"Response" status=%q %s milliseconds=`, res.Status, resHeaderText),
588 },
589 expectedJSONLines: []string{
590 fmt.Sprintf(`"msg":"Request","verb":%q,"url":%q,%s`, method, rawURL, reqHeaderJSON),
591 fmt.Sprintf(`"msg":"Response","status":%q,%s,"milliseconds":`, res.Status, resHeaderJSON),
592 },
593 },
594 {
595 levels: []DebugLevel{DebugByContext},
596 v: 9,
597 expectedTextLines: []string{
598 fmt.Sprintf(`"Request" curlCommand=<
599 curl -v -X%s`, method),
600 fmt.Sprintf(`"Response" verb=%q url=%q status=%q %s milliseconds=`, method, rawURL, res.Status, resHeaderText),
601 },
602 expectedJSONLines: []string{
603 fmt.Sprintf(`"msg":"Request","curlCommand":"curl -v -X%s`, method),
604 fmt.Sprintf(`"msg":"Response","verb":%q,"url":%q,"status":%q,%s,"milliseconds":`, method, rawURL, res.Status, resHeaderJSON),
605 },
606 },
607 }
608
609 for i, tc := range tcs {
610 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
611 for _, format := range []string{"text", "JSON"} {
612 t.Run(format, func(t *testing.T) {
613 // hijack the klog output
614 state := klog.CaptureState()
615 tmpWriteBuffer := bytes.NewBuffer(nil)
616 klog.SetOutput(tmpWriteBuffer)
617 klog.LogToStderr(false)
618 var fs flag.FlagSet
619 klog.InitFlags(&fs)
620 if err := fs.Set("one_output", "true"); err != nil {
621 t.Errorf("unexpected error setting -one_output: %v", err)
622 }
623 if err := fs.Set("v", fmt.Sprintf("%d", tc.v)); err != nil {
624 t.Errorf("unexpected error setting -v: %v", err)
625 }
626
627 expectOutput := tc.expectedTextLines
628 var req *http.Request
629 if format == "JSON" {
630 // Logger will be picked up through the context.
631 logger := funcr.NewJSON(func(obj string) {
632 _, _ = tmpWriteBuffer.Write([]byte(obj))
633 _, _ = tmpWriteBuffer.Write([]byte("\n"))
634 }, funcr.Options{Verbosity: tc.v})
635 ctx := klog.NewContext(context.Background(), logger)
636 expectOutput = tc.expectedJSONLines
637 r, err := http.NewRequestWithContext(ctx, method, rawURL, nil)
638 if err != nil {
639 t.Fatalf("unexpected error constructing the HTTP request: %v", err)
640 }
641 req = r
642 } else {
643 // Intentionally no context, as before.
644 req = &http.Request{
645 Method: method,
646 URL: parsedURL,
647 }
648 }
649 req.Header = header
650
651 // execute the round tripper
652 rt := &testRoundTripper{
653 Response: res,
654 }
655 if len(tc.levels) == 1 && tc.levels[0] == DebugByContext {
656 DebugWrappers(rt).RoundTrip(req)
657 } else {
658 NewDebuggingRoundTripper(rt, tc.levels...).RoundTrip(req)
659 }
660
661 // call Flush to ensure the text isn't still buffered
662 klog.Flush()
663
664 // check if klog's output contains the expected lines
665 actual := tmpWriteBuffer.String()
666
667 // funcr writes a map in non-deterministic order.
668 // Fix that up before comparison.
669 actual = strings.ReplaceAll(actual, reqHeaderJSONReversed, reqHeaderJSON)
670
671 for _, expected := range expectOutput {
672 if !strings.Contains(actual, expected) {
673 t.Errorf("verbosity %d: expected this substring:\n%s\n\ngot:\n%s", tc.v, expected, actual)
674 }
675 }
676 // These test cases describe all expected lines. Split the log output
677 // into log entries and compare their number.
678 entries := regexp.MustCompile(`(?m)^[I{]`).FindAllStringIndex(actual, -1)
679 if tc.v > 0 && len(entries) != len(expectOutput) {
680 t.Errorf("expected %d output lines, got %d:\n%s", len(expectOutput), len(entries), actual)
681 }
682
683 state.Restore()
684 })
685 }
686 })
687 }
688 }