Repository navigation
Expand validation to alternate Protobuf implementations - #565
Draft
jonbodner-buf wants to merge 22 commits into
Draft
jonbodner-buf wants to merge 22 commits into
jonbodner-buf wants to merge 22 commits into
Conversation
Rename the MessageReflector interface to ValidateMessage, and accordingly ProtobufMessageReflector -> ProtobufValidateMessage and MessageReflectorValue -> ValidateMessageValue (with its `reflector` field/locals renamed to `message`). Also give the jvmValue UnsupportedOperationException on the message-backed Value types a descriptive message: MessageValue notes it carries the rule message and should be read via messageValue()/celValue(); the ValidateMessage-backed value notes that a getField() implementation returned a message value for a field evaluated as a scalar.
Add ValidateMessageTest, which validates through a map-backed ValidateMessage (no com.google.protobuf.Message): scalar / nested / repeated / map / repeated-message / map-message violations and their field paths, a valid message, the well-known Timestamp type, bytes, enum, unsigned (uint32), the Int32Value wrapper, a required oneof, the clear error when a message field is not backed by a ValidateMessage, and that jvmValue is unsupported on the message-backed Value types. Co-authored-by: Jon Bodner <jbodner@buf.build>
Exercise successful and failing boolean and string rules through an alternative runtime with native rules enabled and disabled. Document that field and element values must support jvmValue(Object.class), including nested messages.
Keep existing Validator implementations compatible through a default overload. Accept map-backed fields and integer enums, and check message emptiness through ValidateMessage while preserving explicit presence and unknown fields. Document raw and JVM value types and add public-API parity tests in a separate package. Use direct presence and oneof lookups, cache message adapters lazily, and skip zero-value adaptation unless the ignore rule requires it.
Initialize each message adapter in the value constructor so messageValue is a direct accessor and all value fields remain final.
Determine message fields from their descriptors when constructing immutable values, avoiding a Message interface check on every scalar value.
Implementations of ValidateMessage had to build CEL representations themselves: CelByteString and UnsignedLong scalars in Value, and a CEL view of the message in celValue(). That put CEL types in the public API while the POM declares cel as a runtime-only dependency, and the Map view shown in ExternalRuntimeTest makes CEL has() true for unset fields. ValidateMessage.getField now returns plain Java values, or null when the field is unset, and the validator does all CEL conversion internally. Messages are presented to CEL as a StructValue so has() and reads of unset fields match protobuf-java. Value is package-private again, and protobuf-java messages keep their existing evaluation path.
Validating ValidateMessage implementations in place needed a second validation path: a plain-value Value, a CEL struct view, stand-ins for unset messages, and changes to every evaluator. Copying the fields into a DynamicMessage reuses the protobuf-java path instead, so messages from other runtimes get exactly protobuf-java's semantics for has(), defaults, oneofs and well-known types, with far less code. The conversion costs about 1 to 2.5 microseconds per message in a protokt example, which is small next to the network cost of the messages protovalidate usually validates. Wrong value types, null list elements and null map entries fail before validation with an IllegalArgumentException naming the field, and byte[] is accepted for bytes fields. The fix for ignoring zero items of repeated uint32 and uint64 fields is kept.
…icMessage" This reverts commit 4790d27.
A ValidateMessage that returns the wrong Java type for a field failed later with a ClassCastException from a rule evaluator that didn't name the field. Check the type up front and throw an IllegalArgumentException that names the field and the expected type.
CEL unwraps a struct to its value() when the struct ends a select chain, such as an element of a repeated message field. That exposed the raw ValidateMessage, so CEL couldn't select its fields (for example in this.items.all(i, i.name != '')) and compared messages by identity instead of by contents. Return the struct itself from value(), and compare structs by their fields, including against protobuf-java messages. A message literal on the left of == still compares unequal, because cel-java calls the literal's equals.
CEL unpacks Any and reads Struct, Value and ListValue as JSON maps, lists and scalars, but only for protobuf-java messages. A ValidateMessage of one of these types reached CEL as a plain struct, so Any wasn't unpacked, indexing or sizing a Struct or ListValue threw, and Value fields didn't compare equal to their contents. Copy these messages into the generated protobuf-java classes through the wire form when CEL reads them, so CEL applies the same rules as for protobuf-java messages. FieldMask needs no copy, because CEL reads it as an ordinary message.
Several behaviors of ValidateMessages differed from protobuf-java messages: - Unset enum and bytes fields ignored explicit proto2 and editions defaults, using the first enum value and empty bytes instead. - Violations reported singular Timestamp and Duration fields as the ValidateMessage, where protobuf-java reports java.time values. - Comparing a ValidateMessage with a protobuf-java message whose descriptor was another instance of the same type threw. - Map violations came out in a different order on each run, because map values were keyed by identity hashes. protobuf-java messages had the same problem. - repeated.unique treated an enum number given as an Integer and as an EnumValueDescriptor as different values. - A field value of the wrong type escaped validate() as an unchecked IllegalArgumentException when a native rule read it first, and as an ExecutionException when a CEL rule did. It's now always an ExecutionException.
Plain values of the wrong nested message or enum type passed the type check, and rules for the declared type then read them as unset. List and map elements weren't checked at all. CEL rules that read a list inside a comprehension converted it on every read, which is quadratic. Also unwrap wrapper fields when comparing with protobuf-java messages, report whole-list Timestamp and Duration violation values as java.time values, report out-of-range times and failed copies as ExecutionExceptions, and create the ProtobufValidateMessage wrapper only when an evaluator asks for it.
A nested plain message with the right type name but another descriptor instance was read with the parent schema's field descriptors, so a map-backed implementation read every field as unset and rules passed. Equality between a plain message and a DynamicMessage, such as a CEL literal for a runtime-built descriptor, failed when a Timestamp or Duration field was set, because CEL leaves those DynamicMessages unconverted. Also pin that a message literal on the left of == differs from protobuf-java, and stop blaming getField in the jvmValue error for the message being validated.
Conformance only called validate(Message), so the path other runtimes take through plain values was covered only by unit tests. With VALIDATE_MESSAGE=true the runner wraps each case in an adapter over the public ValidateMessage interface, and make conformance runs both.
Equality converted both sides to CEL values, which needed special cases for wrappers, Timestamps and Durations, the source of the last two equality bugs. Comparing getField's plain values recursively treats those as ordinary nested messages. Also replace MessageValue with ValidateMessageValue over a protobuf-java message, and share the Timestamp and Duration conversion in PlainValue.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
protovalidate-javaonly validates messages that use protobuf-java. There are other protobuf implementations for the JVM, including protokt. This PR extendsprotovalidate-javaso it can validate messages from other JVM Protobuf runtimes without converting them to protobuf-java first.The
Validatorinterface is extended with a new method:To use an alternate protobuf implementation with
protovalidate-java, wrap a message in aValidateMessageinstance: