-
Notifications
You must be signed in to change notification settings - Fork 120
/
transport.go
63 lines (51 loc) · 1.3 KB
/
transport.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package kubeclient
import (
"net/http"
netutil "k8s.io/apimachinery/pkg/util/net"
)
const (
xKargoUserCredentialHeader = "X-Kargo-User-Credential" // #nosec G101
)
var (
_ netutil.RoundTripperWrapper = &credentialHook{}
_ netutil.RoundTripperWrapper = &credentialInjector{}
)
type credentialHook struct {
rt http.RoundTripper
}
func newAuthorizationHeaderHook(rt http.RoundTripper) http.RoundTripper {
return &credentialHook{
rt: rt,
}
}
func (h *credentialHook) RoundTrip(req *http.Request) (*http.Response, error) {
cred := req.Header.Get("Authorization")
res, err := h.rt.RoundTrip(req)
if res != nil {
res.Header.Set(xKargoUserCredentialHeader, cred)
}
return res, err
}
func (h *credentialHook) WrappedRoundTripper() http.RoundTripper {
return h.rt
}
type credentialInjector struct {
rt http.RoundTripper
}
func NewCredentialInjector(rt http.RoundTripper) http.RoundTripper {
return &credentialInjector{
rt: rt,
}
}
func (i *credentialInjector) RoundTrip(req *http.Request) (*http.Response, error) {
cred, ok := GetCredentialFromContext(req.Context())
if !ok {
return i.rt.RoundTrip(req)
}
newReq := req.Clone(req.Context())
newReq.Header.Set("Authorization", cred)
return i.rt.RoundTrip(newReq)
}
func (i *credentialInjector) WrappedRoundTripper() http.RoundTripper {
return i.rt
}