Skip to content

Commit

Permalink
feature: add option to extend CEL environment
Browse files Browse the repository at this point in the history
  • Loading branch information
Igor Tsiglyar committed Apr 16, 2024
1 parent 8f25afb commit e599e8d
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
9 changes: 8 additions & 1 deletion proto/tests/example/v1/example.proto
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,14 @@ package tests.example.v1;
import "buf/validate/validate.proto";

message Person {
uint64 id = 1 [(buf.validate.field).uint64.gt = 999];
uint64 id = 1 [
(buf.validate.field).cel = {
id: "person.id",
expression:
"this <= PersonMinId"
"? 'value must be greater than %s'.format([PersonMinId]) : ''"
}
];

string email = 2 [(buf.validate.field).string.email = true];

Expand Down
15 changes: 15 additions & 0 deletions validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"github.com/bufbuild/protovalidate-go/internal/errors"
"github.com/bufbuild/protovalidate-go/internal/evaluator"
"github.com/bufbuild/protovalidate-go/resolver"
"github.com/google/cel-go/cel"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
)
Expand Down Expand Up @@ -70,6 +71,12 @@ func New(options ...ValidatorOption) (*Validator, error) {
"failed to construct CEL environment: %w", err)
}

env, err = env.Extend(cfg.celEnvOpts...)
if err != nil {
return nil, fmt.Errorf(
"failed to extend CEL environment: %w", err)
}

bldr := evaluator.NewBuilder(
env,
cfg.disableLazy,
Expand Down Expand Up @@ -104,6 +111,7 @@ type config struct {
disableLazy bool
desc []protoreflect.MessageDescriptor
resolver StandardConstraintResolver
celEnvOpts []cel.EnvOption
}

// A ValidatorOption modifies the default configuration of a Validator. See the
Expand Down Expand Up @@ -183,3 +191,10 @@ func WithStandardConstraintInterceptor(interceptor StandardConstraintInterceptor
c.resolver = interceptor(c.resolver)
}
}

// WithExtendedCelEnv allows to extend CEL environment used for validation with user provided options
func WithExtendedCelEnv(celEnvOpts ...cel.EnvOption) ValidatorOption {
return func(cfg *config) {
cfg.celEnvOpts = celEnvOpts
}
}
10 changes: 9 additions & 1 deletion validator_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,19 @@ import (
"log"

pb "github.com/bufbuild/protovalidate-go/internal/gen/tests/example/v1"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/common/types"
"google.golang.org/protobuf/reflect/protoregistry"
)

var (
PersonMinId = 999
)

func Example() {
validator, err := New()
validator, err := New(WithExtendedCelEnv(
cel.Constant("PersonMinId", cel.UintType, types.Uint(PersonMinId)),
))
if err != nil {
log.Fatal(err)
}
Expand Down

0 comments on commit e599e8d

Please sign in to comment.