github.com/oam-dev/kubevela@v1.9.11/pkg/auth/round_trippers.go (about)

     1  /*
     2  
     3   Copyright 2021 The KubeVela Authors.
     4  
     5   Licensed under the Apache License, Version 2.0 (the "License");
     6   you may not use this file except in compliance with the License.
     7   You may obtain a copy of the License at
     8  
     9       http://www.apache.org/licenses/LICENSE-2.0
    10  
    11   Unless required by applicable law or agreed to in writing, software
    12   distributed under the License is distributed on an "AS IS" BASIS,
    13   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   See the License for the specific language governing permissions and
    15   limitations under the License.
    16  
    17  */
    18  
    19  package auth
    20  
    21  import (
    22  	"net/http"
    23  
    24  	"github.com/kubevela/pkg/util/net"
    25  	utilnet "k8s.io/apimachinery/pkg/util/net"
    26  	"k8s.io/apiserver/pkg/endpoints/request"
    27  	"k8s.io/client-go/transport"
    28  	"k8s.io/klog/v2"
    29  )
    30  
    31  const (
    32  	impersonateKey = "impersonate"
    33  )
    34  
    35  var _ utilnet.RoundTripperWrapper = &impersonatingRoundTripper{}
    36  
    37  type impersonatingRoundTripper struct {
    38  	rt http.RoundTripper
    39  }
    40  
    41  // NewImpersonatingRoundTripper will add an ImpersonateUser header to a request
    42  // if the context has a specific user whom to act-as.
    43  func NewImpersonatingRoundTripper(rt http.RoundTripper) http.RoundTripper {
    44  	return &impersonatingRoundTripper{
    45  		rt: rt,
    46  	}
    47  }
    48  
    49  func (rt *impersonatingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
    50  	ctx := req.Context()
    51  	req = req.Clone(ctx)
    52  	userInfo, exists := request.UserFrom(ctx)
    53  	klog.V(7).Infof("impersonation request log. path: %s method: %s user info: %+v", req.URL.String(), req.Method, userInfo)
    54  	if exists && userInfo != nil {
    55  		if name := userInfo.GetName(); name != "" {
    56  			req.Header.Set(transport.ImpersonateUserHeader, name)
    57  			for _, group := range userInfo.GetGroups() {
    58  				req.Header.Add(transport.ImpersonateGroupHeader, group)
    59  			}
    60  			q := req.URL.Query()
    61  			q.Add(impersonateKey, "true")
    62  			req.URL.RawQuery = q.Encode()
    63  		}
    64  	}
    65  	return rt.rt.RoundTrip(req)
    66  }
    67  
    68  func (rt *impersonatingRoundTripper) CancelRequest(req *http.Request) {
    69  	net.TryCancelRequest(rt.WrappedRoundTripper(), req)
    70  }
    71  
    72  func (rt *impersonatingRoundTripper) WrappedRoundTripper() http.RoundTripper {
    73  	return rt.rt
    74  }