github.com/zppinho/prow@v0.0.0-20240510014325-1738badeb017/pkg/apptokenequalizer/app_token_equalizer.go (about)

     1  /*
     2  Copyright 2020 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 apptokenequalizer
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/json"
    22  	"io"
    23  	"net/http"
    24  	"strconv"
    25  	"strings"
    26  	"sync"
    27  	"time"
    28  
    29  	"github.com/sirupsen/logrus"
    30  
    31  	"sigs.k8s.io/prow/pkg/github"
    32  )
    33  
    34  func New(delegate http.RoundTripper) http.RoundTripper {
    35  	return &appTokenEqualizerTransport{
    36  		delegate:   delegate,
    37  		tokenCache: map[string]github.AppInstallationToken{},
    38  	}
    39  }
    40  
    41  type appTokenEqualizerTransport struct {
    42  	delegate   http.RoundTripper
    43  	lock       sync.Mutex
    44  	tokenCache map[string]github.AppInstallationToken
    45  }
    46  
    47  func (t *appTokenEqualizerTransport) RoundTrip(r *http.Request) (*http.Response, error) {
    48  	resp, err := t.delegate.RoundTrip(r)
    49  	if err != nil || resp.StatusCode != 201 || r.Method != http.MethodPost || !strings.HasPrefix(r.URL.Path, "/app/installations/") {
    50  		return resp, err
    51  	}
    52  	body := resp.Body
    53  	defer body.Close()
    54  
    55  	l := logrus.WithField("path", r.URL.Path)
    56  	bodyBytes, err := io.ReadAll(resp.Body)
    57  	if err != nil {
    58  		l.WithError(err).Error("Failed to read body")
    59  		resp.StatusCode = http.StatusInternalServerError
    60  		resp.Status = http.StatusText(http.StatusInternalServerError)
    61  		return resp, nil
    62  	}
    63  
    64  	var token github.AppInstallationToken
    65  	if err := json.Unmarshal(bodyBytes, &token); err != nil {
    66  		l.WithError(err).Error("Failed to unmarshal")
    67  		resp.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
    68  		return resp, nil
    69  	}
    70  
    71  	split := strings.Split(r.URL.Path, "/")
    72  	if n := len(split); n != 5 {
    73  		l.Errorf("Splitting path %s by '/' didn't yield exactly five elements but %d", r.URL.Path, n)
    74  		resp.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
    75  		return resp, nil
    76  	}
    77  	appId := split[3]
    78  
    79  	t.lock.Lock()
    80  	defer t.lock.Unlock()
    81  	if cachedToken, ok := t.tokenCache[appId]; ok && cachedToken.ExpiresAt.Add(-time.Minute).After(time.Now()) {
    82  		token = cachedToken
    83  	} else {
    84  		t.tokenCache[appId] = token
    85  	}
    86  
    87  	serializedToken, err := json.Marshal(token)
    88  	if err != nil {
    89  		l.WithError(err).Error("Failed to serialize token")
    90  		resp.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
    91  		return resp, nil
    92  	}
    93  
    94  	resp.Body = io.NopCloser(bytes.NewBuffer(serializedToken))
    95  	resp.ContentLength = int64(len(serializedToken))
    96  	resp.Header.Set("X-PROW-GHPROXY-REPLACED-TOKEN", "true")
    97  	resp.Header.Set("Content-Length", strconv.Itoa(len(serializedToken)))
    98  	return resp, nil
    99  }