Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix interface conversion when Kind() == string but v.(string) panics #12

Merged
merged 4 commits into from
Jan 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion redactrus.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package redactrus

import (
"fmt"
"reflect"
"regexp"

Expand Down Expand Up @@ -56,9 +57,20 @@ func (h *Hook) Fire(e *logrus.Entry) error {
}

// Redact based on value matching in Data fields
// Handle fmt.Stringer type
if vv, ok := v.(fmt.Stringer); ok {
e.Data[k] = re.ReplaceAllString(vv.String(), "$1[REDACTED]$2")
continue
}
whuang8 marked this conversation as resolved.
Show resolved Hide resolved

switch reflect.TypeOf(v).Kind() {
case reflect.String:
e.Data[k] = re.ReplaceAllString(v.(string), "$1[REDACTED]$2")
switch vv := v.(type) {
case string:
e.Data[k] = re.ReplaceAllString(vv, "$1[REDACTED]$2")
default:
e.Data[k] = re.ReplaceAllString(fmt.Sprint(v), "$1[REDACTED]$2")
}
continue
}
}
Expand Down
33 changes: 33 additions & 0 deletions redactrus_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,3 +151,36 @@ func TestNilField(t *testing.T) {
assert.Nil(t, err)
assert.Equal(t, logrus.Fields{"Nil": nil}, logEntry.Data)
}

type stringerValue struct {
value string
}

func (v stringerValue) String() string {
return v.value
}

func TestStringer(t *testing.T) {
logEntry := &logrus.Entry{
Data: logrus.Fields{"Stringer": stringerValue{"kind is fmt.Stringer"}},
}
h = &Hook{RedactionList: []string{"kind"}}
err := h.Fire(logEntry)

assert.Nil(t, err)
assert.Equal(t, logrus.Fields{"Stringer": "[REDACTED] is fmt.Stringer"}, logEntry.Data)
}

type TypedString string

// Logrus fields can have re-typed strings so test we handle this edge case
func TestTypedStringValue(t *testing.T) {
logEntry := &logrus.Entry{
Data: logrus.Fields{"TypedString": TypedString("kind is string")},
}
h = &Hook{RedactionList: []string{"kind"}}
err := h.Fire(logEntry)

assert.Nil(t, err)
assert.Equal(t, logrus.Fields{"TypedString": "[REDACTED] is string"}, logEntry.Data)
}