at master 1.0 kB view raw
1package models 2 3import ( 4 "encoding/base64" 5 "strings" 6) 7 8// SecretMask replaces secret values in strings with "***". 9type SecretMask struct { 10 replacer *strings.Replacer 11} 12 13// NewSecretMask creates a mask for the given secret values. 14// Also registers base64-encoded variants of each secret. 15func NewSecretMask(values []string) *SecretMask { 16 var pairs []string 17 18 for _, value := range values { 19 if value == "" { 20 continue 21 } 22 23 pairs = append(pairs, value, "***") 24 25 b64 := base64.StdEncoding.EncodeToString([]byte(value)) 26 if b64 != value { 27 pairs = append(pairs, b64, "***") 28 } 29 30 b64NoPad := strings.TrimRight(b64, "=") 31 if b64NoPad != b64 && b64NoPad != value { 32 pairs = append(pairs, b64NoPad, "***") 33 } 34 } 35 36 if len(pairs) == 0 { 37 return nil 38 } 39 40 return &SecretMask{ 41 replacer: strings.NewReplacer(pairs...), 42 } 43} 44 45// Mask replaces all registered secret values with "***". 46func (m *SecretMask) Mask(input string) string { 47 if m == nil || m.replacer == nil { 48 return input 49 } 50 return m.replacer.Replace(input) 51}