Skip to content

Expand validation to alternate Protobuf implementations - #565

Draft
jonbodner-buf wants to merge 22 commits into
mainfrom
jonbodner-buf/validate-message-plain-values
Draft

jonbodner-buf wants to merge 22 commits into
mainfrom
jonbodner-buf/validate-message-plain-values

Conversation

@jonbodner-buf

@jonbodner-buf jonbodner-buf commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

protovalidate-java only validates messages that use protobuf-java. There are other protobuf implementations for the JVM, including protokt. This PR extends protovalidate-java so it can validate messages from other JVM Protobuf runtimes without converting them to protobuf-java first.

The Validator interface is extended with a new method:

  /**
   * Validates a message provided as a {@link ValidateMessage}. Used by alternative protobuf
   * runtimes that reflect over their own message types via this interface rather than going through
   * a {@link Message}. The default implementation throws {@link ValidationException} when this
   * overload is unsupported.
   *
   * @param message the {@link ValidateMessage} view of the message to validate.
   * @return the {@link ValidationResult} from the evaluation.
   * @throws ValidationException if there are any compilation or validation execution errors.
   */
  default ValidationResult validate(ValidateMessage message) throws ValidationException {
    throw new ValidationException("ValidateMessage validation is unsupported");
  }

To use an alternate protobuf implementation with protovalidate-java, wrap a message in a ValidateMessage instance:

/**
 * {@link ValidateMessage} is a wrapper around a protobuf message that provides reflective access to
 * the underlying message.
 *
 * <p>{@link ValidateMessage} is a runtime-independent interface. Any protobuf runtime that
 * implements this interface can wrap its messages so that protovalidate-java can validate them.
 */
public interface ValidateMessage {
  /**
   * The {@link Descriptor} of the wrapped message's type.
   *
   * @return The descriptor.
   */
  Descriptor getDescriptorForType();

  /**
   * Whether the field is populated. Repeated and map fields are populated when non-empty. Fields
   * with explicit presence are populated when set, including a set default value. Other scalar
   * fields are populated when their value differs from the protobuf default.
   *
   * @param field The field descriptor to check for.
   * @return Whether the field is present.
   */
  boolean hasField(FieldDescriptor field);

  /**
   * Returns the populated member of a oneof, or null when no member is set.
   *
   * @param oneof The oneof to inspect.
   * @return The populated field descriptor, or null.
   */
  default @Nullable FieldDescriptor getOneofFieldDescriptor(OneofDescriptor oneof) {
    for (FieldDescriptor field : oneof.getFields()) {
      if (hasField(field)) {
        return field;
      }
    }
    return null;
  }

  /**
   * Whether the message has no populated fields. Implementations retaining extensions or unknown
   * fields must override this method to include them in the emptiness check.
   *
   * @return Whether the message is empty.
   */
  default boolean isEmpty() {
    for (FieldDescriptor field : getDescriptorForType().getFields()) {
      if (hasField(field)) {
        return false;
      }
    }
    return true;
  }

  /**
   * Returns the plain Java value of a field, or null when the field is unset. The validator
   * substitutes the protobuf default for unset fields and does all conversion for CEL itself.
   *
   * <p>Singular values use these types. Unsigned integers use the signed type with the same bits.
   *
   * <ul>
   *   <li>int32, sint32, sfixed32, uint32, fixed32: {@link Integer}
   *   <li>int64, sint64, sfixed64, uint64, fixed64: {@link Long}
   *   <li>float: {@link Float}; double: {@link Double}; bool: {@link Boolean}
   *   <li>string: {@link String}; bytes: {@link com.google.protobuf.ByteString}
   *   <li>enum: the number as an {@link Integer}
   *   <li>message: a {@link ValidateMessage}
   * </ul>
   *
   * <p>Repeated fields are a {@link java.util.List} of those values, and map fields a {@link
   * java.util.Map}. If a value has a different type, validation fails with an exception that names
   * the field.
   *
   * @param field The field descriptor for which to retrieve a value.
   * @return The field's value, or null when the field is unset.
   */
  @Nullable Object getField(FieldDescriptor field);
}

andrewparmet and others added 12 commits June 14, 2026 11:04
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.
@jonbodner-buf jonbodner-buf changed the title Jonbodner buf/validate message plain values Expand validation to alternate Protobuf implementations Dec 3, 2026
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.
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants