github.com/argoproj/argo-cd/v3@v3.2.1/util/grpc/logging_test.go (about) 1 package grpc 2 3 import ( 4 "bytes" 5 "context" 6 "fmt" 7 "testing" 8 9 "github.com/golang-jwt/jwt/v5" 10 "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors" 11 "github.com/sirupsen/logrus" 12 "github.com/stretchr/testify/assert" 13 "github.com/stretchr/testify/require" 14 "google.golang.org/grpc" 15 16 "github.com/argoproj/argo-cd/v3/pkg/apiclient/account" 17 ) 18 19 func Test_JSONLogging(t *testing.T) { 20 l := logrus.New() 21 l.SetFormatter(&logrus.JSONFormatter{}) 22 var buf bytes.Buffer 23 l.SetOutput(&buf) 24 entry := logrus.NewEntry(l) 25 26 c := t.Context() 27 req := new(account.CreateTokenRequest) 28 req.Name = "create-token-name" 29 info := &grpc.UnaryServerInfo{} 30 handler := func(_ context.Context, _ any) (any, error) { 31 return nil, nil 32 } 33 decider := func(_ context.Context, _ interceptors.CallMeta) bool { 34 return true 35 } 36 interceptor := PayloadUnaryServerInterceptor(entry, false, decider) 37 _, err := interceptor(c, req, info, handler) 38 require.NoError(t, err) 39 40 out := buf.String() 41 assert.Contains(t, out, fmt.Sprintf(`"grpc.request.content":{"name":%q`, req.Name)) 42 } 43 44 func Test_logRequest(t *testing.T) { 45 c := t.Context() 46 //nolint:staticcheck 47 c = context.WithValue(c, "claims", jwt.MapClaims{"groups": []string{"expected-group-claim"}}) 48 req := new(account.CreateTokenRequest) 49 req.Name = "create-token-name" 50 info := &grpc.UnaryServerInfo{} 51 handler := func(_ context.Context, _ any) (any, error) { 52 return nil, nil 53 } 54 decider := func(_ context.Context, _ interceptors.CallMeta) bool { 55 return true 56 } 57 58 t.Run("with debug enabled, group claims are logged", func(t *testing.T) { 59 l := logrus.New() 60 l.SetFormatter(&logrus.JSONFormatter{}) 61 var buf bytes.Buffer 62 l.SetOutput(&buf) 63 l.SetLevel(logrus.DebugLevel) 64 entry := logrus.NewEntry(l) 65 66 interceptor := PayloadUnaryServerInterceptor(entry, true, decider) 67 68 _, err := interceptor(c, req, info, handler) 69 require.NoError(t, err) 70 71 out := buf.String() 72 assert.Contains(t, out, "expected-group-claim") 73 }) 74 75 t.Run("with debug not enabled, group claims aren't logged", func(t *testing.T) { 76 l := logrus.New() 77 l.SetFormatter(&logrus.JSONFormatter{}) 78 var buf bytes.Buffer 79 l.SetOutput(&buf) 80 l.SetLevel(logrus.InfoLevel) 81 entry := logrus.NewEntry(l) 82 83 interceptor := PayloadUnaryServerInterceptor(entry, true, decider) 84 85 _, err := interceptor(c, req, info, handler) 86 require.NoError(t, err) 87 88 out := buf.String() 89 assert.NotContains(t, out, "expected-group-claim") 90 }) 91 }