Skip to content

Commit

Permalink
Merge pull request #26 from m-mizutani/fix/redact-string-any
Browse files Browse the repository at this point in the history
fix(redact): RedactString to handle any in map
  • Loading branch information
m-mizutani authored Feb 23, 2025
2 parents 351da57 + 6c9adfe commit ded8cee
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
19 changes: 15 additions & 4 deletions redactor.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,23 @@ func (x Redactors) Redact(src, dst reflect.Value) bool {
// RedactString is a redactor to redact string value. It receives a function to redact string. The function receives the string value and returns the redacted string value. The returned Redact function always returns true if the source value is string. Otherwise, it returns false.
func RedactString(redact func(s string) string) Redactor {
return func(src, dst reflect.Value) bool {
if src.Kind() != reflect.String {
return false
if src.Kind() == reflect.String {
dst.Elem().SetString(redact(src.String()))
return true
}

// If the source value is `any`, not nil and string, it should be redacted.
if src.Kind() == reflect.Interface && !src.IsNil() {
elem := src.Elem()
if elem.Kind() == reflect.String {
redacted := redact(elem.String())
// Destination value is also `any`, so it should use `Set` to set the redacted string value instead of `SetString`.
dst.Elem().Set(reflect.ValueOf(redacted))
return true
}
}

dst.Elem().SetString(redact(src.String()))
return true
return false
}
}

Expand Down
18 changes: 18 additions & 0 deletions redactor_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package masq_test

import (
"bytes"
"log/slog"
"testing"

"github.com/m-mizutani/gt"
"github.com/m-mizutani/masq"
)

Expand Down Expand Up @@ -28,3 +33,16 @@ func ExampleMaskWithSymbol() {
// Output:
// {"level":"INFO","msg":"Got record","record":{"Email":"************ (remained 36 chars)","ID":"m-mizutani","Phone":"*************"},"time":"2022-12-25T09:00:00.123456789"}
}

func TestMapAny(t *testing.T) {
var buf bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&buf, &slog.HandlerOptions{
ReplaceAttr: masq.New(
masq.WithFieldName("Secret", masq.RedactString(func(s string) string {
return "REDACTED"
})),
),
}))
logger.Info("hello", slog.Any("target", map[string]any{"Secret": "xxx"}))
gt.S(t, buf.String()).Contains("REDACTED")
}

0 comments on commit ded8cee

Please sign in to comment.