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

Add: the ability to redact values from Stringer and Error interface. #592

Merged
merged 8 commits into from
Apr 1, 2024
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
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [Unreleased]
- No changes yet.
## Added
- Redacted annotation provides a mechanism to redact certain struct fields from
errors messages and log objects.

## [1.31.0] - 2023-06-09
### Changed
Expand Down
69 changes: 57 additions & 12 deletions gen/field.go
Original file line number Diff line number Diff line change
Expand Up @@ -699,25 +699,38 @@ func (f fieldGroupGenerator) String(g Generator) error {
<range .Fields>
<- $fname := goName . ->
<- $f := printf "%s.%s" $v $fname ->
<- $shouldRedact := shouldRedact . ->
<- $redactedContent := redactedContent ->

<- if not .Required ->
if <$f> != nil {
<if isPrimitiveType .Type ->
<$fields>[<$i>] = <$fmt>.Sprintf("<$fname>: %v", *(<$f>))
<- else ->
<$fields>[<$i>] = <$fmt>.Sprintf("<$fname>: %v", <$f>)
<- if $shouldRedact ->
<$fields>[<$i>] = "<$fname>: <$redactedContent>"
<- else >
<if isPrimitiveType .Type ->
<$fields>[<$i>] = <$fmt>.Sprintf("<$fname>: %v", *(<$f>))
<- else ->
<$fields>[<$i>] = <$fmt>.Sprintf("<$fname>: %v", <$f>)
<- end>
<- end>
<$i>++
}
<- else ->
<$fields>[<$i>] = <$fmt>.Sprintf("<$fname>: %v", <$f>)
<- if $shouldRedact ->
<$fields>[<$i>] = "<$fname>: <$redactedContent>"
<- else ->
<$fields>[<$i>] = <$fmt>.Sprintf("<$fname>: %v", <$f>)
<- end>
<$i>++
<- end>
<end>

return <$fmt>.Sprintf("<.Name>{%v}", <$strings>.Join(<$fields>[:<$i>], ", "))
}
`, f)
`, f,
TemplateFunc("shouldRedact", shouldRedact),
TemplateFunc("redactedContent", redactedContent),
)
}

func (f fieldGroupGenerator) ErrorName(g Generator) error {
Expand Down Expand Up @@ -779,18 +792,28 @@ func (f fieldGroupGenerator) Zap(g Generator) error {
if <$v> == nil {
return nil
}
< $redactedContent := redactedContent ->
<range .Fields>
<- $shouldRedact := shouldRedact . ->
<- if not (zapOptOut .) ->
<- $fval := printf "%s.%s" $v (goName .) ->
<- if .Required ->
<zapEncodeBegin .Type ->
<$enc>.Add<zapEncoder .Type>("<fieldLabel .>", <zapMarshaler .Type $fval>)
<- zapEncodeEnd .Type>
<- if $shouldRedact ->
<$enc>.AddString("<fieldLabel .>", "<$redactedContent>")
<- else ->
<- zapEncodeBegin .Type ->
<$enc>.Add<zapEncoder .Type>("<fieldLabel .>", <zapMarshaler .Type $fval>)
<- zapEncodeEnd .Type ->
<- end ->
<- else ->
if <$fval> != nil {
<zapEncodeBegin .Type ->
<$enc>.Add<zapEncoder .Type>("<fieldLabel .>", <zapMarshalerPtr .Type $fval>)
<- zapEncodeEnd .Type>
<- if $shouldRedact ->
<$enc>.AddString("<fieldLabel .>", "<$redactedContent>")
<- else ->
<- zapEncodeBegin .Type ->
<$enc>.Add<zapEncoder .Type>("<fieldLabel .>", <zapMarshalerPtr .Type $fval>)
<- zapEncodeEnd .Type ->
<- end >
}
<- end>
<- end>
Expand All @@ -800,6 +823,8 @@ func (f fieldGroupGenerator) Zap(g Generator) error {
`, f,
TemplateFunc("zapOptOut", zapOptOut),
TemplateFunc("fieldLabel", entityLabel),
TemplateFunc("shouldRedact", shouldRedact),
TemplateFunc("redactedContent", redactedContent),
)
}

Expand Down Expand Up @@ -875,3 +900,23 @@ func verifyUniqueFieldLabels(fs compile.FieldGroup) error {
}
return nil
}

// RedactLabel provides a mechanism to redact certain struct fields from
// the outputs of String(), Error() and MarshalLogObject() methods.
//
// struct Contact {
// 1: required string name
// 2: required string email (go.redact)
// }
const RedactLabel = "go.redact"

func shouldRedact(spec *compile.FieldSpec) bool {
_, ok := spec.Annotations[RedactLabel]
return ok
}

const _redactContent = "<redacted>"

func redactedContent() string {
return _redactContent
}
73 changes: 71 additions & 2 deletions gen/field_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,12 @@ import (
"strings"
"testing"

"go.uber.org/thriftrw/compile"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/thriftrw/compile"
"go.uber.org/thriftrw/gen/internal/tests/exceptions"
ts "go.uber.org/thriftrw/gen/internal/tests/structs"
"go.uber.org/zap/zapcore"
)

func TestFieldLabelConflict(t *testing.T) {
Expand Down Expand Up @@ -137,3 +139,70 @@ func TestCompileJSONTag(t *testing.T) {
})
}
}

func TestHasRedactedAnnotation(t *testing.T) {
foo := &compile.FieldSpec{
Name: "foo",
}
redact := &compile.FieldSpec{
Name: "redact",
Annotations: compile.Annotations{RedactLabel: ""},
}
tests := []struct {
name string
spec *compile.FieldSpec
want bool
}{
{name: "redact annotation", spec: redact, want: true},
{name: "no redact annotation", spec: foo, want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equalf(t, tt.want, shouldRedact(tt.spec), "shouldRedact(%v)", tt.spec)
})
}
}

func TestRedactedAnnotation(t *testing.T) {
age := int32(21)
pi := ts.PersonalInfo{
Age: toPtr(age),
Race: toPtr("martian"),
}
redactException := exceptions.DoesNotExistException{
Key: "s",
UserName: toPtr("john doe"),
}
enc := zapcore.NewMapObjectEncoder()
require.NoError(t, pi.MarshalLogObject(enc))
require.Len(t, enc.Fields, 2)
_, ok := enc.Fields["race"]
require.True(t, ok)

eEncoder := zapcore.NewMapObjectEncoder()
require.NoError(t, redactException.MarshalLogObject(eEncoder))
require.Len(t, eEncoder.Fields, 2)
_, ok = eEncoder.Fields["userName"]
require.True(t, ok)

tests := []struct {
name string
got any
want any
}{
{name: "struct/string", got: pi.String(), want: "PersonalInfo{Age: 21, Race: <redacted>}"},
{name: "struct/MarshalLogObject", got: enc.Fields["race"], want: _redactContent},
{name: "exception/string", got: redactException.String(), want: "DoesNotExistException{Key: s, UserName: <redacted>}"},
{name: "exception/error", got: redactException.Error(), want: "DoesNotExistException{Key: s, UserName: <redacted>}"},
{name: "exception/MarshalLogObject", got: eEncoder.Fields["userName"], want: _redactContent},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.EqualValues(t, tt.want, tt.got)
})
}
}

func toPtr[T any](input T) *T {
return &input
}
76 changes: 70 additions & 6 deletions gen/internal/tests/exceptions/exceptions.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading