Giter Club home page Giter Club logo

Comments (4)

bhollis avatar bhollis commented on June 26, 2024

Amazing, I just came here to file the exact same request :-)

from protovalidate-go.

kralicky avatar kralicky commented on June 26, 2024

That design ended up having some limitations, notably I needed to be able to access the Env's CELTypeProvider() and CELTypeAdapter() to use custom protobuf message types as function inputs/outputs. The updated implementation is here: kralicky@da6dae8

Here's an example of how I used it:

message X509Certificate {
  bytes                     raw       = 1;
  bool                      isCA      = 2;
  string                    issuer    = 3;
  string                    subject   = 4;
  google.protobuf.Timestamp notBefore = 5;
  google.protobuf.Timestamp notAfter  = 6;
  string                    alg       = 7;
}
protovalidate.New(
  protovalidate.WithExtendFunc(func(e *cel.Env) []cel.EnvOption {
    tr := env.CELTypeProvider().(*types.Registry)
    tr.RegisterMessage(&X509Certificate{})

    return []cel.EnvOption {
      cel.Function("x509Parse",
        cel.Overload("str_parse_x509",
          []*cel.Type{cel.StringType},
          cel.ObjectType(string(proto.MessageName(&X509Certificate{}))),
          cel.UnaryBinding(func(value ref.Val) ref.Val {
            str, ok := value.Value().(string)
            if !ok {
              return types.UnsupportedRefValConversionErr(value)
            }
            block, _ := pem.Decode([]byte(str))
            if block == nil {
              return types.NewErr("malformed PEM block")
            }

            cert, err := x509.ParseCertificate(block.Bytes)
            if err != nil {
              return types.WrapErr(err)
            }
            return env.CELTypeAdapter().NativeToValue(&X509Certificate{
              Raw:       cert.Raw,
              IsCA:      cert.IsCA,
              Issuer:    cert.Issuer.String(),
              Subject:   cert.Subject.String(),
              NotBefore: timestamppb.New(cert.NotBefore),
              NotAfter:  timestamppb.New(cert.NotAfter),
              Alg:       cert.PublicKeyAlgorithm.String(),
            })
          }),
        ),
      ),
    }
  }),
)

Then I can write, for example:

expression: "x509Parse(this.certData).issuer == 'foo'"

or pass it to some other methods:

expression: "x509Parse(this.certData).checkSignatureFrom(x509Parse(this.caCertData))"

from protovalidate-go.

rodaine avatar rodaine commented on June 26, 2024

See #60 for a previous discussion on this topic.

We are not going to expose the CEL environment. The goal of protovalidate is for constraints to be portable across any implementation as the protos where the rules are defined might be run in any context. This means that the only supported custom CEL functions must be part of the protovalidate spec or defined as a custom CEL expression on the message/field itself.

That said, if your validation rule is common enough, we're happy to discuss incorporating it as a standard constraint (a recent example is support for IP/CIDR Prefixes). We're alternatively looking at ways to share/reuse a CEL expression across multiple entities.

As for your certificate example above, perhaps this goes a bit beyond the scope of protovalidate and into actual implementation of your service. I can see an isX509 function to make sure the data is in the correct shape, but actually evaluating the cert data is signed by the CA probably belongs in your business logic.

from protovalidate-go.

kralicky avatar kralicky commented on June 26, 2024

That is disappointing, but understandable I suppose. In my case, I am using protovalidate to standardize validation across a bunch of different APIs, which were previously all doing their own thing slightly differently. This way validations can be performed automatically and have all the context info from the descriptors.

My example code is a bit contrived, yes, and out of scope for any standard validators, but I wanted to give an example that made use of a few different features. The intent was a rigorous sanity-check, not a replacement for real backend logic, of course. 😉

from protovalidate-go.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.