Debian Codegraph @

transport/round_trippers.go

raw
1 /*
2 Copyright 2015 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 "crypto/tls"
21 "fmt"
22 "net/http"
23 "net/http/httptrace"
24 "sort"
25 "strings"
26 "sync"
27 "time"
28
29 "github.com/go-logr/logr"
30 "golang.org/x/oauth2"
31
32 utilnet "k8s.io/apimachinery/pkg/util/net"
33 "k8s.io/klog/v2"
34 )
35
36 // HTTPWrappersForConfig wraps a round tripper with any relevant layered
37 // behavior from the config. Exposed to allow more clients that need HTTP-like
38 // behavior but then must hijack the underlying connection (like WebSocket or
39 // HTTP2 clients). Pure HTTP clients should use the RoundTripper returned from
40 // New.
41 func HTTPWrappersForConfig(config *Config, rt http.RoundTripper) (http.RoundTripper, error) {
42 if config.WrapTransport != nil {
43 rt = config.WrapTransport(rt)
44 }
45
46 rt = DebugWrappers(rt)
47
48 // Set authentication wrappers
49 switch {
50 case config.HasBasicAuth() && config.HasTokenAuth():
51 return nil, fmt.Errorf("username/password or bearer token may be set, but not both")
52 case config.HasTokenAuth():
53 var err error
54 rt, err = NewBearerAuthWithRefreshRoundTripper(config.BearerToken, config.BearerTokenFile, rt)
55 if err != nil {
56 return nil, err
57 }
58 case config.HasBasicAuth():
59 rt = NewBasicAuthRoundTripper(config.Username, config.Password, rt)
60 }
61 if len(config.UserAgent) > 0 {
62 rt = NewUserAgentRoundTripper(config.UserAgent, rt)
63 }
64 if len(config.Impersonate.UserName) > 0 ||
65 len(config.Impersonate.UID) > 0 ||
66 len(config.Impersonate.Groups) > 0 ||
67 len(config.Impersonate.Extra) > 0 {
68 rt = NewImpersonatingRoundTripper(config.Impersonate, rt)
69 }
70 return rt, nil
71 }
72
73 // DebugWrappers potentially wraps a round tripper with a wrapper that logs
74 // based on the log level in the context of each individual request.
75 //
76 // At the moment, wrapping depends on the global log verbosity and is done
77 // if that verbosity is >= 6. This may change in the future.
78 func DebugWrappers(rt http.RoundTripper) http.RoundTripper {
79 //nolint:logcheck // The actual logging is done with a different logger, so only checking here is okay.
80 if klog.V(6).Enabled() {
81 rt = NewDebuggingRoundTripper(rt, DebugByContext)
82 }
83 return rt
84 }
85
86 type authProxyRoundTripper struct {
87 username string
88 uid string
89 groups []string
90 extra map[string][]string
91
92 rt http.RoundTripper
93 }
94
95 var _ utilnet.RoundTripperWrapper = &authProxyRoundTripper{}
96
97 // NewAuthProxyRoundTripper provides a roundtripper which will add auth proxy fields to requests for
98 // authentication terminating proxy cases
99 // assuming you pull the user from the context:
100 // username is the user.Info.GetName() of the user
101 // uid is the user.Info.GetUID() of the user
102 // groups is the user.Info.GetGroups() of the user
103 // extra is the user.Info.GetExtra() of the user
104 // extra can contain any additional information that the authenticator
105 // thought was interesting, for example authorization scopes.
106 // In order to faithfully round-trip through an impersonation flow, these keys
107 // MUST be lowercase.
108 func NewAuthProxyRoundTripper(username, uid string, groups []string, extra map[string][]string, rt http.RoundTripper) http.RoundTripper {
109 return &authProxyRoundTripper{
110 username: username,
111 uid: uid,
112 groups: groups,
113 extra: extra,
114 rt: rt,
115 }
116 }
117
118 func (rt *authProxyRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
119 req = utilnet.CloneRequest(req)
120 SetAuthProxyHeaders(req, rt.username, rt.uid, rt.groups, rt.extra)
121
122 return rt.rt.RoundTrip(req)
123 }
124
125 // SetAuthProxyHeaders stomps the auth proxy header fields. It mutates its argument.
126 func SetAuthProxyHeaders(req *http.Request, username, uid string, groups []string, extra map[string][]string) {
127 req.Header.Del("X-Remote-User")
128 req.Header.Del("X-Remote-Uid")
129 req.Header.Del("X-Remote-Group")
130 for key := range req.Header {
131 if strings.HasPrefix(strings.ToLower(key), strings.ToLower("X-Remote-Extra-")) {
132 req.Header.Del(key)
133 }
134 }
135
136 req.Header.Set("X-Remote-User", username)
137 if len(uid) > 0 {
138 req.Header.Set("X-Remote-Uid", uid)
139 }
140 for _, group := range groups {
141 req.Header.Add("X-Remote-Group", group)
142 }
143 for key, values := range extra {
144 for _, value := range values {
145 req.Header.Add("X-Remote-Extra-"+headerKeyEscape(key), value)
146 }
147 }
148 }
149
150 func (rt *authProxyRoundTripper) CancelRequest(req *http.Request) {
151 tryCancelRequest(rt.WrappedRoundTripper(), req)
152 }
153
154 func (rt *authProxyRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.rt }
155
156 type userAgentRoundTripper struct {
157 agent string
158 rt http.RoundTripper
159 }
160
161 var _ utilnet.RoundTripperWrapper = &userAgentRoundTripper{}
162
163 // NewUserAgentRoundTripper will add User-Agent header to a request unless it has already been set.
164 func NewUserAgentRoundTripper(agent string, rt http.RoundTripper) http.RoundTripper {
165 return &userAgentRoundTripper{agent, rt}
166 }
167
168 func (rt *userAgentRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
169 if len(req.Header.Get("User-Agent")) != 0 {
170 return rt.rt.RoundTrip(req)
171 }
172 req = utilnet.CloneRequest(req)
173 req.Header.Set("User-Agent", rt.agent)
174 return rt.rt.RoundTrip(req)
175 }
176
177 func (rt *userAgentRoundTripper) CancelRequest(req *http.Request) {
178 tryCancelRequest(rt.WrappedRoundTripper(), req)
179 }
180
181 func (rt *userAgentRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.rt }
182
183 type basicAuthRoundTripper struct {
184 username string
185 password string `datapolicy:"password"`
186 rt http.RoundTripper
187 }
188
189 var _ utilnet.RoundTripperWrapper = &basicAuthRoundTripper{}
190
191 // NewBasicAuthRoundTripper will apply a BASIC auth authorization header to a
192 // request unless it has already been set.
193 func NewBasicAuthRoundTripper(username, password string, rt http.RoundTripper) http.RoundTripper {
194 return &basicAuthRoundTripper{username, password, rt}
195 }
196
197 func (rt *basicAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
198 if len(req.Header.Get("Authorization")) != 0 {
199 return rt.rt.RoundTrip(req)
200 }
201 req = utilnet.CloneRequest(req)
202 req.SetBasicAuth(rt.username, rt.password)
203 return rt.rt.RoundTrip(req)
204 }
205
206 func (rt *basicAuthRoundTripper) CancelRequest(req *http.Request) {
207 tryCancelRequest(rt.WrappedRoundTripper(), req)
208 }
209
210 func (rt *basicAuthRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.rt }
211
212 // These correspond to the headers used in pkg/apis/authentication. We don't want the package dependency,
213 // but you must not change the values.
214 const (
215 // ImpersonateUserHeader is used to impersonate a particular user during an API server request
216 ImpersonateUserHeader = "Impersonate-User"
217
218 // ImpersonateUIDHeader is used to impersonate a particular UID during an API server request
219 ImpersonateUIDHeader = "Impersonate-Uid"
220
221 // ImpersonateGroupHeader is used to impersonate a particular group during an API server request.
222 // It can be repeated multiplied times for multiple groups.
223 ImpersonateGroupHeader = "Impersonate-Group"
224
225 // ImpersonateUserExtraHeaderPrefix is a prefix for a header used to impersonate an entry in the
226 // extra map[string][]string for user.Info. The key for the `extra` map is suffix.
227 // The same key can be repeated multiple times to have multiple elements in the slice under a single key.
228 // For instance:
229 // Impersonate-Extra-Foo: one
230 // Impersonate-Extra-Foo: two
231 // results in extra["Foo"] = []string{"one", "two"}
232 ImpersonateUserExtraHeaderPrefix = "Impersonate-Extra-"
233 )
234
235 type impersonatingRoundTripper struct {
236 impersonate ImpersonationConfig
237 delegate http.RoundTripper
238 }
239
240 var _ utilnet.RoundTripperWrapper = &impersonatingRoundTripper{}
241
242 // NewImpersonatingRoundTripper will add an Act-As header to a request unless it has already been set.
243 func NewImpersonatingRoundTripper(impersonate ImpersonationConfig, delegate http.RoundTripper) http.RoundTripper {
244 return &impersonatingRoundTripper{impersonate, delegate}
245 }
246
247 func (rt *impersonatingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
248 // use the user header as marker for the rest.
249 if len(req.Header.Get(ImpersonateUserHeader)) != 0 {
250 return rt.delegate.RoundTrip(req)
251 }
252 req = utilnet.CloneRequest(req)
253 req.Header.Set(ImpersonateUserHeader, rt.impersonate.UserName)
254 if rt.impersonate.UID != "" {
255 req.Header.Set(ImpersonateUIDHeader, rt.impersonate.UID)
256 }
257 for _, group := range rt.impersonate.Groups {
258 req.Header.Add(ImpersonateGroupHeader, group)
259 }
260 for k, vv := range rt.impersonate.Extra {
261 for _, v := range vv {
262 req.Header.Add(ImpersonateUserExtraHeaderPrefix+headerKeyEscape(k), v)
263 }
264 }
265
266 return rt.delegate.RoundTrip(req)
267 }
268
269 func (rt *impersonatingRoundTripper) CancelRequest(req *http.Request) {
270 tryCancelRequest(rt.WrappedRoundTripper(), req)
271 }
272
273 func (rt *impersonatingRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.delegate }
274
275 type bearerAuthRoundTripper struct {
276 bearer string
277 source oauth2.TokenSource
278 rt http.RoundTripper
279 }
280
281 var _ utilnet.RoundTripperWrapper = &bearerAuthRoundTripper{}
282
283 // NewBearerAuthRoundTripper adds the provided bearer token to a request
284 // unless the authorization header has already been set.
285 func NewBearerAuthRoundTripper(bearer string, rt http.RoundTripper) http.RoundTripper {
286 return &bearerAuthRoundTripper{bearer, nil, rt}
287 }
288
289 // NewBearerAuthWithRefreshRoundTripper adds the provided bearer token to a request
290 // unless the authorization header has already been set.
291 // If tokenFile is non-empty, it is periodically read,
292 // and the last successfully read content is used as the bearer token.
293 // If tokenFile is non-empty and bearer is empty, the tokenFile is read
294 // immediately to populate the initial bearer token.
295 func NewBearerAuthWithRefreshRoundTripper(bearer string, tokenFile string, rt http.RoundTripper) (http.RoundTripper, error) {
296 if len(tokenFile) == 0 {
297 return &bearerAuthRoundTripper{bearer, nil, rt}, nil
298 }
299 source := NewCachedFileTokenSource(tokenFile)
300 if len(bearer) == 0 {
301 token, err := source.Token()
302 if err != nil {
303 return nil, err
304 }
305 bearer = token.AccessToken
306 }
307 return &bearerAuthRoundTripper{bearer, source, rt}, nil
308 }
309
310 func (rt *bearerAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
311 if len(req.Header.Get("Authorization")) != 0 {
312 return rt.rt.RoundTrip(req)
313 }
314
315 req = utilnet.CloneRequest(req)
316 token := rt.bearer
317 if rt.source != nil {
318 if refreshedToken, err := rt.source.Token(); err == nil {
319 token = refreshedToken.AccessToken
320 }
321 }
322 req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
323 return rt.rt.RoundTrip(req)
324 }
325
326 func (rt *bearerAuthRoundTripper) CancelRequest(req *http.Request) {
327 tryCancelRequest(rt.WrappedRoundTripper(), req)
328 }
329
330 func (rt *bearerAuthRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.rt }
331
332 // requestInfo keeps track of information about a request/response combination
333 type requestInfo struct {
334 RequestHeaders http.Header `datapolicy:"token"`
335 RequestVerb string
336 RequestURL string
337
338 ResponseStatus string
339 ResponseHeaders http.Header
340 ResponseErr error
341
342 muTrace sync.Mutex // Protect trace fields
343 DNSLookup time.Duration
344 Dialing time.Duration
345 GetConnection time.Duration
346 TLSHandshake time.Duration
347 ServerProcessing time.Duration
348 ConnectionReused bool
349
350 Duration time.Duration
351 }
352
353 // newRequestInfo creates a new RequestInfo based on an http request
354 func newRequestInfo(req *http.Request) *requestInfo {
355 return &requestInfo{
356 RequestURL: req.URL.String(),
357 RequestVerb: req.Method,
358 RequestHeaders: req.Header,
359 }
360 }
361
362 // complete adds information about the response to the requestInfo
363 func (r *requestInfo) complete(response *http.Response, err error) {
364 if err != nil {
365 r.ResponseErr = err
366 return
367 }
368 r.ResponseStatus = response.Status
369 r.ResponseHeaders = response.Header
370 }
371
372 // toCurl returns a string that can be run as a command in a terminal (minus the body)
373 func (r *requestInfo) toCurl() string {
374 headers := ""
375 for key, values := range r.RequestHeaders {
376 for _, value := range values {
377 value = maskValue(key, value)
378 headers += fmt.Sprintf(` -H %q`, fmt.Sprintf("%s: %s", key, value))
379 }
380 }
381
382 // Newline at the end makes this look better in the text log output (the
383 // only usage of this method) because it becomes a multi-line string with
384 // no quoting.
385 return fmt.Sprintf("curl -v -X%s %s '%s'\n", r.RequestVerb, headers, r.RequestURL)
386 }
387
388 // debuggingRoundTripper will display information about the requests passing
389 // through it based on what is configured
390 type debuggingRoundTripper struct {
391 delegatedRoundTripper http.RoundTripper
392 levels int
393 }
394
395 var _ utilnet.RoundTripperWrapper = &debuggingRoundTripper{}
396
397 // DebugLevel is used to enable debugging of certain
398 // HTTP requests and responses fields via the debuggingRoundTripper.
399 type DebugLevel int
400
401 const (
402 // DebugJustURL will add to the debug output HTTP requests method and url.
403 DebugJustURL DebugLevel = iota
404 // DebugURLTiming will add to the debug output the duration of HTTP requests.
405 DebugURLTiming
406 // DebugCurlCommand will add to the debug output the curl command equivalent to the
407 // HTTP request.
408 DebugCurlCommand
409 // DebugRequestHeaders will add to the debug output the HTTP requests headers.
410 DebugRequestHeaders
411 // DebugResponseStatus will add to the debug output the HTTP response status.
412 DebugResponseStatus
413 // DebugResponseHeaders will add to the debug output the HTTP response headers.
414 DebugResponseHeaders
415 // DebugDetailedTiming will add to the debug output the duration of the HTTP requests events.
416 DebugDetailedTiming
417 // DebugByContext will add any of the above depending on the verbosity of the per-request logger obtained from the requests context.
418 //
419 // Can be combined in NewDebuggingRoundTripper with some of the other options, in which case the
420 // debug roundtripper will always log what is requested there plus the information that gets
421 // enabled by the context's log verbosity.
422 DebugByContext
423 )
424
425 // Different log levels include different sets of information.
426 //
427 // Not exported because the exact content of log messages is not part
428 // of of the package API.
429 const (
430 levelsV6 = (1 << DebugURLTiming)
431 // Logging *less* information for the response at level 7 compared to 6 replicates prior behavior:
432 // https://github.com/kubernetes/kubernetes/blob/2b472fe4690c83a2b343995f88050b2a3e9ff0fa/staging/src/k8s.io/client-go/transport/round_trippers.go#L79
433 // Presumably that was done because verb and URL are already in the request log entry.
434 levelsV7 = (1 << DebugJustURL) | (1 << DebugRequestHeaders) | (1 << DebugResponseStatus)
435 levelsV8 = (1 << DebugJustURL) | (1 << DebugRequestHeaders) | (1 << DebugResponseStatus) | (1 << DebugResponseHeaders)
436 levelsV9 = (1 << DebugCurlCommand) | (1 << DebugURLTiming) | (1 << DebugDetailedTiming) | (1 << DebugResponseHeaders)
437 )
438
439 // NewDebuggingRoundTripper allows to display in the logs output debug information
440 // on the API requests performed by the client.
441 func NewDebuggingRoundTripper(rt http.RoundTripper, levels ...DebugLevel) http.RoundTripper {
442 drt := &debuggingRoundTripper{
443 delegatedRoundTripper: rt,
444 }
445 for _, v := range levels {
446 drt.levels |= 1 << v
447 }
448 return drt
449 }
450
451 func (rt *debuggingRoundTripper) CancelRequest(req *http.Request) {
452 tryCancelRequest(rt.WrappedRoundTripper(), req)
453 }
454
455 var knownAuthTypes = map[string]bool{
456 "bearer": true,
457 "basic": true,
458 "negotiate": true,
459 }
460
461 // maskValue masks credential content from authorization headers
462 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization
463 func maskValue(key string, value string) string {
464 if !strings.EqualFold(key, "Authorization") {
465 return value
466 }
467 if len(value) == 0 {
468 return ""
469 }
470 var authType string
471 if i := strings.Index(value, " "); i > 0 {
472 authType = value[0:i]
473 } else {
474 authType = value
475 }
476 if !knownAuthTypes[strings.ToLower(authType)] {
477 return "<masked>"
478 }
479 if len(value) > len(authType)+1 {
480 value = authType + " <masked>"
481 } else {
482 value = authType
483 }
484 return value
485 }
486
487 func (rt *debuggingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
488 logger := klog.FromContext(req.Context())
489 levels := rt.levels
490
491 // When logging depends on the context, it uses the verbosity of the per-context logger
492 // and a hard-coded mapping of verbosity to debug details. Otherwise all messages
493 // are logged as V(0).
494 if levels&(1<<DebugByContext) != 0 {
495 if loggerV := logger.V(9); loggerV.Enabled() {
496 logger = loggerV
497 // The curl command replaces logging of the URL.
498 levels |= levelsV9
499 } else if loggerV := logger.V(8); loggerV.Enabled() {
500 logger = loggerV
501 levels |= levelsV8
502 } else if loggerV := logger.V(7); loggerV.Enabled() {
503 logger = loggerV
504 levels |= levelsV7
505 } else if loggerV := logger.V(6); loggerV.Enabled() {
506 logger = loggerV
507 levels |= levelsV6
508 }
509 }
510
511 reqInfo := newRequestInfo(req)
512
513 kvs := make([]any, 0, 8) // Exactly large enough for all appends below.
514 if levels&(1<<DebugJustURL) != 0 {
515 kvs = append(kvs,
516 "verb", reqInfo.RequestVerb,
517 "url", reqInfo.RequestURL,
518 )
519 }
520 if levels&(1<<DebugCurlCommand) != 0 {
521 kvs = append(kvs, "curlCommand", reqInfo.toCurl())
522 }
523 if levels&(1<<DebugRequestHeaders) != 0 {
524 kvs = append(kvs, "headers", newHeadersMap(reqInfo.RequestHeaders))
525 }
526 if len(kvs) > 0 {
527 logger.Info("Request", kvs...)
528 }
529
530 startTime := time.Now()
531
532 if levels&(1<<DebugDetailedTiming) != 0 {
533 var getConn, dnsStart, dialStart, tlsStart, serverStart time.Time
534 var host string
535 trace := &httptrace.ClientTrace{
536 // DNS
537 DNSStart: func(info httptrace.DNSStartInfo) {
538 reqInfo.muTrace.Lock()
539 defer reqInfo.muTrace.Unlock()
540 dnsStart = time.Now()
541 host = info.Host
542 },
543 DNSDone: func(info httptrace.DNSDoneInfo) {
544 reqInfo.muTrace.Lock()
545 defer reqInfo.muTrace.Unlock()
546 reqInfo.DNSLookup = time.Since(dnsStart)
547 logger.Info("HTTP Trace: DNS Lookup resolved", "host", host, "address", info.Addrs)
548 },
549 // Dial
550 ConnectStart: func(network, addr string) {
551 reqInfo.muTrace.Lock()
552 defer reqInfo.muTrace.Unlock()
553 dialStart = time.Now()
554 },
555 ConnectDone: func(network, addr string, err error) {
556 reqInfo.muTrace.Lock()
557 defer reqInfo.muTrace.Unlock()
558 reqInfo.Dialing = time.Since(dialStart)
559 if err != nil {
560 logger.Info("HTTP Trace: Dial failed", "network", network, "address", addr, "err", err)
561 } else {
562 logger.Info("HTTP Trace: Dial succeed", "network", network, "address", addr)
563 }
564 },
565 // TLS
566 TLSHandshakeStart: func() {
567 tlsStart = time.Now()
568 },
569 TLSHandshakeDone: func(_ tls.ConnectionState, _ error) {
570 reqInfo.muTrace.Lock()
571 defer reqInfo.muTrace.Unlock()
572 reqInfo.TLSHandshake = time.Since(tlsStart)
573 },
574 // Connection (it can be DNS + Dial or just the time to get one from the connection pool)
575 GetConn: func(hostPort string) {
576 getConn = time.Now()
577 },
578 GotConn: func(info httptrace.GotConnInfo) {
579 reqInfo.muTrace.Lock()
580 defer reqInfo.muTrace.Unlock()
581 reqInfo.GetConnection = time.Since(getConn)
582 reqInfo.ConnectionReused = info.Reused
583 },
584 // Server Processing (time since we wrote the request until first byte is received)
585 WroteRequest: func(info httptrace.WroteRequestInfo) {
586 reqInfo.muTrace.Lock()
587 defer reqInfo.muTrace.Unlock()
588 serverStart = time.Now()
589 },
590 GotFirstResponseByte: func() {
591 reqInfo.muTrace.Lock()
592 defer reqInfo.muTrace.Unlock()
593 reqInfo.ServerProcessing = time.Since(serverStart)
594 },
595 }
596 req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
597 }
598
599 response, err := rt.delegatedRoundTripper.RoundTrip(req)
600 reqInfo.Duration = time.Since(startTime)
601
602 reqInfo.complete(response, err)
603
604 kvs = make([]any, 0, 20) // Exactly large enough for all appends below.
605 if levels&(1<<DebugURLTiming) != 0 {
606 kvs = append(kvs, "verb", reqInfo.RequestVerb, "url", reqInfo.RequestURL)
607 }
608 if levels&(1<<DebugURLTiming|1<<DebugResponseStatus) != 0 {
609 kvs = append(kvs, "status", reqInfo.ResponseStatus)
610 }
611 if levels&(1<<DebugResponseHeaders) != 0 {
612 kvs = append(kvs, "headers", newHeadersMap(reqInfo.ResponseHeaders))
613 }
614 if levels&(1<<DebugURLTiming|1<<DebugDetailedTiming|1<<DebugResponseStatus) != 0 {
615 kvs = append(kvs, "milliseconds", reqInfo.Duration.Nanoseconds()/int64(time.Millisecond))
616 }
617 if levels&(1<<DebugDetailedTiming) != 0 {
618 if !reqInfo.ConnectionReused {
619 kvs = append(kvs,
620 "dnsLookupMilliseconds", reqInfo.DNSLookup.Nanoseconds()/int64(time.Millisecond),
621 "dialMilliseconds", reqInfo.Dialing.Nanoseconds()/int64(time.Millisecond),
622 "tlsHandshakeMilliseconds", reqInfo.TLSHandshake.Nanoseconds()/int64(time.Millisecond),
623 )
624 } else {
625 kvs = append(kvs, "getConnectionMilliseconds", reqInfo.GetConnection.Nanoseconds()/int64(time.Millisecond))
626 }
627 if reqInfo.ServerProcessing != 0 {
628 kvs = append(kvs, "serverProcessingMilliseconds", reqInfo.ServerProcessing.Nanoseconds()/int64(time.Millisecond))
629 }
630 }
631 if len(kvs) > 0 {
632 logger.Info("Response", kvs...)
633 }
634
635 return response, err
636 }
637
638 // headerMap formats headers sorted and across multiple lines with no quoting
639 // when using string output and as JSON when using zapr.
640 type headersMap http.Header
641
642 // newHeadersMap masks all sensitive values. This has to be done before
643 // passing the map to a logger because while in practice all loggers
644 // either use String or MarshalLog, that is not guaranteed.
645 func newHeadersMap(header http.Header) headersMap {
646 h := make(headersMap, len(header))
647 for key, values := range header {
648 maskedValues := make([]string, 0, len(values))
649 for _, value := range values {
650 maskedValues = append(maskedValues, maskValue(key, value))
651 }
652 h[key] = maskedValues
653 }
654 return h
655 }
656
657 var _ fmt.Stringer = headersMap{}
658 var _ logr.Marshaler = headersMap{}
659
660 func (h headersMap) String() string {
661 // The fixed size typically avoids memory allocations when it is large enough.
662 keys := make([]string, 0, 20)
663 for key := range h {
664 keys = append(keys, key)
665 }
666 sort.Strings(keys)
667 var buffer strings.Builder
668 for _, key := range keys {
669 for _, value := range h[key] {
670 _, _ = buffer.WriteString(key)
671 _, _ = buffer.WriteString(": ")
672 _, _ = buffer.WriteString(value)
673 _, _ = buffer.WriteString("\n")
674 }
675 }
676 return buffer.String()
677 }
678
679 func (h headersMap) MarshalLog() any {
680 return map[string][]string(h)
681 }
682
683 func (rt *debuggingRoundTripper) WrappedRoundTripper() http.RoundTripper {
684 return rt.delegatedRoundTripper
685 }
686
687 func legalHeaderByte(b byte) bool {
688 return int(b) < len(legalHeaderKeyBytes) && legalHeaderKeyBytes[b]
689 }
690
691 func shouldEscape(b byte) bool {
692 // url.PathUnescape() returns an error if any '%' is not followed by two
693 // hexadecimal digits, so we'll intentionally encode it.
694 return !legalHeaderByte(b) || b == '%'
695 }
696
697 func headerKeyEscape(key string) string {
698 buf := strings.Builder{}
699 for i := 0; i < len(key); i++ {
700 b := key[i]
701 if shouldEscape(b) {
702 // %-encode bytes that should be escaped:
703 // https://tools.ietf.org/html/rfc3986#section-2.1
704 fmt.Fprintf(&buf, "%%%02X", b)
705 continue
706 }
707 buf.WriteByte(b)
708 }
709 return buf.String()
710 }
711
712 // legalHeaderKeyBytes was copied from net/http/lex.go's isTokenTable.
713 // See https://httpwg.github.io/specs/rfc7230.html#rule.token.separators
714 var legalHeaderKeyBytes = [127]bool{
715 '%': true,
716 '!': true,
717 '#': true,
718 '$': true,
719 '&': true,
720 '\'': true,
721 '*': true,
722 '+': true,
723 '-': true,
724 '.': true,
725 '0': true,
726 '1': true,
727 '2': true,
728 '3': true,
729 '4': true,
730 '5': true,
731 '6': true,
732 '7': true,
733 '8': true,
734 '9': true,
735 'A': true,
736 'B': true,
737 'C': true,
738 'D': true,
739 'E': true,
740 'F': true,
741 'G': true,
742 'H': true,
743 'I': true,
744 'J': true,
745 'K': true,
746 'L': true,
747 'M': true,
748 'N': true,
749 'O': true,
750 'P': true,
751 'Q': true,
752 'R': true,
753 'S': true,
754 'T': true,
755 'U': true,
756 'W': true,
757 'V': true,
758 'X': true,
759 'Y': true,
760 'Z': true,
761 '^': true,
762 '_': true,
763 '`': true,
764 'a': true,
765 'b': true,
766 'c': true,
767 'd': true,
768 'e': true,
769 'f': true,
770 'g': true,
771 'h': true,
772 'i': true,
773 'j': true,
774 'k': true,
775 'l': true,
776 'm': true,
777 'n': true,
778 'o': true,
779 'p': true,
780 'q': true,
781 'r': true,
782 's': true,
783 't': true,
784 'u': true,
785 'v': true,
786 'w': true,
787 'x': true,
788 'y': true,
789 'z': true,
790 '|': true,
791 '~': true,
792 }