fix: mask redis credentials when logging (#2264)

This commit is contained in:
mycodeself
2022-06-06 10:07:08 +02:00
committed by GitHub
parent d8b59efea9
commit a17c3eec2a
3 changed files with 49 additions and 1 deletions

View File

@@ -33,7 +33,7 @@ type Cache struct {
// NewCache is the factory method for Cache
func NewCache(c option.CacheOption) (Cache, error) {
if strings.HasPrefix(c.CacheBackend, "redis://") {
log.Logger.Infof("Redis cache: %s", c.CacheBackend)
log.Logger.Infof("Redis cache: %s", c.CacheBackendMasked())
options, err := redis.ParseURL(c.CacheBackend)
if err != nil {
return Cache{}, err

View File

@@ -1,6 +1,7 @@
package option
import (
"fmt"
"strings"
"time"
@@ -51,3 +52,15 @@ func (c *CacheOption) Init() error {
}
return nil
}
// CacheBackendMasked returns the redis connection string masking credentials
func (c *CacheOption) CacheBackendMasked() string {
endIndex := strings.Index(c.CacheBackend, "@")
if endIndex == -1 {
return c.CacheBackend
}
startIndex := strings.Index(c.CacheBackend, "//")
return fmt.Sprintf("%s****%s", c.CacheBackend[:startIndex+2], c.CacheBackend[endIndex:])
}

View File

@@ -90,3 +90,38 @@ func TestCacheOption_Init(t *testing.T) {
})
}
}
func TestCacheOption_CacheBackendMasked(t *testing.T) {
type fields struct {
backend string
}
tests := []struct {
name string
fields fields
want string
}{
{
name: "redis cache backend masked",
fields: fields{
backend: "redis://root:password@localhost:6379",
},
want: "redis://****@localhost:6379",
},
{
name: "redis cache backend masked does nothing",
fields: fields{
backend: "redis://localhost:6379",
},
want: "redis://localhost:6379",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &option.CacheOption{
CacheBackend: tt.fields.backend,
}
assert.Equal(t, tt.want, c.CacheBackendMasked())
})
}
}