go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/auth/transport.go (about) 1 // Copyright 2016 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package auth 16 17 import ( 18 "context" 19 "net/http" 20 ) 21 22 // NewModifyingTransport returns a transport that can modify headers of 23 // http.Request's that pass through it (e.g. by appending authentication 24 // information). 25 // 26 // Go docs explicitly prohibit this kind of behavior, but everyone cheat and 27 // implement it anyway. E.g. https://github.com/golang/oauth2. 28 // 29 // Works only with Go >=1.5 transports (that use Request.Cancel instead of 30 // deprecated Transport.CancelRequest). For same reason doesn't implement 31 // CancelRequest itself. 32 // 33 // TODO(vadimsh): Move it elsewhere. It has no direct relation to auth. 34 func NewModifyingTransport(base http.RoundTripper, modifier func(*http.Request) error) http.RoundTripper { 35 return &modifyingTransport{ 36 base: base, 37 modifier: modifier, 38 } 39 } 40 41 type modifyingTransport struct { 42 base http.RoundTripper 43 modifier func(*http.Request) error 44 } 45 46 func (t *modifyingTransport) RoundTrip(req *http.Request) (*http.Response, error) { 47 clone := *req 48 clone.Header = make(http.Header, len(req.Header)) 49 for k, v := range req.Header { 50 clone.Header[k] = v 51 } 52 if err := t.modifier(&clone); err != nil { 53 return nil, err 54 } 55 return t.base.RoundTrip(&clone) 56 } 57 58 var globalInstrumentTransport func(context.Context, http.RoundTripper, string) http.RoundTripper 59 60 // SetMonitoringInstrumentation sets a global callback used by Authenticator to 61 // add monitoring instrumentation to a transport. 62 // 63 // This is used by tsmon library in init(). We have to resort to callbacks to 64 // break module dependency cycle (tsmon is using auth lib already). 65 func SetMonitoringInstrumentation(cb func(context.Context, http.RoundTripper, string) http.RoundTripper) { 66 globalInstrumentTransport = cb 67 }