Skip to content

Commit

Permalink
Redact http header values in logs (#343)
Browse files Browse the repository at this point in the history
  • Loading branch information
sfc-gh-elinardi authored Oct 11, 2023
1 parent 04285e2 commit 0f9d7d7
Show file tree
Hide file tree
Showing 8 changed files with 315 additions and 52 deletions.
131 changes: 131 additions & 0 deletions auth/opa/rpcauth/redact.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/* Copyright (c) 2023 Snowflake Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/

package rpcauth

import (
"encoding/json"
"fmt"

"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/types/descriptorpb"
)

func isMessage(descriptor protoreflect.FieldDescriptor) bool {
return descriptor.Kind() == protoreflect.MessageKind || descriptor.Kind() == protoreflect.GroupKind
}

func isDebugRedactEnabled(fd protoreflect.FieldDescriptor) bool {
opts, ok := fd.Options().(*descriptorpb.FieldOptions)
if !ok {
return false
}
return opts.GetDebugRedact()
}

func redactListField(value protoreflect.Value) {
for i := 0; i < value.List().Len(); i++ {
redactFields(value.List().Get(i).Message())
}
}

func redactMapField(value protoreflect.Value) {
value.Map().Range(func(mapKey protoreflect.MapKey, mapValue protoreflect.Value) bool {
redactFields(mapValue.Message())
return true
})
}

func redactNestedMessage(message protoreflect.Message, descriptor protoreflect.FieldDescriptor, value protoreflect.Value) {
switch {
case descriptor.IsList() && isMessage(descriptor):
redactListField(value)
case descriptor.IsMap() && isMessage(descriptor):
redactMapField(value)
case !descriptor.IsMap() && isMessage(descriptor):
redactFields(value.Message())
}
}

func redactSingleField(message protoreflect.Message, descriptor protoreflect.FieldDescriptor) {
if descriptor.Kind() == protoreflect.StringKind {
if descriptor.Cardinality() != protoreflect.Repeated {
message.Set(descriptor, protoreflect.ValueOfString("--REDACTED--"))
} else {
list := message.Mutable(descriptor).List()
for i := 0; i < list.Len(); i++ {
list.Set(i, protoreflect.ValueOfString("--REDACTED--"))
}
}
} else {
// other than string, clear it
message.Clear(descriptor)
}
}

func redactFields(message protoreflect.Message) {
message.Range(
func(descriptor protoreflect.FieldDescriptor, value protoreflect.Value) bool {
if isDebugRedactEnabled(descriptor) {
redactSingleField(message, descriptor)
return true
}
redactNestedMessage(message, descriptor, value)
return true
},
)
}

func getRedactedInput(input *RPCAuthInput) (RPCAuthInput, error) {
if input == nil {
return RPCAuthInput{}, nil
}
redactedInput := RPCAuthInput{
Method: input.Method,
MessageType: input.MessageType,
Metadata: input.Metadata,
Peer: input.Peer,
Host: input.Host,
Environment: input.Environment,
Extensions: input.Extensions,
}
if input.MessageType == "" {
return redactedInput, nil
}
var redactedMessage protoreflect.ProtoMessage
if input != nil {
// Transform the rpcauth input into the original proto
messageType, err := protoregistry.GlobalTypes.FindMessageByURL(input.MessageType)
if err != nil {
return RPCAuthInput{}, fmt.Errorf("unable to find proto type %v: %v", input.MessageType, err)
}
redactedMessage = messageType.New().Interface()
if err := protojson.Unmarshal([]byte(input.Message), redactedMessage); err != nil {
return RPCAuthInput{}, fmt.Errorf("could not marshal input into %v: %v", input.MessageType, err)
}
redactFields(redactedMessage.ProtoReflect())
}
marshaled, err := protojson.MarshalOptions{UseProtoNames: true}.Marshal(redactedMessage)
if err != nil {
return RPCAuthInput{}, status.Errorf(codes.Internal, "error marshalling request for auth: %v", err)
}
redactedInput.Message = json.RawMessage(marshaled)
return redactedInput, nil
}
106 changes: 106 additions & 0 deletions auth/opa/rpcauth/redact_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/* Copyright (c) 2023 Snowflake Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/

package rpcauth

import (
"context"
"testing"

httppb "github.com/Snowflake-Labs/sansshell/services/httpoverrpc"
"github.com/stretchr/testify/assert"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/reflect/protoregistry"
)

func TestGetRedactedInput(t *testing.T) {
httpReq := httppb.HostHTTPRequest{
Port: 8080,
Hostname: "localhost",
Protocol: "https",
Request: &httppb.HTTPRequest{
Method: "POST",
RequestUri: "/",
Headers: []*httppb.Header{
{Key: "key0", Values: []string{"val0"}},
},
},
}
mockInput, _ := NewRPCAuthInput(context.TODO(), "/HTTPOverRPC.HTTPOverRPC/Host", httpReq.ProtoReflect().Interface())

for _, tc := range []struct {
name string
createInputFn func() *RPCAuthInput
assertionFn func(RPCAuthInput)
errFunc func(*testing.T, error)
}{
{
name: "redacted fields should be redacted",
createInputFn: func() *RPCAuthInput {
return mockInput
},
assertionFn: func(result RPCAuthInput) {
messageType, _ := protoregistry.GlobalTypes.FindMessageByURL(mockInput.MessageType)
resultMessage := messageType.New().Interface()
err := protojson.Unmarshal([]byte(result.Message), resultMessage)
assert.NoError(t, err)

req := resultMessage.(*httppb.HostHTTPRequest)

assert.Equal(t, "--REDACTED--", req.Request.Headers[0].Values[0]) // field with debug_redact should be redacted
assert.Equal(t, "key0", req.Request.Headers[0].Key) // field without debug_redact should not be redacted
},
errFunc: func(t *testing.T, err error) {
assert.NoError(t, err)
},
},
{
name: "malformed input should return err",
createInputFn: func() *RPCAuthInput {
i := &RPCAuthInput{
MessageType: "malformed",
}
return i
},
errFunc: func(t *testing.T, err error) {
assert.NotNil(t, err)
},
},
{
name: "nil input should return nil",
createInputFn: func() *RPCAuthInput {
return nil
},
assertionFn: func(i RPCAuthInput) {
assert.Equal(t, RPCAuthInput{}, i)
},
errFunc: func(t *testing.T, err error) {
assert.NoError(t, err)
},
},
} {
t.Run(tc.name, func(t *testing.T) {
input := tc.createInputFn()
result, err := getRedactedInput(input)
if tc.assertionFn != nil {
tc.assertionFn(result)
}
if tc.errFunc != nil {
tc.errFunc(t, err)
}
})
}
}
22 changes: 16 additions & 6 deletions auth/opa/rpcauth/rpcauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ package rpcauth

import (
"context"
"fmt"
"strings"

"github.com/go-logr/logr"
Expand Down Expand Up @@ -96,29 +97,38 @@ func NewWithPolicy(ctx context.Context, policy string, authzHooks ...RPCAuthzHoo
func (g *Authorizer) Eval(ctx context.Context, input *RPCAuthInput) error {
logger := logr.FromContextOrDiscard(ctx)
recorder := metrics.RecorderFromContextOrNoop(ctx)

redactedInput, err := getRedactedInput(input)
if err != nil {
return fmt.Errorf("failed to get redacted input: %v", err)
}
if input != nil {
logger.V(2).Info("evaluating authz policy", "input", input)
logger.V(2).Info("evaluating authz policy", "input", redactedInput)
}
if input == nil {
err := status.Error(codes.InvalidArgument, "policy input cannot be nil")
logger.V(1).Error(err, "failed to evaluate authz policy", "input", input)
logger.V(1).Error(err, "failed to evaluate authz policy", "input", redactedInput)
recorder.CounterOrLog(ctx, authzFailureInputMissingCounter, 1)
return err
}
for _, hook := range g.hooks {
if err := hook.Hook(ctx, input); err != nil {
logger.V(1).Error(err, "authz hook error", "input", input)
logger.V(1).Error(err, "authz hook error", "input", redactedInput)
if _, ok := status.FromError(err); ok {
// error is already an appropriate status.Status
return err
}
return status.Errorf(codes.Internal, "authz hook error: %v", err)
}
}
logger.V(2).Info("evaluating authz policy post hooks", "input", input)
redactedInput, err = getRedactedInput(input)
if err != nil {
return fmt.Errorf("failed to get redacted input post hooks: %v", err)
}
logger.V(2).Info("evaluating authz policy post hooks", "input", redactedInput)
result, err := g.policy.Eval(ctx, input)
if err != nil {
logger.V(1).Error(err, "failed to evaluate authz policy", "input", input)
logger.V(1).Error(err, "failed to evaluate authz policy", "input", redactedInput)
recorder.CounterOrLog(ctx, authzFailureEvalErrorCounter, 1, attribute.String("method", input.Method))
return status.Errorf(codes.Internal, "authz policy evaluation error: %v", err)
}
Expand All @@ -133,7 +143,7 @@ func (g *Authorizer) Eval(ctx context.Context, input *RPCAuthInput) error {
logger.V(1).Error(err, "failed to get hints for authz policy denial", "error", err)
}
}
logger.Info("authz policy evaluation result", "authorizationResult", result, "input", input, "denialHints", hints)
logger.Info("authz policy evaluation result", "authorizationResult", result, "input", redactedInput, "denialHints", hints)
if !result {
errRegister := recorder.Counter(ctx, authzDeniedPolicyCounter, 1, attribute.String("method", input.Method))
if errRegister != nil {
Expand Down
16 changes: 11 additions & 5 deletions auth/opa/rpcauth/rpcauth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ default allow = false
allow {
input.method = "/Foo.Bar/Baz"
input.type = "Foo.BazRequest"
input.type = "google.protobuf.Empty"
}
allow {
Expand Down Expand Up @@ -164,7 +164,8 @@ func TestAuthzHook(t *testing.T) {
hooks: []RPCAuthzHook{
RPCAuthzHookFunc(func(_ context.Context, input *RPCAuthInput) error {
input.Method = "/Foo.Bar/Baz"
input.MessageType = "Foo.BazRequest"
input.Message = []byte("{}")
input.MessageType = "google.protobuf.Empty"
return nil
}),
},
Expand All @@ -187,10 +188,13 @@ func TestAuthzHook(t *testing.T) {
hooks: []RPCAuthzHook{
RPCAuthzHookFunc(func(_ context.Context, input *RPCAuthInput) error {
input.Method = "/Foo.Bar/Baz"
input.Message = []byte("{}")
input.MessageType = "google.protobuf.Empty"
return nil
}),
RPCAuthzHookFunc(func(_ context.Context, input *RPCAuthInput) error {
input.MessageType = "Foo.BazRequest"
input.Message = []byte("{}")
input.MessageType = "google.protobuf.Empty"
return nil
}),
},
Expand Down Expand Up @@ -249,11 +253,13 @@ func TestAuthzHook(t *testing.T) {
hooks: []RPCAuthzHook{
RPCAuthzHookFunc(func(_ context.Context, input *RPCAuthInput) error {
input.Method = "/Foo.Bar/Baz"
input.MessageType = "Foo.BarRequest"
input.MessageType = "google.protobuf.Empty"
input.Message = []byte("{}")
return nil
}),
RPCAuthzHookFunc(func(_ context.Context, input *RPCAuthInput) error {
input.MessageType = "Foo.BazRequest"
input.MessageType = "google.protobuf.Empty"
input.Message = []byte("{}")
return nil
}),
},
Expand Down
4 changes: 4 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ require (
github.com/open-policy-agent/opa v0.57.0
github.com/pkg/errors v0.9.1
github.com/prometheus/client_golang v1.17.0
github.com/stretchr/testify v1.8.4
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.45.0
go.opentelemetry.io/otel v1.19.0
go.opentelemetry.io/otel/exporters/prometheus v0.42.0
Expand Down Expand Up @@ -65,6 +66,7 @@ require (
github.com/aws/smithy-go v1.13.5 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-ini/ini v1.67.0 // indirect
github.com/gobwas/glob v0.2.3 // indirect
github.com/godbus/dbus/v5 v5.1.0 // indirect
Expand All @@ -82,6 +84,7 @@ require (
github.com/kylelemons/godebug v1.1.0 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_model v0.4.1-0.20230718164431-9a2bf3000d16 // indirect
github.com/prometheus/common v0.44.0 // indirect
github.com/prometheus/procfs v0.11.1 // indirect
Expand All @@ -106,5 +109,6 @@ require (
google.golang.org/genproto/googleapis/api v0.0.0-20230717213848-3f92550aa753 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20230717213848-3f92550aa753 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
sigs.k8s.io/yaml v1.3.0 // indirect
)
Loading

0 comments on commit 0f9d7d7

Please sign in to comment.