github.com/zppinho/prow@v0.0.0-20240510014325-1738badeb017/pkg/github/ghmetrics/hash.go (about) 1 /* 2 Copyright 2019 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 ghmetrics 18 19 import ( 20 "crypto/sha256" 21 "fmt" 22 "net/http" 23 "sync" 24 25 "github.com/sirupsen/logrus" 26 ) 27 28 // Hasher knows how to hash an authorization header from a request 29 type Hasher interface { 30 Hash(req *http.Request) string 31 } 32 33 func NewCachingHasher() Hasher { 34 return &cachingHasher{ 35 lock: sync.RWMutex{}, 36 hashes: map[string]string{}, 37 } 38 } 39 40 type cachingHasher struct { 41 lock sync.RWMutex 42 hashes map[string]string 43 } 44 45 func (h *cachingHasher) Hash(req *http.Request) string { 46 // get authorization header to convert to sha256 47 authHeader := req.Header.Get("Authorization") 48 if authHeader == "" { 49 logrus.Warn("Couldn't retrieve 'Authorization' header, adding to unknown bucket") 50 authHeader = "unknown" 51 } 52 h.lock.RLock() 53 hash, cached := h.hashes[authHeader] 54 h.lock.RUnlock() 55 if cached { 56 return hash 57 } 58 59 h.lock.Lock() 60 hash = fmt.Sprintf("%x", sha256.Sum256([]byte(authHeader))) // use %x to make this a utf-8 string for use as a label 61 h.hashes[authHeader] = hash 62 h.lock.Unlock() 63 return hash 64 }