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

protovalidate: add option to ignore certain message types #684

Merged
merged 3 commits into from
Jan 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
5 changes: 4 additions & 1 deletion interceptors/protovalidate/example_stream_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ func ExampleStreamServerInterceptor() {
var (
srv = grpc.NewServer(
grpc.StreamInterceptor(
protovalidate_middleware.StreamServerInterceptor(validator),
protovalidate_middleware.StreamServerInterceptor(validator,
protovalidate_middleware.WithIgnoreMessages(
(&testvalidatev1.SendStreamRequest{}).ProtoReflect().Type(),
)),
),
)
svc = &StreamService{}
Expand Down
6 changes: 5 additions & 1 deletion interceptors/protovalidate/example_unary_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@ func ExampleUnaryServerInterceptor() {
var (
srv = grpc.NewServer(
grpc.UnaryInterceptor(
protovalidate_middleware.UnaryServerInterceptor(validator),
protovalidate_middleware.UnaryServerInterceptor(validator,
protovalidate_middleware.WithIgnoreMessages(
(&testvalidatev1.SendRequest{}).ProtoReflect().Type(),
),
),
),
)
svc = &UnaryService{}
Expand Down
41 changes: 41 additions & 0 deletions interceptors/protovalidate/options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright (c) The go-grpc-middleware Authors.
// Licensed under the Apache License 2.0.

// Copyright 2017 David Ackroyd. All Rights Reserved.
// See LICENSE for licensing terms.

package protovalidate

import (
"golang.org/x/exp/slices"
"google.golang.org/protobuf/reflect/protoreflect"
)

type options struct {
ignoreMessages []protoreflect.MessageType
}

// An Option lets you add options to protovalidate interceptors using With* funcs.
type Option func(*options)
johanbrandhorst marked this conversation as resolved.
Show resolved Hide resolved

func evaluateOpts(opts []Option) *options {
optCopy := &options{}
for _, o := range opts {
o(optCopy)
}
return optCopy
}

// WithIgnoreMessages sets the messages that should be ignored by the validator. Use with
// caution and ensure validation is performed elsewhere.
func WithIgnoreMessages(msgs ...protoreflect.MessageType) Option {
return func(o *options) {
o.ignoreMessages = msgs
}
}

func (o *options) shouldIgnoreMessage(m protoreflect.MessageType) bool {
return slices.ContainsFunc(o.ignoreMessages, func(t protoreflect.MessageType) bool {
return m == t
})
}
18 changes: 11 additions & 7 deletions interceptors/protovalidate/protovalidate.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,6 @@ import (
"google.golang.org/protobuf/proto"
)

// Option interface is currently empty and serves as a placeholder for potential future implementations.
// It allows adding new options without breaking existing code.
type Option interface {
unimplemented()
}

// UnaryServerInterceptor returns a new unary server interceptor that validates incoming messages.
func UnaryServerInterceptor(validator *protovalidate.Validator, opts ...Option) grpc.UnaryServerInterceptor {
return func(
Expand All @@ -28,8 +22,12 @@ func UnaryServerInterceptor(validator *protovalidate.Validator, opts ...Option)
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (resp interface{}, err error) {
o := evaluateOpts(opts)
switch msg := req.(type) {
case proto.Message:
if o.shouldIgnoreMessage(msg.ProtoReflect().Type()) {
break
}
if err = validator.Validate(msg); err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
Expand All @@ -54,6 +52,7 @@ func StreamServerInterceptor(validator *protovalidate.Validator, opts ...Option)
wrapped := wrapServerStream(stream)
wrapped.wrappedContext = ctx
wrapped.validator = validator
wrapped.options = evaluateOpts(opts)

return handler(srv, wrapped)
}
Expand All @@ -64,7 +63,11 @@ func (w *wrappedServerStream) RecvMsg(m interface{}) error {
return err
}

if err := w.validator.Validate(m.(proto.Message)); err != nil {
msg := m.(proto.Message)
if w.options.shouldIgnoreMessage(msg.ProtoReflect().Type()) {
return nil
}
if err := w.validator.Validate(msg); err != nil {
return status.Error(codes.InvalidArgument, err.Error())
}

Expand All @@ -78,6 +81,7 @@ type wrappedServerStream struct {
wrappedContext context.Context

validator *protovalidate.Validator
options *options
}

// Context returns the wrapper's WrappedContext, overwriting the nested grpc.ServerStream.Context()
Expand Down
33 changes: 31 additions & 2 deletions interceptors/protovalidate/protovalidate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/grpc/test/bufconn"
"google.golang.org/protobuf/reflect/protoreflect"
)

func TestUnaryServerInterceptor(t *testing.T) {
Expand Down Expand Up @@ -50,6 +51,20 @@ func TestUnaryServerInterceptor(t *testing.T) {
assert.Error(t, err)
assert.Equal(t, codes.InvalidArgument, status.Code(err))
})

interceptor = protovalidate_middleware.UnaryServerInterceptor(validator,
protovalidate_middleware.WithIgnoreMessages(testvalidate.BadUnaryRequest.ProtoReflect().Type()),
)

t.Run("invalid_email_ignored", func(t *testing.T) {
info := &grpc.UnaryServerInfo{
FullMethod: "FakeMethod",
}

resp, err := interceptor(context.TODO(), testvalidate.BadUnaryRequest, info, handler)
assert.Nil(t, err)
assert.Equal(t, resp, "good")
})
}

type server struct {
Expand All @@ -69,15 +84,17 @@ func (g *server) SendStream(

const bufSize = 1024 * 1024

func startGrpcServer(t *testing.T) *grpc.ClientConn {
func startGrpcServer(t *testing.T, ignoreMessages ...protoreflect.MessageType) *grpc.ClientConn {
lis := bufconn.Listen(bufSize)

validator, err := protovalidate.New()
assert.Nil(t, err)

s := grpc.NewServer(
grpc.StreamInterceptor(
protovalidate_middleware.StreamServerInterceptor(validator),
protovalidate_middleware.StreamServerInterceptor(validator,
protovalidate_middleware.WithIgnoreMessages(ignoreMessages...),
),
),
)
testvalidatev1.RegisterTestValidateServiceServer(s, &server{})
Expand Down Expand Up @@ -131,4 +148,16 @@ func TestStreamServerInterceptor(t *testing.T) {
assert.Error(t, err)
assert.Equal(t, codes.InvalidArgument, status.Code(err))
})

t.Run("invalid_email_ignored", func(t *testing.T) {
client := testvalidatev1.NewTestValidateServiceClient(
startGrpcServer(t, testvalidate.BadStreamRequest.ProtoReflect().Type()),
)

out, err := client.SendStream(context.Background(), testvalidate.BadStreamRequest)
assert.Nil(t, err)

_, err = out.Recv()
assert.Nil(t, err)
})
}
Loading