Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/openvsx-proxy/pkg/utils.go
2498 views
1
// Copyright (c) 2021 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package pkg
6
7
import (
8
"bytes"
9
"crypto/sha1"
10
"fmt"
11
"io/ioutil"
12
"net/http"
13
"time"
14
"unicode/utf8"
15
16
"github.com/gitpod-io/gitpod/common-go/log"
17
"github.com/sirupsen/logrus"
18
"golang.org/x/xerrors"
19
)
20
21
func (o *OpenVSXProxy) DurationLogFields(duration time.Duration) logrus.Fields {
22
return logrus.Fields{
23
"duration": duration,
24
"duration_human": duration.String(),
25
}
26
}
27
28
func (o *OpenVSXProxy) key(r *http.Request) (string, error) {
29
bh, err := o.bodyHash(r)
30
if err != nil {
31
return "", err
32
}
33
return fmt.Sprintf("%s %s %d %s", r.Method, r.URL, r.ContentLength, bh), nil
34
}
35
36
func (o *OpenVSXProxy) bodyHash(r *http.Request) (string, error) {
37
if r == nil || r.Body == nil {
38
return "", xerrors.Errorf("request or body is nil")
39
}
40
body, err := ioutil.ReadAll(r.Body)
41
if err != nil {
42
return "", err
43
}
44
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
45
bodyHash := o.hash(body)
46
if log.Log.Level >= logrus.DebugLevel {
47
if utf8.Valid(body) {
48
bodyStr := string(body)
49
truncatedSuffix := ""
50
if len(bodyStr) > 500 {
51
truncatedSuffix = "... [truncated]"
52
}
53
log.WithField("bodyHash", bodyHash).Debugf("body of bodyhash '%s': %.500s%s", bodyHash, bodyStr, truncatedSuffix)
54
} else {
55
log.WithField("bodyHash", bodyHash).Debugf("body of bodyhash '%s' is binary", bodyHash)
56
}
57
}
58
return bodyHash, nil
59
}
60
61
func (o *OpenVSXProxy) hash(v []byte) string {
62
h := sha1.New()
63
h.Write(v)
64
bs := h.Sum(nil)
65
return fmt.Sprintf("%x", bs)
66
}
67
68