Skip to content

Commit

Permalink
Added func to redact slices
Browse files Browse the repository at this point in the history
  • Loading branch information
gildas committed Nov 19, 2024
1 parent 7cd433c commit fa998a2
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
2 changes: 2 additions & 0 deletions common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,8 @@ func (suite *LoggerSuite) LogLineEqual(line string, records map[string]string) {
stringvalue = actual.String()
case map[string]interface{}:
stringvalue = fmt.Sprintf("%v", value)
case []interface{}:
stringvalue = fmt.Sprintf("%v", value)
default:
suite.Failf(fmt.Sprintf("The value of the key %s cannot be casted to string", key), "Type: %s", reflect.TypeOf(value))
}
Expand Down
12 changes: 12 additions & 0 deletions redact.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
)

// Redact redacts a stringable value
func Redact(value interface{}) string {
if value == nil {
return ""
Expand All @@ -15,10 +16,21 @@ func Redact(value interface{}) string {
return ""
}

// RedactAll redacts all items in a slice of redactable items
func RedactAll[T Redactable](items []T) []any {
redacted := make([]any, len(items))
for i, item := range items {
redacted[i] = item.Redact()
}
return redacted
}

// RedactWithHash redacts a value with a hash
func RedactWithHash(value interface{}) string {
return RedactWithPrefixedHash("REDACTED", value)
}

// RedactWithPrefixedHash redacts a value with a prefix and a hash
func RedactWithPrefixedHash(prefix string, value interface{}) string {
if value == nil {
return ""
Expand Down
21 changes: 21 additions & 0 deletions redact_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,27 @@ func (suite *RedactSuite) TestCanRedactSensitiveStruct() {
})
}

func (suite *RedactSuite) TestCanRedactSensitiveSliceOfStruct() {
customers := []User{{"12345678", "John Doe", nil}, {"87654321", "Jane Doe", nil}}
output := CaptureStdout(func() {
log := logger.Create("test", &logger.StdoutStream{Unbuffered: true})
log.Record("customers", logger.RedactAll(customers)).Infof("message")
})
suite.LogLineEqual(output, map[string]string{
"customers": `\[map\[id:12345678 name:REDACTED\] map\[id:87654321 name:REDACTED\]\]`,
"hostname": `[a-zA-Z_0-9\-\.]+`,
"level": "30",
"msg": "message",
"name": "test",
"pid": "[0-9]+",
"scope": "main",
"tid": "[0-9]+",
"time": `[0-9]+-[0-9]+-[0-9]+T[0-9]+:[0-9]+:[0-9]+Z`,
"topic": "main",
"v": "0",
})
}

func (suite *RedactSuite) TestCanRedactMessage() {
redactor := core.Must(logger.NewRedactor(`\+[0-9]{11}`))
suite.Require().NotEmpty(redactor.String())
Expand Down

0 comments on commit fa998a2

Please sign in to comment.