From 5624a945dcd861d13fcbadf45e729b987e66f75d Mon Sep 17 00:00:00 2001 From: Andrew Parmet Date: Sun, 14 Jun 2026 11:04:12 -0400 Subject: [PATCH 01/23] Introduce MessageReflector to enable alternative protobuf runtimes --- .../build/buf/protovalidate/AnyEvaluator.java | 5 +- .../build/buf/protovalidate/CelPrograms.java | 2 +- .../buf/protovalidate/EnumEvaluator.java | 2 +- .../buf/protovalidate/FieldEvaluator.java | 15 +++-- .../buf/protovalidate/ListElementValue.java | 11 +++- .../build/buf/protovalidate/MapEvaluator.java | 8 +-- .../protovalidate/MessageOneofEvaluator.java | 2 +- .../buf/protovalidate/MessageReflector.java | 59 +++++++++++++++++ .../protovalidate/MessageReflectorValue.java | 66 +++++++++++++++++++ .../build/buf/protovalidate/MessageValue.java | 18 +++-- .../build/buf/protovalidate/ObjectValue.java | 14 +++- .../buf/protovalidate/OneofEvaluator.java | 9 ++- .../ProtobufMessageReflector.java | 51 ++++++++++++++ .../buf/protovalidate/RuleViolation.java | 2 +- .../build/buf/protovalidate/Validator.java | 11 ++++ .../buf/protovalidate/ValidatorImpl.java | 14 +++- .../java/build/buf/protovalidate/Value.java | 39 ++++++----- .../buf/protovalidate/ValueEvaluator.java | 2 +- .../protovalidate/WrappedValueEvaluator.java | 9 ++- 19 files changed, 280 insertions(+), 59 deletions(-) create mode 100644 src/main/java/build/buf/protovalidate/MessageReflector.java create mode 100644 src/main/java/build/buf/protovalidate/MessageReflectorValue.java create mode 100644 src/main/java/build/buf/protovalidate/ProtobufMessageReflector.java diff --git a/src/main/java/build/buf/protovalidate/AnyEvaluator.java b/src/main/java/build/buf/protovalidate/AnyEvaluator.java index d7d18356d..450a555fa 100644 --- a/src/main/java/build/buf/protovalidate/AnyEvaluator.java +++ b/src/main/java/build/buf/protovalidate/AnyEvaluator.java @@ -19,7 +19,6 @@ import build.buf.validate.FieldPath; import build.buf.validate.FieldRules; import com.google.protobuf.Descriptors; -import com.google.protobuf.Message; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; @@ -78,12 +77,12 @@ final class AnyEvaluator implements Evaluator { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - Message anyValue = val.messageValue(); + MessageReflector anyValue = val.messageValue(); if (anyValue == null) { return RuleViolation.NO_VIOLATIONS; } List violationList = new ArrayList<>(); - String typeURL = (String) anyValue.getField(typeURLDescriptor); + String typeURL = anyValue.getField(typeURLDescriptor).jvmValue(String.class); if (!in.isEmpty() && !in.contains(typeURL)) { RuleViolation.Builder violation = RuleViolation.newBuilder() diff --git a/src/main/java/build/buf/protovalidate/CelPrograms.java b/src/main/java/build/buf/protovalidate/CelPrograms.java index ed712f796..f88e56035 100644 --- a/src/main/java/build/buf/protovalidate/CelPrograms.java +++ b/src/main/java/build/buf/protovalidate/CelPrograms.java @@ -45,7 +45,7 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - CelVariableResolver bindings = Variable.newThisVariable(val.value(Object.class)); + CelVariableResolver bindings = Variable.newThisVariable(val.celValue()); List violations = new ArrayList<>(); for (CompiledProgram program : programs) { RuleViolation.Builder violation = program.eval(val, bindings); diff --git a/src/main/java/build/buf/protovalidate/EnumEvaluator.java b/src/main/java/build/buf/protovalidate/EnumEvaluator.java index d2fa00df4..52f6e1bb1 100644 --- a/src/main/java/build/buf/protovalidate/EnumEvaluator.java +++ b/src/main/java/build/buf/protovalidate/EnumEvaluator.java @@ -77,7 +77,7 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - Object enumValue = val.value(Object.class); + Long enumValue = val.jvmValue(Long.class); if (enumValue == null) { return RuleViolation.NO_VIOLATIONS; } diff --git a/src/main/java/build/buf/protovalidate/FieldEvaluator.java b/src/main/java/build/buf/protovalidate/FieldEvaluator.java index 877aec5ea..26533f547 100644 --- a/src/main/java/build/buf/protovalidate/FieldEvaluator.java +++ b/src/main/java/build/buf/protovalidate/FieldEvaluator.java @@ -19,7 +19,6 @@ import build.buf.validate.FieldRules; import build.buf.validate.Ignore; import com.google.protobuf.Descriptors.FieldDescriptor; -import com.google.protobuf.Message; import java.util.Collections; import java.util.List; @@ -95,7 +94,7 @@ public List evaluate(Value val, boolean failFast) if (this.shouldIgnoreAlways()) { return RuleViolation.NO_VIOLATIONS; } - Message message = val.messageValue(); + MessageReflector message = val.messageValue(); if (message == null) { return RuleViolation.NO_VIOLATIONS; } @@ -113,17 +112,19 @@ public List evaluate(Value val, boolean failFast) if (this.shouldIgnoreEmpty() && !hasField) { return RuleViolation.NO_VIOLATIONS; } - return valueEvaluator.evaluate( - new ObjectValue(descriptor, message.getField(descriptor)), failFast); + return valueEvaluator.evaluate(message.getField(descriptor), failFast); } /** * Returns whether the given field is set on the message. Handles repeated and map fields, which - * are not supported by {@link Message#hasField}. + * require inspecting the list/map contents rather than a presence bit. */ - static boolean isFieldSet(Message message, FieldDescriptor field) { + static boolean isFieldSet(MessageReflector message, FieldDescriptor field) { if (field.isRepeated()) { - return message.getRepeatedFieldCount(field) != 0; + if (field.isMapField()) { + return !message.getField(field).mapValue().isEmpty(); + } + return !message.getField(field).repeatedValue().isEmpty(); } return message.hasField(field); } diff --git a/src/main/java/build/buf/protovalidate/ListElementValue.java b/src/main/java/build/buf/protovalidate/ListElementValue.java index 8e397d328..848cfbf92 100644 --- a/src/main/java/build/buf/protovalidate/ListElementValue.java +++ b/src/main/java/build/buf/protovalidate/ListElementValue.java @@ -45,15 +45,20 @@ final class ListElementValue implements Value { } @Override - public @Nullable Message messageValue() { + public @Nullable MessageReflector messageValue() { if (fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { - return (Message) value; + return new ProtobufMessageReflector((Message) value); } return null; } @Override - public T value(Class clazz) { + public Object celValue() { + return ProtoAdapter.scalarToCel(fieldDescriptor.getType(), value); + } + + @Override + public T jvmValue(Class clazz) { Descriptors.FieldDescriptor.Type type = fieldDescriptor.getType(); if (type == Descriptors.FieldDescriptor.Type.MESSAGE) { return clazz.cast(value); diff --git a/src/main/java/build/buf/protovalidate/MapEvaluator.java b/src/main/java/build/buf/protovalidate/MapEvaluator.java index bc418e977..0dfcecbfb 100644 --- a/src/main/java/build/buf/protovalidate/MapEvaluator.java +++ b/src/main/java/build/buf/protovalidate/MapEvaluator.java @@ -155,19 +155,19 @@ private List evalPairs(Value key, Value value, boolean fa case TYPE_SINT64: case TYPE_SFIXED32: case TYPE_SFIXED64: - fieldPathElementBuilder.setIntKey(key.value(Number.class).longValue()); + fieldPathElementBuilder.setIntKey(key.jvmValue(Number.class).longValue()); break; case TYPE_UINT32: case TYPE_UINT64: case TYPE_FIXED32: case TYPE_FIXED64: - fieldPathElementBuilder.setUintKey(key.value(Number.class).longValue()); + fieldPathElementBuilder.setUintKey(key.jvmValue(Number.class).longValue()); break; case TYPE_BOOL: - fieldPathElementBuilder.setBoolKey(key.value(Boolean.class)); + fieldPathElementBuilder.setBoolKey(key.jvmValue(Boolean.class)); break; case TYPE_STRING: - fieldPathElementBuilder.setStringKey(key.value(String.class)); + fieldPathElementBuilder.setStringKey(key.jvmValue(String.class)); break; default: throw new ExecutionException("Unexpected map key type"); diff --git a/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java b/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java index aecce4e92..3b68fb5f5 100644 --- a/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java +++ b/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java @@ -45,7 +45,7 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - Message msg = val.messageValue(); + MessageReflector msg = val.messageValue(); if (msg == null) { return RuleViolation.NO_VIOLATIONS; } diff --git a/src/main/java/build/buf/protovalidate/MessageReflector.java b/src/main/java/build/buf/protovalidate/MessageReflector.java new file mode 100644 index 000000000..99da86c08 --- /dev/null +++ b/src/main/java/build/buf/protovalidate/MessageReflector.java @@ -0,0 +1,59 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; + +/** + * {@link MessageReflector} is a wrapper around a protobuf message that provides reflective access + * to the underlying message. + * + *

{@link MessageReflector} 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 MessageReflector { + /** + * The {@link Descriptor} of the wrapped message's type. + * + * @return The descriptor. + */ + Descriptor getDescriptorForType(); + + /** + * Whether the wrapped message has the field described by the provided field descriptor. + * + * @param field The field descriptor to check for. + * @return Whether the field is present. + */ + boolean hasField(FieldDescriptor field); + + /** + * Get the value described by the provided field descriptor. + * + * @param field The field descriptor for which to retrieve a value. + * @return The value corresponding to the field descriptor. + */ + Value getField(FieldDescriptor field); + + /** + * Returns the representation of this message to hand to CEL for {@code this}-variable rule + * evaluation. Implementations return whichever form CEL can navigate for their runtime, such as + * a {@link com.google.protobuf.Message} or a {@code dev.cel.common.values.CelValue}. + * + * @return The CEL-navigable representation of this message. + */ + Object celValue(); +} diff --git a/src/main/java/build/buf/protovalidate/MessageReflectorValue.java b/src/main/java/build/buf/protovalidate/MessageReflectorValue.java new file mode 100644 index 000000000..555943edf --- /dev/null +++ b/src/main/java/build/buf/protovalidate/MessageReflectorValue.java @@ -0,0 +1,66 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import com.google.protobuf.Descriptors; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import org.jspecify.annotations.Nullable; + +/** Top-level {@link Value} backed by a user-supplied {@link MessageReflector}. */ +final class MessageReflectorValue implements Value { + + private final MessageReflector reflector; + + MessageReflectorValue(MessageReflector reflector) { + this.reflector = reflector; + } + + @Override + public Descriptors.@Nullable FieldDescriptor fieldDescriptor() { + return null; + } + + @Override + public MessageReflector messageValue() { + return reflector; + } + + @Override + public Object rawValue() { + return reflector; + } + + @Override + public Object celValue() { + return reflector.celValue(); + } + + @Override + public T jvmValue(Class clazz) { + throw new UnsupportedOperationException(); + } + + @Override + public List repeatedValue() { + return Collections.emptyList(); + } + + @Override + public Map mapValue() { + return Collections.emptyMap(); + } +} diff --git a/src/main/java/build/buf/protovalidate/MessageValue.java b/src/main/java/build/buf/protovalidate/MessageValue.java index fa96e3b8c..9d5cf2c55 100644 --- a/src/main/java/build/buf/protovalidate/MessageValue.java +++ b/src/main/java/build/buf/protovalidate/MessageValue.java @@ -24,8 +24,7 @@ /** The {@link Value} type that contains a {@link com.google.protobuf.Message}. */ final class MessageValue implements Value { - /** Object type since the object type is inferred from the field descriptor. */ - private final Object value; + private final ProtobufMessageReflector value; /** * Constructs a {@link MessageValue} with the provided message value. @@ -33,7 +32,7 @@ final class MessageValue implements Value { * @param value The message value. */ MessageValue(Message value) { - this.value = value; + this.value = new ProtobufMessageReflector(value); } @Override @@ -42,13 +41,18 @@ final class MessageValue implements Value { } @Override - public Message messageValue() { - return (Message) value; + public MessageReflector messageValue() { + return value; + } + + @Override + public Object celValue() { + return value.getMessage(); } @Override - public T value(Class clazz) { - return clazz.cast(value); + public T jvmValue(Class clazz) { + throw new UnsupportedOperationException(); } @Override diff --git a/src/main/java/build/buf/protovalidate/ObjectValue.java b/src/main/java/build/buf/protovalidate/ObjectValue.java index 9a53574ac..2b01a6938 100644 --- a/src/main/java/build/buf/protovalidate/ObjectValue.java +++ b/src/main/java/build/buf/protovalidate/ObjectValue.java @@ -53,15 +53,23 @@ public Descriptors.FieldDescriptor fieldDescriptor() { @Nullable @Override - public Message messageValue() { + public MessageReflector messageValue() { if (fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { - return (Message) value; + return new ProtobufMessageReflector((Message) value); } return null; } @Override - public T value(Class clazz) { + public Object celValue() { + return ProtoAdapter.toCel(fieldDescriptor, value); + } + + @Override + public T jvmValue(Class clazz) { + if (value instanceof Descriptors.EnumValueDescriptor) { + return clazz.cast((long) ((Descriptors.EnumValueDescriptor) value).getNumber()); + } return clazz.cast(ProtoAdapter.toCel(fieldDescriptor, value)); } diff --git a/src/main/java/build/buf/protovalidate/OneofEvaluator.java b/src/main/java/build/buf/protovalidate/OneofEvaluator.java index 5ddccd6d6..c45611e88 100644 --- a/src/main/java/build/buf/protovalidate/OneofEvaluator.java +++ b/src/main/java/build/buf/protovalidate/OneofEvaluator.java @@ -17,7 +17,6 @@ import build.buf.protovalidate.exceptions.ExecutionException; import build.buf.validate.FieldPathElement; import com.google.protobuf.Descriptors.OneofDescriptor; -import com.google.protobuf.Message; import java.util.Collections; import java.util.List; @@ -48,8 +47,12 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - Message message = val.messageValue(); - if (message == null || !required || (message.getOneofFieldDescriptor(descriptor) != null)) { + MessageReflector message = val.messageValue(); + if (message == null) { + return RuleViolation.NO_VIOLATIONS; + } + boolean hasField = descriptor.getFields().stream().anyMatch(message::hasField); + if (!required || hasField) { return RuleViolation.NO_VIOLATIONS; } return Collections.singletonList( diff --git a/src/main/java/build/buf/protovalidate/ProtobufMessageReflector.java b/src/main/java/build/buf/protovalidate/ProtobufMessageReflector.java new file mode 100644 index 000000000..75f7c46d6 --- /dev/null +++ b/src/main/java/build/buf/protovalidate/ProtobufMessageReflector.java @@ -0,0 +1,51 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Message; + +class ProtobufMessageReflector implements MessageReflector { + private final Message message; + + ProtobufMessageReflector(Message message) { + this.message = message; + } + + public Message getMessage() { + return message; + } + + @Override + public Descriptor getDescriptorForType() { + return message.getDescriptorForType(); + } + + @Override + public boolean hasField(FieldDescriptor field) { + return message.hasField(field); + } + + @Override + public Value getField(FieldDescriptor field) { + return new ObjectValue(field, message.getField(field)); + } + + @Override + public Object celValue() { + return message; + } +} diff --git a/src/main/java/build/buf/protovalidate/RuleViolation.java b/src/main/java/build/buf/protovalidate/RuleViolation.java index 454d2f782..39d18930d 100644 --- a/src/main/java/build/buf/protovalidate/RuleViolation.java +++ b/src/main/java/build/buf/protovalidate/RuleViolation.java @@ -55,7 +55,7 @@ static class FieldValue implements Violation.FieldValue { * @param value A {@link Value} to create this {@link FieldValue} from. */ FieldValue(Value value) { - this.value = value.value(Object.class); + this.value = value.jvmValue(Object.class); this.descriptor = Objects.requireNonNull(value.fieldDescriptor()); } diff --git a/src/main/java/build/buf/protovalidate/Validator.java b/src/main/java/build/buf/protovalidate/Validator.java index 449abef73..f0571971f 100644 --- a/src/main/java/build/buf/protovalidate/Validator.java +++ b/src/main/java/build/buf/protovalidate/Validator.java @@ -35,4 +35,15 @@ public interface Validator { * @throws ValidationException if there are any compilation or validation execution errors. */ ValidationResult validate(Message msg) throws ValidationException; + + /** + * Validates a message provided as a {@link MessageReflector}. Used by alternative protobuf + * runtimes that reflect over their own message types via this interface rather than going + * through a {@link Message}. + * + * @param message the {@link MessageReflector} view of the message to validate. + * @return the {@link ValidationResult} from the evaluation. + * @throws ValidationException if there are any compilation or validation execution errors. + */ + ValidationResult validate(MessageReflector message) throws ValidationException; } diff --git a/src/main/java/build/buf/protovalidate/ValidatorImpl.java b/src/main/java/build/buf/protovalidate/ValidatorImpl.java index 39613c9f8..7911545d0 100644 --- a/src/main/java/build/buf/protovalidate/ValidatorImpl.java +++ b/src/main/java/build/buf/protovalidate/ValidatorImpl.java @@ -48,9 +48,17 @@ public ValidationResult validate(Message msg) throws ValidationException { if (msg == null) { return ValidationResult.EMPTY; } - Descriptor descriptor = msg.getDescriptorForType(); - Evaluator evaluator = evaluatorBuilder.load(descriptor); - List result = evaluator.evaluate(new MessageValue(msg), this.failFast); + return validate(new ProtobufMessageReflector(msg)); + } + + @Override + public ValidationResult validate(MessageReflector message) throws ValidationException { + if (message == null) { + return ValidationResult.EMPTY; + } + Evaluator evaluator = evaluatorBuilder.load(message.getDescriptorForType()); + List result = + evaluator.evaluate(new MessageReflectorValue(message), this.failFast); if (result.isEmpty()) { return ValidationResult.EMPTY; } diff --git a/src/main/java/build/buf/protovalidate/Value.java b/src/main/java/build/buf/protovalidate/Value.java index a2bb96b29..385778928 100644 --- a/src/main/java/build/buf/protovalidate/Value.java +++ b/src/main/java/build/buf/protovalidate/Value.java @@ -15,7 +15,6 @@ package build.buf.protovalidate; import com.google.protobuf.Descriptors; -import com.google.protobuf.Message; import java.util.List; import java.util.Map; import org.jspecify.annotations.Nullable; @@ -24,7 +23,7 @@ * {@link Value} is a wrapper around a protobuf value that provides helper methods for accessing the * value. */ -interface Value { +public interface Value { /** * Get the field descriptor that corresponds to the underlying Value, if it is a message field. * @@ -34,26 +33,17 @@ interface Value { Descriptors.@Nullable FieldDescriptor fieldDescriptor(); /** - * Get the underlying value as a {@link Message} type. + * Get the underlying value as a {@link MessageReflector} type. * - * @return The underlying {@link Message} value. null if the underlying value is not a {@link - * Message} type. + * @return The underlying {@link MessageReflector} value. null if the underlying value is not a {@link + * MessageReflector} type. */ - @Nullable Message messageValue(); - - /** - * Get the underlying value and cast it to the class type. - * - * @param clazz The inferred class. - * @return The value casted to the inferred class type. - * @param The class type. - */ - T value(Class clazz); + @Nullable MessageReflector messageValue(); /** * Returns the underlying protobuf Java value without any CEL-specific adaptation. * - *

{@link #value(Class)} routes scalars through {@code ProtoAdapter.toCel}, which converts + *

{@link #jvmValue(Class)} routes scalars through {@code ProtoAdapter.toCel}, which converts * {@code int32→Long}, {@code uint32→UnsignedLong}, {@code float→Double}, {@code bytes→ * CelByteString}, etc. — appropriate for the CEL evaluation path but lossy for native rule * evaluators that compare against raw protobuf field values. Native evaluators in {@code @@ -81,4 +71,21 @@ interface Value { * list. */ Map mapValue(); + + /** + * Get the underlying value as it should be provided to CEL. + * + * @return The underlying value as a CEL-compatible type. + */ + Object celValue(); + + /** + * Get the underlying value and cast it to the class type, which will be a type checkable + * internally by protovalidate-java. + * + * @param clazz The inferred class. + * @return The value cast to the inferred class type. + * @param The class type. + */ + T jvmValue(Class clazz); } diff --git a/src/main/java/build/buf/protovalidate/ValueEvaluator.java b/src/main/java/build/buf/protovalidate/ValueEvaluator.java index 433da1c40..2408b0049 100644 --- a/src/main/java/build/buf/protovalidate/ValueEvaluator.java +++ b/src/main/java/build/buf/protovalidate/ValueEvaluator.java @@ -71,7 +71,7 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - if (this.shouldIgnore(val.value(Object.class))) { + if (this.shouldIgnore(val.jvmValue(Object.class))) { return RuleViolation.NO_VIOLATIONS; } List allViolations = new ArrayList<>(); diff --git a/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java b/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java index 6cba9a242..39395df55 100644 --- a/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java +++ b/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java @@ -16,7 +16,6 @@ import build.buf.protovalidate.exceptions.ExecutionException; import com.google.protobuf.Descriptors.FieldDescriptor; -import com.google.protobuf.Message; import java.util.List; /** @@ -26,7 +25,7 @@ * *

CEL's runtime auto-unwraps wrappers to their inner primitive type, so the CEL path doesn't * need this adapter. Native evaluators expect the underlying scalar (e.g. {@code Long} for {@code - * Int64Value.value}); without unwrapping they'd see the wrapper {@link Message} and misbehave. + * Int64Value.value}); without unwrapping they'd see the wrapper message and misbehave. * Mirrors {@code wrappedValueEval} in protovalidate-go's {@code builder.go}. * *

The wrapped evaluator's {@link RuleBase} is constructed against the OUTER wrapper field's @@ -58,12 +57,12 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - Message message = val.messageValue(); + MessageReflector message = val.messageValue(); if (message == null) { // proto3 message-typed field absent — no value to validate. return RuleViolation.NO_VIOLATIONS; } - Object innerValue = message.getField(innerField); - return inner.evaluate(new ObjectValue(innerField, innerValue), failFast); + Value innerValue = message.getField(innerField); + return inner.evaluate(innerValue, failFast); } } From 37883086e10e99db8d1d11c55e03c9cb695d4f19 Mon Sep 17 00:00:00 2001 From: Andrew Parmet Date: Wed, 17 Jun 2026 12:24:39 -0400 Subject: [PATCH 02/23] Apply spotless formatting --- src/main/java/build/buf/protovalidate/ListElementValue.java | 2 +- .../java/build/buf/protovalidate/MessageOneofEvaluator.java | 1 - src/main/java/build/buf/protovalidate/MessageReflector.java | 4 ++-- src/main/java/build/buf/protovalidate/MessageValue.java | 2 +- src/main/java/build/buf/protovalidate/ObjectValue.java | 2 +- src/main/java/build/buf/protovalidate/OneofEvaluator.java | 2 +- src/main/java/build/buf/protovalidate/Validator.java | 4 ++-- src/main/java/build/buf/protovalidate/Value.java | 4 ++-- .../java/build/buf/protovalidate/WrappedValueEvaluator.java | 4 ++-- 9 files changed, 12 insertions(+), 13 deletions(-) diff --git a/src/main/java/build/buf/protovalidate/ListElementValue.java b/src/main/java/build/buf/protovalidate/ListElementValue.java index 848cfbf92..1c350e3d4 100644 --- a/src/main/java/build/buf/protovalidate/ListElementValue.java +++ b/src/main/java/build/buf/protovalidate/ListElementValue.java @@ -54,7 +54,7 @@ final class ListElementValue implements Value { @Override public Object celValue() { - return ProtoAdapter.scalarToCel(fieldDescriptor.getType(), value); + return ProtoAdapter.scalarToCel(fieldDescriptor.getType(), value); } @Override diff --git a/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java b/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java index 3b68fb5f5..c0b12d705 100644 --- a/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java +++ b/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java @@ -16,7 +16,6 @@ import build.buf.protovalidate.exceptions.ExecutionException; import com.google.protobuf.Descriptors.FieldDescriptor; -import com.google.protobuf.Message; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; diff --git a/src/main/java/build/buf/protovalidate/MessageReflector.java b/src/main/java/build/buf/protovalidate/MessageReflector.java index 99da86c08..6f20d9a1f 100644 --- a/src/main/java/build/buf/protovalidate/MessageReflector.java +++ b/src/main/java/build/buf/protovalidate/MessageReflector.java @@ -50,8 +50,8 @@ public interface MessageReflector { /** * Returns the representation of this message to hand to CEL for {@code this}-variable rule - * evaluation. Implementations return whichever form CEL can navigate for their runtime, such as - * a {@link com.google.protobuf.Message} or a {@code dev.cel.common.values.CelValue}. + * evaluation. Implementations return whichever form CEL can navigate for their runtime, such as a + * {@link com.google.protobuf.Message} or a {@code dev.cel.common.values.CelValue}. * * @return The CEL-navigable representation of this message. */ diff --git a/src/main/java/build/buf/protovalidate/MessageValue.java b/src/main/java/build/buf/protovalidate/MessageValue.java index 9d5cf2c55..1069c4167 100644 --- a/src/main/java/build/buf/protovalidate/MessageValue.java +++ b/src/main/java/build/buf/protovalidate/MessageValue.java @@ -47,7 +47,7 @@ public MessageReflector messageValue() { @Override public Object celValue() { - return value.getMessage(); + return value.getMessage(); } @Override diff --git a/src/main/java/build/buf/protovalidate/ObjectValue.java b/src/main/java/build/buf/protovalidate/ObjectValue.java index 2b01a6938..00ac8f63c 100644 --- a/src/main/java/build/buf/protovalidate/ObjectValue.java +++ b/src/main/java/build/buf/protovalidate/ObjectValue.java @@ -62,7 +62,7 @@ public MessageReflector messageValue() { @Override public Object celValue() { - return ProtoAdapter.toCel(fieldDescriptor, value); + return ProtoAdapter.toCel(fieldDescriptor, value); } @Override diff --git a/src/main/java/build/buf/protovalidate/OneofEvaluator.java b/src/main/java/build/buf/protovalidate/OneofEvaluator.java index c45611e88..a7274f8dc 100644 --- a/src/main/java/build/buf/protovalidate/OneofEvaluator.java +++ b/src/main/java/build/buf/protovalidate/OneofEvaluator.java @@ -49,7 +49,7 @@ public List evaluate(Value val, boolean failFast) throws ExecutionException { MessageReflector message = val.messageValue(); if (message == null) { - return RuleViolation.NO_VIOLATIONS; + return RuleViolation.NO_VIOLATIONS; } boolean hasField = descriptor.getFields().stream().anyMatch(message::hasField); if (!required || hasField) { diff --git a/src/main/java/build/buf/protovalidate/Validator.java b/src/main/java/build/buf/protovalidate/Validator.java index f0571971f..a9d4c2837 100644 --- a/src/main/java/build/buf/protovalidate/Validator.java +++ b/src/main/java/build/buf/protovalidate/Validator.java @@ -38,8 +38,8 @@ public interface Validator { /** * Validates a message provided as a {@link MessageReflector}. Used by alternative protobuf - * runtimes that reflect over their own message types via this interface rather than going - * through a {@link Message}. + * runtimes that reflect over their own message types via this interface rather than going through + * a {@link Message}. * * @param message the {@link MessageReflector} view of the message to validate. * @return the {@link ValidationResult} from the evaluation. diff --git a/src/main/java/build/buf/protovalidate/Value.java b/src/main/java/build/buf/protovalidate/Value.java index 385778928..5980b4107 100644 --- a/src/main/java/build/buf/protovalidate/Value.java +++ b/src/main/java/build/buf/protovalidate/Value.java @@ -35,8 +35,8 @@ public interface Value { /** * Get the underlying value as a {@link MessageReflector} type. * - * @return The underlying {@link MessageReflector} value. null if the underlying value is not a {@link - * MessageReflector} type. + * @return The underlying {@link MessageReflector} value. null if the underlying value is not a + * {@link MessageReflector} type. */ @Nullable MessageReflector messageValue(); diff --git a/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java b/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java index 39395df55..c97965c3d 100644 --- a/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java +++ b/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java @@ -25,8 +25,8 @@ * *

CEL's runtime auto-unwraps wrappers to their inner primitive type, so the CEL path doesn't * need this adapter. Native evaluators expect the underlying scalar (e.g. {@code Long} for {@code - * Int64Value.value}); without unwrapping they'd see the wrapper message and misbehave. - * Mirrors {@code wrappedValueEval} in protovalidate-go's {@code builder.go}. + * Int64Value.value}); without unwrapping they'd see the wrapper message and misbehave. Mirrors + * {@code wrappedValueEval} in protovalidate-go's {@code builder.go}. * *

The wrapped evaluator's {@link RuleBase} is constructed against the OUTER wrapper field's * {@code ValueEvaluator}, so violation field paths point at the user's wrapper-typed field rather From ce25bd7a5b41bd52036eb54395c4943c0f79c6b9 Mon Sep 17 00:00:00 2001 From: Andrew Parmet Date: Wed, 17 Jun 2026 23:15:42 -0400 Subject: [PATCH 03/23] Rename MessageReflector to ValidateMessage 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. --- .../build/buf/protovalidate/AnyEvaluator.java | 2 +- .../buf/protovalidate/FieldEvaluator.java | 4 ++-- .../buf/protovalidate/ListElementValue.java | 4 ++-- .../protovalidate/MessageOneofEvaluator.java | 2 +- .../build/buf/protovalidate/MessageValue.java | 10 ++++---- .../build/buf/protovalidate/ObjectValue.java | 4 ++-- .../buf/protovalidate/OneofEvaluator.java | 2 +- ...ctor.java => ProtobufValidateMessage.java} | 4 ++-- ...ageReflector.java => ValidateMessage.java} | 8 +++---- ...orValue.java => ValidateMessageValue.java} | 23 +++++++++++-------- .../build/buf/protovalidate/Validator.java | 6 ++--- .../buf/protovalidate/ValidatorImpl.java | 6 ++--- .../java/build/buf/protovalidate/Value.java | 8 +++---- .../protovalidate/WrappedValueEvaluator.java | 2 +- 14 files changed, 45 insertions(+), 40 deletions(-) rename src/main/java/build/buf/protovalidate/{ProtobufMessageReflector.java => ProtobufValidateMessage.java} (92%) rename src/main/java/build/buf/protovalidate/{MessageReflector.java => ValidateMessage.java} (87%) rename src/main/java/build/buf/protovalidate/{MessageReflectorValue.java => ValidateMessageValue.java} (65%) diff --git a/src/main/java/build/buf/protovalidate/AnyEvaluator.java b/src/main/java/build/buf/protovalidate/AnyEvaluator.java index 450a555fa..c79b55113 100644 --- a/src/main/java/build/buf/protovalidate/AnyEvaluator.java +++ b/src/main/java/build/buf/protovalidate/AnyEvaluator.java @@ -77,7 +77,7 @@ final class AnyEvaluator implements Evaluator { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - MessageReflector anyValue = val.messageValue(); + ValidateMessage anyValue = val.messageValue(); if (anyValue == null) { return RuleViolation.NO_VIOLATIONS; } diff --git a/src/main/java/build/buf/protovalidate/FieldEvaluator.java b/src/main/java/build/buf/protovalidate/FieldEvaluator.java index 26533f547..3c88eb8a9 100644 --- a/src/main/java/build/buf/protovalidate/FieldEvaluator.java +++ b/src/main/java/build/buf/protovalidate/FieldEvaluator.java @@ -94,7 +94,7 @@ public List evaluate(Value val, boolean failFast) if (this.shouldIgnoreAlways()) { return RuleViolation.NO_VIOLATIONS; } - MessageReflector message = val.messageValue(); + ValidateMessage message = val.messageValue(); if (message == null) { return RuleViolation.NO_VIOLATIONS; } @@ -119,7 +119,7 @@ public List evaluate(Value val, boolean failFast) * Returns whether the given field is set on the message. Handles repeated and map fields, which * require inspecting the list/map contents rather than a presence bit. */ - static boolean isFieldSet(MessageReflector message, FieldDescriptor field) { + static boolean isFieldSet(ValidateMessage message, FieldDescriptor field) { if (field.isRepeated()) { if (field.isMapField()) { return !message.getField(field).mapValue().isEmpty(); diff --git a/src/main/java/build/buf/protovalidate/ListElementValue.java b/src/main/java/build/buf/protovalidate/ListElementValue.java index 1c350e3d4..ffe11f7e7 100644 --- a/src/main/java/build/buf/protovalidate/ListElementValue.java +++ b/src/main/java/build/buf/protovalidate/ListElementValue.java @@ -45,9 +45,9 @@ final class ListElementValue implements Value { } @Override - public @Nullable MessageReflector messageValue() { + public @Nullable ValidateMessage messageValue() { if (fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { - return new ProtobufMessageReflector((Message) value); + return new ProtobufValidateMessage((Message) value); } return null; } diff --git a/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java b/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java index c0b12d705..1613be48e 100644 --- a/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java +++ b/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java @@ -44,7 +44,7 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - MessageReflector msg = val.messageValue(); + ValidateMessage msg = val.messageValue(); if (msg == null) { return RuleViolation.NO_VIOLATIONS; } diff --git a/src/main/java/build/buf/protovalidate/MessageValue.java b/src/main/java/build/buf/protovalidate/MessageValue.java index 1069c4167..08012a36a 100644 --- a/src/main/java/build/buf/protovalidate/MessageValue.java +++ b/src/main/java/build/buf/protovalidate/MessageValue.java @@ -24,7 +24,7 @@ /** The {@link Value} type that contains a {@link com.google.protobuf.Message}. */ final class MessageValue implements Value { - private final ProtobufMessageReflector value; + private final ProtobufValidateMessage value; /** * Constructs a {@link MessageValue} with the provided message value. @@ -32,7 +32,7 @@ final class MessageValue implements Value { * @param value The message value. */ MessageValue(Message value) { - this.value = new ProtobufMessageReflector(value); + this.value = new ProtobufValidateMessage(value); } @Override @@ -41,7 +41,7 @@ final class MessageValue implements Value { } @Override - public MessageReflector messageValue() { + public ValidateMessage messageValue() { return value; } @@ -52,7 +52,9 @@ public Object celValue() { @Override public T jvmValue(Class clazz) { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException( + "jvmValue returns a raw scalar for native rule evaluation and is not supported on a message" + + " value; use messageValue() or celValue() instead"); } @Override diff --git a/src/main/java/build/buf/protovalidate/ObjectValue.java b/src/main/java/build/buf/protovalidate/ObjectValue.java index 00ac8f63c..b7c29d0cc 100644 --- a/src/main/java/build/buf/protovalidate/ObjectValue.java +++ b/src/main/java/build/buf/protovalidate/ObjectValue.java @@ -53,9 +53,9 @@ public Descriptors.FieldDescriptor fieldDescriptor() { @Nullable @Override - public MessageReflector messageValue() { + public ValidateMessage messageValue() { if (fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { - return new ProtobufMessageReflector((Message) value); + return new ProtobufValidateMessage((Message) value); } return null; } diff --git a/src/main/java/build/buf/protovalidate/OneofEvaluator.java b/src/main/java/build/buf/protovalidate/OneofEvaluator.java index a7274f8dc..7dc091883 100644 --- a/src/main/java/build/buf/protovalidate/OneofEvaluator.java +++ b/src/main/java/build/buf/protovalidate/OneofEvaluator.java @@ -47,7 +47,7 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - MessageReflector message = val.messageValue(); + ValidateMessage message = val.messageValue(); if (message == null) { return RuleViolation.NO_VIOLATIONS; } diff --git a/src/main/java/build/buf/protovalidate/ProtobufMessageReflector.java b/src/main/java/build/buf/protovalidate/ProtobufValidateMessage.java similarity index 92% rename from src/main/java/build/buf/protovalidate/ProtobufMessageReflector.java rename to src/main/java/build/buf/protovalidate/ProtobufValidateMessage.java index 75f7c46d6..6d21dd513 100644 --- a/src/main/java/build/buf/protovalidate/ProtobufMessageReflector.java +++ b/src/main/java/build/buf/protovalidate/ProtobufValidateMessage.java @@ -18,10 +18,10 @@ import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Message; -class ProtobufMessageReflector implements MessageReflector { +class ProtobufValidateMessage implements ValidateMessage { private final Message message; - ProtobufMessageReflector(Message message) { + ProtobufValidateMessage(Message message) { this.message = message; } diff --git a/src/main/java/build/buf/protovalidate/MessageReflector.java b/src/main/java/build/buf/protovalidate/ValidateMessage.java similarity index 87% rename from src/main/java/build/buf/protovalidate/MessageReflector.java rename to src/main/java/build/buf/protovalidate/ValidateMessage.java index 6f20d9a1f..b637fe674 100644 --- a/src/main/java/build/buf/protovalidate/MessageReflector.java +++ b/src/main/java/build/buf/protovalidate/ValidateMessage.java @@ -18,13 +18,13 @@ import com.google.protobuf.Descriptors.FieldDescriptor; /** - * {@link MessageReflector} is a wrapper around a protobuf message that provides reflective access - * to the underlying message. + * {@link ValidateMessage} is a wrapper around a protobuf message that provides reflective access to + * the underlying message. * - *

{@link MessageReflector} is a runtime-independent interface. Any protobuf runtime that + *

{@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 MessageReflector { +public interface ValidateMessage { /** * The {@link Descriptor} of the wrapped message's type. * diff --git a/src/main/java/build/buf/protovalidate/MessageReflectorValue.java b/src/main/java/build/buf/protovalidate/ValidateMessageValue.java similarity index 65% rename from src/main/java/build/buf/protovalidate/MessageReflectorValue.java rename to src/main/java/build/buf/protovalidate/ValidateMessageValue.java index 555943edf..1fe8ed8ca 100644 --- a/src/main/java/build/buf/protovalidate/MessageReflectorValue.java +++ b/src/main/java/build/buf/protovalidate/ValidateMessageValue.java @@ -20,13 +20,13 @@ import java.util.Map; import org.jspecify.annotations.Nullable; -/** Top-level {@link Value} backed by a user-supplied {@link MessageReflector}. */ -final class MessageReflectorValue implements Value { +/** Top-level {@link Value} backed by a user-supplied {@link ValidateMessage}. */ +final class ValidateMessageValue implements Value { - private final MessageReflector reflector; + private final ValidateMessage message; - MessageReflectorValue(MessageReflector reflector) { - this.reflector = reflector; + ValidateMessageValue(ValidateMessage message) { + this.message = message; } @Override @@ -35,23 +35,26 @@ final class MessageReflectorValue implements Value { } @Override - public MessageReflector messageValue() { - return reflector; + public ValidateMessage messageValue() { + return message; } @Override public Object rawValue() { - return reflector; + return message; } @Override public Object celValue() { - return reflector.celValue(); + return message.celValue(); } @Override public T jvmValue(Class clazz) { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException( + "jvmValue returns a raw scalar for native rule evaluation and is not supported on a message" + + " value; a ValidateMessage.getField() implementation returned a message value for a" + + " field evaluated as a scalar"); } @Override diff --git a/src/main/java/build/buf/protovalidate/Validator.java b/src/main/java/build/buf/protovalidate/Validator.java index a9d4c2837..31ba0a48a 100644 --- a/src/main/java/build/buf/protovalidate/Validator.java +++ b/src/main/java/build/buf/protovalidate/Validator.java @@ -37,13 +37,13 @@ public interface Validator { ValidationResult validate(Message msg) throws ValidationException; /** - * Validates a message provided as a {@link MessageReflector}. Used by alternative protobuf + * 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}. * - * @param message the {@link MessageReflector} view of the message to validate. + * @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. */ - ValidationResult validate(MessageReflector message) throws ValidationException; + ValidationResult validate(ValidateMessage message) throws ValidationException; } diff --git a/src/main/java/build/buf/protovalidate/ValidatorImpl.java b/src/main/java/build/buf/protovalidate/ValidatorImpl.java index 7911545d0..8c0f408ae 100644 --- a/src/main/java/build/buf/protovalidate/ValidatorImpl.java +++ b/src/main/java/build/buf/protovalidate/ValidatorImpl.java @@ -48,17 +48,17 @@ public ValidationResult validate(Message msg) throws ValidationException { if (msg == null) { return ValidationResult.EMPTY; } - return validate(new ProtobufMessageReflector(msg)); + return validate(new ProtobufValidateMessage(msg)); } @Override - public ValidationResult validate(MessageReflector message) throws ValidationException { + public ValidationResult validate(ValidateMessage message) throws ValidationException { if (message == null) { return ValidationResult.EMPTY; } Evaluator evaluator = evaluatorBuilder.load(message.getDescriptorForType()); List result = - evaluator.evaluate(new MessageReflectorValue(message), this.failFast); + evaluator.evaluate(new ValidateMessageValue(message), this.failFast); if (result.isEmpty()) { return ValidationResult.EMPTY; } diff --git a/src/main/java/build/buf/protovalidate/Value.java b/src/main/java/build/buf/protovalidate/Value.java index 5980b4107..296113e66 100644 --- a/src/main/java/build/buf/protovalidate/Value.java +++ b/src/main/java/build/buf/protovalidate/Value.java @@ -33,12 +33,12 @@ public interface Value { Descriptors.@Nullable FieldDescriptor fieldDescriptor(); /** - * Get the underlying value as a {@link MessageReflector} type. + * Get the underlying value as a {@link ValidateMessage} type. * - * @return The underlying {@link MessageReflector} value. null if the underlying value is not a - * {@link MessageReflector} type. + * @return The underlying {@link ValidateMessage} value. null if the underlying value is not a + * {@link ValidateMessage} type. */ - @Nullable MessageReflector messageValue(); + @Nullable ValidateMessage messageValue(); /** * Returns the underlying protobuf Java value without any CEL-specific adaptation. diff --git a/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java b/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java index c97965c3d..5dab7e67c 100644 --- a/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java +++ b/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java @@ -57,7 +57,7 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - MessageReflector message = val.messageValue(); + ValidateMessage message = val.messageValue(); if (message == null) { // proto3 message-typed field absent — no value to validate. return RuleViolation.NO_VIOLATIONS; From 2d39522ab8e91cdd390f70f73896897f82e947ab Mon Sep 17 00:00:00 2001 From: Andrew Parmet Date: Wed, 17 Jun 2026 23:15:56 -0400 Subject: [PATCH 04/23] Add ValidateMessage coverage tests 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 --- .../protovalidate/ValidateMessageTest.java | 1052 +++++++++++++++++ 1 file changed, 1052 insertions(+) create mode 100644 src/test/java/build/buf/protovalidate/ValidateMessageTest.java diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java new file mode 100644 index 000000000..059222520 --- /dev/null +++ b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java @@ -0,0 +1,1052 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import build.buf.validate.FieldPathElement; +import build.buf.validate.FieldRules; +import build.buf.validate.Int32Rules; +import build.buf.validate.MapRules; +import build.buf.validate.MessageRules; +import build.buf.validate.RepeatedRules; +import build.buf.validate.Rule; +import build.buf.validate.StringRules; +import build.buf.validate.TimestampRules; +import build.buf.validate.ValidateProto; +import com.google.protobuf.DescriptorProtos.DescriptorProto; +import com.google.protobuf.DescriptorProtos.FieldDescriptorProto; +import com.google.protobuf.DescriptorProtos.FieldOptions; +import com.google.protobuf.DescriptorProtos.FileDescriptorProto; +import com.google.protobuf.DescriptorProtos.MessageOptions; +import com.google.protobuf.Descriptors; +import com.google.protobuf.Timestamp; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import org.jspecify.annotations.Nullable; +import org.junit.jupiter.api.Test; + +/** + * Exercises {@link Validator#validate(ValidateMessage)} with an alternative-runtime {@link + * ValidateMessage} backed by a plain map of field values, so the interface is covered without a + * {@code com.google.protobuf.Message}. + */ +public class ValidateMessageTest { + @Test + public void violations() throws Exception { + // "Person" has two scalar fields with buf.validate.field rules and a + // message-level buf.validate.message CEL rule. + Descriptors.Descriptor descriptor = buildPersonDescriptor(); + + // name "ab" violates the field rule (min_len = 3); age 200 satisfies the field + // rule (gte = 0) but violates the message-level CEL rule (this.age <= 150). + Descriptors.Descriptor addressDescriptor = + descriptor.findFieldByName("address").getMessageType(); + ValidateMessage message = + person(descriptor, "ab", 200, address(addressDescriptor, "Main Street")); + Validator validator = ValidatorFactory.newBuilder().build(); + ValidationResult result = validator.validate(message); + + assertThat(result.getViolations()).hasSize(2); + assertThat(result.getViolations()) + .extracting(violation -> violation.toProto().getRuleId()) + .containsExactlyInAnyOrder("string.min_len", "person.age_range"); + } + + @Test + public void nestedViolation() throws Exception { + Descriptors.Descriptor descriptor = buildPersonDescriptor(); + + // Person is valid, but the nested Address.street violates its own min_len rule. + Descriptors.Descriptor addressDescriptor = + descriptor.findFieldByName("address").getMessageType(); + ValidateMessage message = person(descriptor, "alice", 30, address(addressDescriptor, "x")); + Validator validator = ValidatorFactory.newBuilder().build(); + ValidationResult result = validator.validate(message); + + assertThat(result.getViolations()).hasSize(1); + assertThat(result.getViolations().get(0).toProto().getRuleId()).isEqualTo("string.min_len"); + // The violation path is reported relative to the root message: address.street. + List fieldPath = + result.getViolations().get(0).toProto().getField().getElementsList().stream() + .map(FieldPathElement::getFieldName) + .collect(Collectors.toList()); + assertThat(fieldPath).containsExactly("address", "street"); + } + + @Test + public void valid() throws Exception { + Descriptors.Descriptor descriptor = buildPersonDescriptor(); + + // Satisfies every rule: name long enough, age in [0, 150], street long enough. + Descriptors.Descriptor addressDescriptor = + descriptor.findFieldByName("address").getMessageType(); + ValidateMessage message = + person(descriptor, "alice", 30, address(addressDescriptor, "Main Street")); + Validator validator = ValidatorFactory.newBuilder().build(); + ValidationResult result = validator.validate(message); + + assertThat(result.getViolations()).isEmpty(); + } + + @Test + public void repeatedViolation() throws Exception { + Descriptors.Descriptor descriptor = buildPersonDescriptor(); + Descriptors.Descriptor addressDescriptor = + descriptor.findFieldByName("address").getMessageType(); + + // nicknames = ["jo", "x"]; the second element "x" violates the items min_len = 2. + Map fields = + personFields(descriptor, "alice", 30, address(addressDescriptor, "Main Street")); + fields.put(descriptor.findFieldByName("nicknames"), Arrays.asList("jo", "x")); + ValidateMessage message = new MapValidateMessage(descriptor, fields); + + ValidationResult result = ValidatorFactory.newBuilder().build().validate(message); + + assertThat(result.getViolations()).hasSize(1); + assertThat(result.getViolations().get(0).toProto().getRuleId()).isEqualTo("string.min_len"); + // The violation path points at the offending element: nicknames[1]. + FieldPathElement element = result.getViolations().get(0).toProto().getField().getElements(0); + assertThat(element.getFieldName()).isEqualTo("nicknames"); + assertThat(element.getIndex()).isEqualTo(1); + } + + @Test + public void mapViolation() throws Exception { + Descriptors.Descriptor descriptor = buildPersonDescriptor(); + Descriptors.Descriptor addressDescriptor = + descriptor.findFieldByName("address").getMessageType(); + + // scores = {"math": 90, "art": -5}; the "art" value violates values gte = 0. + Map scores = new LinkedHashMap<>(); + scores.put("math", 90); + scores.put("art", -5); + Map fields = + personFields(descriptor, "alice", 30, address(addressDescriptor, "Main Street")); + fields.put(descriptor.findFieldByName("scores"), scores); + ValidateMessage message = new MapValidateMessage(descriptor, fields); + + ValidationResult result = ValidatorFactory.newBuilder().build().validate(message); + + assertThat(result.getViolations()).hasSize(1); + assertThat(result.getViolations().get(0).toProto().getRuleId()).isEqualTo("int32.gte"); + // The violation path points at the offending entry: scores["art"]. + FieldPathElement element = result.getViolations().get(0).toProto().getField().getElements(0); + assertThat(element.getFieldName()).isEqualTo("scores"); + assertThat(element.getStringKey()).isEqualTo("art"); + } + + @Test + public void repeatedMessageViolation() throws Exception { + Descriptors.Descriptor descriptor = buildPersonDescriptor(); + Descriptors.Descriptor addressDescriptor = + descriptor.findFieldByName("address").getMessageType(); + + // previous_addresses = [Address("Main Street"), Address("x")]; the second element's + // street violates min_len = 4, reached through a repeated message element. + Map fields = + personFields(descriptor, "alice", 30, address(addressDescriptor, "Main Street")); + fields.put( + descriptor.findFieldByName("previous_addresses"), + Arrays.asList(address(addressDescriptor, "Main Street"), address(addressDescriptor, "x"))); + ValidateMessage message = new MapValidateMessage(descriptor, fields); + + ValidationResult result = ValidatorFactory.newBuilder().build().validate(message); + + assertThat(result.getViolations()).hasSize(1); + assertThat(result.getViolations().get(0).toProto().getRuleId()).isEqualTo("string.min_len"); + List path = + result.getViolations().get(0).toProto().getField().getElementsList(); + assertThat(path) + .extracting(FieldPathElement::getFieldName) + .containsExactly("previous_addresses", "street"); + // The element index is carried on the repeated field path element. + assertThat(path.get(0).getIndex()).isEqualTo(1); + } + + @Test + public void mapMessageViolation() throws Exception { + Descriptors.Descriptor descriptor = buildPersonDescriptor(); + Descriptors.Descriptor addressDescriptor = + descriptor.findFieldByName("address").getMessageType(); + + // homes = {"primary": Address("x")}; the value message's street violates min_len = 4, + // reached through a map value message. + Map homes = new LinkedHashMap<>(); + homes.put("primary", address(addressDescriptor, "x")); + Map fields = + personFields(descriptor, "alice", 30, address(addressDescriptor, "Main Street")); + fields.put(descriptor.findFieldByName("homes"), homes); + ValidateMessage message = new MapValidateMessage(descriptor, fields); + + ValidationResult result = ValidatorFactory.newBuilder().build().validate(message); + + assertThat(result.getViolations()).hasSize(1); + assertThat(result.getViolations().get(0).toProto().getRuleId()).isEqualTo("string.min_len"); + List path = + result.getViolations().get(0).toProto().getField().getElementsList(); + assertThat(path).extracting(FieldPathElement::getFieldName).containsExactly("homes", "street"); + // The map key is carried on the map field path element. + assertThat(path.get(0).getStringKey()).isEqualTo("primary"); + } + + @Test + public void messageFieldRequiresValidateMessage() throws Exception { + Descriptors.Descriptor descriptor = buildPersonDescriptor(); + Descriptors.Descriptor addressDescriptor = + descriptor.findFieldByName("address").getMessageType(); + + // A singular message field stored as a non-ValidateMessage value is rejected with a clear + // error, rather than failing later as an opaque ClassCastException. + Map fields = + personFields(descriptor, "alice", 30, address(addressDescriptor, "Main Street")); + fields.put(descriptor.findFieldByName("address"), "not a ValidateMessage"); + ValidateMessage message = new MapValidateMessage(descriptor, fields); + + Validator validator = ValidatorFactory.newBuilder().build(); + assertThatThrownBy(() -> validator.validate(message)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("address") + .hasMessageContaining("ValidateMessage"); + } + + @Test + public void messageValueJvmValueUnsupported() throws Exception { + // A message has no raw scalar form, so jvmValue is unsupported on a message-backed Value. + Descriptors.Descriptor descriptor = buildPersonDescriptor(); + Descriptors.Descriptor addressDescriptor = + descriptor.findFieldByName("address").getMessageType(); + + Value messageValue = new ValidateMessageValue(address(addressDescriptor, "Main Street")); + assertThatThrownBy(() -> messageValue.jvmValue(Object.class)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("jvmValue returns a raw scalar for native rule evaluation") + .hasMessageContaining("not supported on a message value") + .hasMessageContaining("ValidateMessage.getField() implementation returned a message value"); + + Value protobufMessageValue = new MessageValue(Timestamp.getDefaultInstance()); + assertThatThrownBy(() -> protobufMessageValue.jvmValue(Object.class)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("jvmValue returns a raw scalar for native rule evaluation") + .hasMessageContaining("not supported on a message value") + .hasMessageContaining("use messageValue() or celValue() instead"); + } + + @Test + public void wellKnownTypeTimestamp() throws Exception { + Descriptors.Descriptor descriptor = buildEventDescriptor(); + Validator validator = ValidatorFactory.newBuilder().build(); + + // created_at is exposed as a ValidateMessage over google.protobuf.Timestamp, whose celValue() + // surfaces a java.time.Instant. The standard timestamp.lt rule ("this >= rules.lt") can now + // evaluate against it. rules.lt is seconds=1_000_000_000. + + // After the lt bound -> violation. + Map late = new HashMap<>(); + late.put( + descriptor.findFieldByName("created_at"), timestampMessage(descriptor, 2_000_000_000L)); + ValidationResult lateResult = validator.validate(new MapValidateMessage(descriptor, late)); + assertThat(lateResult.getViolations()).hasSize(1); + assertThat(lateResult.getViolations().get(0).toProto().getRuleId()).isEqualTo("timestamp.lt"); + + // Before the lt bound -> valid. + Map early = new HashMap<>(); + early.put(descriptor.findFieldByName("created_at"), timestampMessage(descriptor, 0L)); + ValidationResult earlyResult = validator.validate(new MapValidateMessage(descriptor, early)); + assertThat(earlyResult.getViolations()).isEmpty(); + } + + @Test + public void bytesViolation() throws Exception { + Descriptors.Descriptor descriptor = buildScalarsDescriptor(); + + // data = two bytes; violates the field rule (bytes min_len = 3). + Map fields = new HashMap<>(); + fields.put( + descriptor.findFieldByName("data"), + com.google.protobuf.ByteString.copyFrom(new byte[] {1, 2})); + ValidationResult result = + ValidatorFactory.newBuilder().build().validate(new MapValidateMessage(descriptor, fields)); + + assertThat(result.getViolations()).hasSize(1); + assertThat(result.getViolations().get(0).toProto().getRuleId()).isEqualTo("bytes.min_len"); + } + + @Test + public void enumViolation() throws Exception { + Descriptors.Descriptor descriptor = buildScalarsDescriptor(); + + // color = RED (0); violates the field rule (enum const = GREEN). + Map fields = new HashMap<>(); + Descriptors.EnumDescriptor color = descriptor.findFieldByName("color").getEnumType(); + fields.put(descriptor.findFieldByName("color"), color.findValueByNumber(0)); + ValidationResult result = + ValidatorFactory.newBuilder().build().validate(new MapValidateMessage(descriptor, fields)); + + assertThat(result.getViolations()).hasSize(1); + assertThat(result.getViolations().get(0).toProto().getRuleId()).isEqualTo("enum.const"); + } + + @Test + public void unsignedViolation() throws Exception { + Descriptors.Descriptor descriptor = buildScalarsDescriptor(); + + // count = 5; violates the field rule (uint32 gt = 10). + Map fields = new HashMap<>(); + fields.put(descriptor.findFieldByName("count"), 5); + ValidationResult result = + ValidatorFactory.newBuilder().build().validate(new MapValidateMessage(descriptor, fields)); + + assertThat(result.getViolations()).hasSize(1); + assertThat(result.getViolations().get(0).toProto().getRuleId()).isEqualTo("uint32.gt"); + } + + @Test + public void wrapperViolation() throws Exception { + Descriptors.Descriptor descriptor = buildScalarsDescriptor(); + + // wrapped = Int32Value(0); the inner value violates the field rule (int32 gt = 0). + Descriptors.Descriptor wrapperDescriptor = + descriptor.findFieldByName("wrapped").getMessageType(); + Map wrapperFields = new HashMap<>(); + wrapperFields.put(wrapperDescriptor.findFieldByName("value"), 0); + Map fields = new HashMap<>(); + fields.put( + descriptor.findFieldByName("wrapped"), + new MapValidateMessage(wrapperDescriptor, wrapperFields)); + ValidationResult result = + ValidatorFactory.newBuilder().build().validate(new MapValidateMessage(descriptor, fields)); + + assertThat(result.getViolations()).hasSize(1); + assertThat(result.getViolations().get(0).toProto().getRuleId()).isEqualTo("int32.gt"); + } + + @Test + public void oneofRequiredViolation() throws Exception { + Descriptors.Descriptor descriptor = buildOneofDescriptor(); + + // The "choice" oneof is required, but no member is set. + ValidationResult result = + ValidatorFactory.newBuilder() + .build() + .validate(new MapValidateMessage(descriptor, new HashMap<>())); + + assertThat(result.getViolations()).hasSize(1); + assertThat(result.getViolations().get(0).toProto().getRuleId()).isEqualTo("required"); + assertThat(result.getViolations().get(0).toProto().getField().getElements(0).getFieldName()) + .isEqualTo("choice"); + } + + /** Builds a {@link MapValidateMessage} for the "Person" message type. */ + private static MapValidateMessage person( + Descriptors.Descriptor descriptor, String name, int age, ValidateMessage address) { + return new MapValidateMessage(descriptor, personFields(descriptor, name, age, address)); + } + + /** Builds the field-value map for a "Person", which tests can extend with optional fields. */ + private static Map personFields( + Descriptors.Descriptor descriptor, String name, int age, ValidateMessage address) { + Map fields = new HashMap<>(); + fields.put(descriptor.findFieldByName("name"), name); + fields.put(descriptor.findFieldByName("age"), age); + fields.put(descriptor.findFieldByName("address"), address); + return fields; + } + + /** Builds a {@link MapValidateMessage} for the "Address" message type. */ + private static MapValidateMessage address( + Descriptors.Descriptor addressDescriptor, String street) { + Map fields = new HashMap<>(); + fields.put(addressDescriptor.findFieldByName("street"), street); + return new MapValidateMessage(addressDescriptor, fields); + } + + /** + * Builds the "Person" {@link Descriptors.Descriptor} at runtime by assembling a {@link + * FileDescriptorProto}. Field rules are attached via the {@code buf.validate.field} extension, a + * message-level CEL rule via {@code buf.validate.message}, and a nested {@code Address} message + * carries its own field rule. + */ + private static Descriptors.Descriptor buildPersonDescriptor() throws Exception { + DescriptorProto address = + DescriptorProto.newBuilder() + .setName("Address") + .addField( + FieldDescriptorProto.newBuilder() + .setName("street") + .setNumber(1) + .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) + .setType(FieldDescriptorProto.Type.TYPE_STRING) + .setOptions(stringMinLen(4))) + .build(); + + DescriptorProto person = + DescriptorProto.newBuilder() + .setName("Person") + .setOptions( + MessageOptions.newBuilder() + .setExtension( + ValidateProto.message, + MessageRules.newBuilder() + .addCel( + Rule.newBuilder() + .setId("person.age_range") + .setMessage("age must be at most 150") + .setExpression("this.age <= 150")) + .build())) + .addField( + FieldDescriptorProto.newBuilder() + .setName("name") + .setNumber(1) + .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) + .setType(FieldDescriptorProto.Type.TYPE_STRING) + .setOptions(stringMinLen(3))) + .addField( + FieldDescriptorProto.newBuilder() + .setName("age") + .setNumber(2) + .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) + .setType(FieldDescriptorProto.Type.TYPE_INT32) + .setOptions( + FieldOptions.newBuilder() + .setExtension( + ValidateProto.field, + FieldRules.newBuilder() + .setInt32(Int32Rules.newBuilder().setGte(0)) + .build()))) + .addField( + FieldDescriptorProto.newBuilder() + .setName("address") + .setNumber(3) + .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) + .setType(FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".example.Address")) + // repeated string nicknames, where each element must have min_len 2. + .addField( + FieldDescriptorProto.newBuilder() + .setName("nicknames") + .setNumber(4) + .setLabel(FieldDescriptorProto.Label.LABEL_REPEATED) + .setType(FieldDescriptorProto.Type.TYPE_STRING) + .setOptions( + fieldRule( + FieldRules.newBuilder() + .setRepeated( + RepeatedRules.newBuilder() + .setItems( + FieldRules.newBuilder() + .setString( + StringRules.newBuilder().setMinLen(2))))))) + // map scores, where each value must be gte 0. + .addField( + FieldDescriptorProto.newBuilder() + .setName("scores") + .setNumber(5) + .setLabel(FieldDescriptorProto.Label.LABEL_REPEATED) + .setType(FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".example.Person.ScoresEntry") + .setOptions( + fieldRule( + FieldRules.newBuilder() + .setMap( + MapRules.newBuilder() + .setValues( + FieldRules.newBuilder() + .setInt32(Int32Rules.newBuilder().setGte(0))))))) + // repeated Address previous_addresses; each element is recursively validated. + .addField( + FieldDescriptorProto.newBuilder() + .setName("previous_addresses") + .setNumber(6) + .setLabel(FieldDescriptorProto.Label.LABEL_REPEATED) + .setType(FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".example.Address")) + // map homes; each value message is recursively validated. + .addField( + FieldDescriptorProto.newBuilder() + .setName("homes") + .setNumber(7) + .setLabel(FieldDescriptorProto.Label.LABEL_REPEATED) + .setType(FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".example.Person.HomesEntry")) + // The synthetic map-entry type that a map field expands to. + .addNestedType( + DescriptorProto.newBuilder() + .setName("ScoresEntry") + .setOptions(MessageOptions.newBuilder().setMapEntry(true)) + .addField( + FieldDescriptorProto.newBuilder() + .setName("key") + .setNumber(1) + .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) + .setType(FieldDescriptorProto.Type.TYPE_STRING)) + .addField( + FieldDescriptorProto.newBuilder() + .setName("value") + .setNumber(2) + .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) + .setType(FieldDescriptorProto.Type.TYPE_INT32))) + // The synthetic map-entry type for map homes. + .addNestedType( + DescriptorProto.newBuilder() + .setName("HomesEntry") + .setOptions(MessageOptions.newBuilder().setMapEntry(true)) + .addField( + FieldDescriptorProto.newBuilder() + .setName("key") + .setNumber(1) + .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) + .setType(FieldDescriptorProto.Type.TYPE_STRING)) + .addField( + FieldDescriptorProto.newBuilder() + .setName("value") + .setNumber(2) + .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) + .setType(FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".example.Address"))) + .build(); + + FileDescriptorProto file = + FileDescriptorProto.newBuilder() + .setName("person.proto") + .setSyntax("proto2") + .setPackage("example") + .addMessageType(address) + .addMessageType(person) + .build(); + + Descriptors.FileDescriptor fileDescriptor = + Descriptors.FileDescriptor.buildFrom(file, new Descriptors.FileDescriptor[] {}); + return fileDescriptor.findMessageTypeByName("Person"); + } + + /** + * Builds an "Event" descriptor with a {@code google.protobuf.Timestamp created_at} field carrying + * a {@code timestamp.lt} rule. Depends on the real {@code timestamp.proto} file descriptor. + */ + private static Descriptors.Descriptor buildEventDescriptor() throws Exception { + DescriptorProto event = + DescriptorProto.newBuilder() + .setName("Event") + .addField( + FieldDescriptorProto.newBuilder() + .setName("created_at") + .setNumber(1) + .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) + .setType(FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".google.protobuf.Timestamp") + .setOptions( + fieldRule( + FieldRules.newBuilder() + .setTimestamp( + TimestampRules.newBuilder() + .setLt(Timestamp.newBuilder().setSeconds(1_000_000_000)))))) + .build(); + + FileDescriptorProto file = + FileDescriptorProto.newBuilder() + .setName("event.proto") + .setSyntax("proto2") + .setPackage("example") + .addDependency("google/protobuf/timestamp.proto") + .addMessageType(event) + .build(); + + Descriptors.FileDescriptor fileDescriptor = + Descriptors.FileDescriptor.buildFrom( + file, new Descriptors.FileDescriptor[] {Timestamp.getDescriptor().getFile()}); + return fileDescriptor.findMessageTypeByName("Event"); + } + + /** + * Builds a "Scalars" descriptor exercising bytes, enum, uint32, a {@code + * google.protobuf.Int32Value} wrapper field, and a required oneof, each carrying a rule. + */ + private static Descriptors.Descriptor buildScalarsDescriptor() throws Exception { + com.google.protobuf.DescriptorProtos.EnumDescriptorProto color = + com.google.protobuf.DescriptorProtos.EnumDescriptorProto.newBuilder() + .setName("Color") + .addValue( + com.google.protobuf.DescriptorProtos.EnumValueDescriptorProto.newBuilder() + .setName("RED") + .setNumber(0)) + .addValue( + com.google.protobuf.DescriptorProtos.EnumValueDescriptorProto.newBuilder() + .setName("GREEN") + .setNumber(1)) + .build(); + + DescriptorProto scalars = + DescriptorProto.newBuilder() + .setName("Scalars") + .addEnumType(color) + // bytes data with bytes.min_len = 3. + .addField( + FieldDescriptorProto.newBuilder() + .setName("data") + .setNumber(1) + .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) + .setType(FieldDescriptorProto.Type.TYPE_BYTES) + .setOptions( + fieldRule( + FieldRules.newBuilder() + .setBytes( + build.buf.validate.BytesRules.newBuilder().setMinLen(3))))) + // enum color with enum.const = 1 (GREEN). + .addField( + FieldDescriptorProto.newBuilder() + .setName("color") + .setNumber(2) + .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) + .setType(FieldDescriptorProto.Type.TYPE_ENUM) + .setTypeName(".example.Scalars.Color") + .setOptions( + fieldRule( + FieldRules.newBuilder() + .setEnum(build.buf.validate.EnumRules.newBuilder().setConst(1))))) + // uint32 count with uint32.gt = 10. + .addField( + FieldDescriptorProto.newBuilder() + .setName("count") + .setNumber(3) + .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) + .setType(FieldDescriptorProto.Type.TYPE_UINT32) + .setOptions( + fieldRule( + FieldRules.newBuilder() + .setUint32(build.buf.validate.UInt32Rules.newBuilder().setGt(10))))) + // google.protobuf.Int32Value wrapped with int32.gt = 0 on its inner value. + .addField( + FieldDescriptorProto.newBuilder() + .setName("wrapped") + .setNumber(4) + .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) + .setType(FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".google.protobuf.Int32Value") + .setOptions( + fieldRule( + FieldRules.newBuilder().setInt32(Int32Rules.newBuilder().setGt(0))))) + .build(); + + FileDescriptorProto file = + FileDescriptorProto.newBuilder() + .setName("scalars.proto") + .setSyntax("proto2") + .setPackage("example") + .addDependency("google/protobuf/wrappers.proto") + .addMessageType(scalars) + .build(); + + Descriptors.FileDescriptor fileDescriptor = + Descriptors.FileDescriptor.buildFrom( + file, + new Descriptors.FileDescriptor[] { + com.google.protobuf.Int32Value.getDescriptor().getFile() + }); + return fileDescriptor.findMessageTypeByName("Scalars"); + } + + /** Builds a "Choice" descriptor with a required {@code oneof choice { string a; string b; }}. */ + private static Descriptors.Descriptor buildOneofDescriptor() throws Exception { + DescriptorProto choice = + DescriptorProto.newBuilder() + .setName("Choice") + .addOneofDecl( + com.google.protobuf.DescriptorProtos.OneofDescriptorProto.newBuilder() + .setName("choice") + .setOptions( + com.google.protobuf.DescriptorProtos.OneofOptions.newBuilder() + .setExtension( + ValidateProto.oneof, + build.buf.validate.OneofRules.newBuilder() + .setRequired(true) + .build()))) + .addField( + FieldDescriptorProto.newBuilder() + .setName("a") + .setNumber(1) + .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) + .setType(FieldDescriptorProto.Type.TYPE_STRING) + .setOneofIndex(0)) + .addField( + FieldDescriptorProto.newBuilder() + .setName("b") + .setNumber(2) + .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) + .setType(FieldDescriptorProto.Type.TYPE_STRING) + .setOneofIndex(0)) + .build(); + + FileDescriptorProto file = + FileDescriptorProto.newBuilder() + .setName("choice.proto") + .setSyntax("proto2") + .setPackage("example") + .addMessageType(choice) + .build(); + + Descriptors.FileDescriptor fileDescriptor = + Descriptors.FileDescriptor.buildFrom(file, new Descriptors.FileDescriptor[] {}); + return fileDescriptor.findMessageTypeByName("Choice"); + } + + /** Builds a {@link MapValidateMessage} over {@code google.protobuf.Timestamp}. */ + private static MapValidateMessage timestampMessage( + Descriptors.Descriptor eventDescriptor, long seconds) { + Descriptors.Descriptor timestampDescriptor = + eventDescriptor.findFieldByName("created_at").getMessageType(); + Map fields = new HashMap<>(); + fields.put(timestampDescriptor.findFieldByName("seconds"), seconds); + return new MapValidateMessage(timestampDescriptor, fields); + } + + /** A {@code FieldOptions} carrying a {@code string.min_len} field rule. */ + private static FieldOptions stringMinLen(int minLen) { + return fieldRule(FieldRules.newBuilder().setString(StringRules.newBuilder().setMinLen(minLen))); + } + + /** + * Wraps a {@link FieldRules} into {@code FieldOptions} via the {@code buf.validate.field} ext. + */ + private static FieldOptions fieldRule(FieldRules.Builder rules) { + return FieldOptions.newBuilder().setExtension(ValidateProto.field, rules.build()).build(); + } + + /** A {@link ValidateMessage} backed by an in-memory map of field values. */ + private static final class MapValidateMessage implements ValidateMessage { + private final Descriptors.Descriptor descriptor; + private final Map fields; + + MapValidateMessage( + Descriptors.Descriptor descriptor, Map fields) { + this.descriptor = descriptor; + this.fields = fields; + } + + @Override + public Descriptors.Descriptor getDescriptorForType() { + return descriptor; + } + + @Override + public boolean hasField(Descriptors.FieldDescriptor field) { + return fields.containsKey(field); + } + + @Override + public Value getField(Descriptors.FieldDescriptor field) { + Object value = fields.get(field); + // A message-typed singular field is backed by another ValidateMessage; wrap it so the + // embedded-message evaluator can recurse without a protobuf Message. + if (value instanceof ValidateMessage) { + return new ValidateMessageFieldValue(field, (ValidateMessage) value); + } + // Map fields need a runtime-independent Value: ObjectValue.mapValue() expects + // protobuf map-entry messages, which an alternative runtime would not have. + if (field.isMapField()) { + Map map = value == null ? Collections.emptyMap() : (Map) value; + return new MapFieldValue(field, map); + } + // Repeated fields: a custom Value so message elements recurse as ValidateMessages. + if (field.isRepeated()) { + List list = value == null ? Collections.emptyList() : (List) value; + return new RepeatedFieldValue(field, list); + } + // A singular message field must be backed by a ValidateMessage (handled above). Reaching + // here means a non-ValidateMessage value was stored for a message field, which would + // otherwise fail later as a ClassCastException to com.google.protobuf.Message. + if (isMessage(field)) { + throw new IllegalArgumentException( + "message field \"" + + field.getName() + + "\" must be provided as a ValidateMessage, but got " + + (value == null ? "null" : value.getClass().getName())); + } + if (value == null) { + value = field.getDefaultValue(); + } + return new ObjectValue(field, value); + } + + @Override + public Object celValue() { + // Well-known types must surface their CEL-native form (e.g. Timestamp -> Instant) + // so the standard WKT rules, which expect `this` to be that form, can evaluate. + Object wellKnown = wellKnownCelValue(); + if (wellKnown != null) { + return wellKnown; + } + // Otherwise: CEL's runtime dispatches field selection on the actual object, so a + // plain Map keyed by field name works in place of a protobuf Message. Each field + // delegates to its Value's own CEL conversion (nested messages, repeated, maps). + Map out = new HashMap<>(); + for (Descriptors.FieldDescriptor field : fields.keySet()) { + out.put(field.getName(), getField(field).celValue()); + } + return out; + } + + /** + * Returns the CEL-native representation if this message wraps a well-known type, otherwise + * {@code null}. Mirrors how {@code ProtoAdapter} converts these messages for the protobuf + * runtime, but builds the value from the field map instead of a {@code Message}. + */ + private @Nullable Object wellKnownCelValue() { + switch (descriptor.getFullName()) { + case "google.protobuf.Timestamp": + return Instant.ofEpochSecond(longField("seconds"), longField("nanos")); + case "google.protobuf.Duration": + return Duration.ofSeconds(longField("seconds"), longField("nanos")); + case "google.protobuf.DoubleValue": + case "google.protobuf.FloatValue": + case "google.protobuf.Int64Value": + case "google.protobuf.UInt64Value": + case "google.protobuf.Int32Value": + case "google.protobuf.UInt32Value": + case "google.protobuf.BoolValue": + case "google.protobuf.StringValue": + case "google.protobuf.BytesValue": + Descriptors.FieldDescriptor valueField = descriptor.findFieldByName("value"); + Object raw = fields.get(valueField); + return ProtoAdapter.scalarToCel( + valueField.getType(), raw == null ? valueField.getDefaultValue() : raw); + default: + return null; + } + } + + /** Reads a numeric field as a long, defaulting to 0 when unset. */ + private long longField(String name) { + Object value = fields.get(descriptor.findFieldByName(name)); + return value == null ? 0L : ((Number) value).longValue(); + } + } + + /** A {@link Value} for a message-typed field, backed by a nested {@link ValidateMessage}. */ + private static final class ValidateMessageFieldValue implements Value { + private final Descriptors.FieldDescriptor fieldDescriptor; + private final ValidateMessage message; + + ValidateMessageFieldValue( + Descriptors.FieldDescriptor fieldDescriptor, ValidateMessage message) { + this.fieldDescriptor = fieldDescriptor; + this.message = message; + } + + @Override + public Descriptors.FieldDescriptor fieldDescriptor() { + return fieldDescriptor; + } + + @Override + public ValidateMessage messageValue() { + return message; + } + + @Override + public Object rawValue() { + return message; + } + + @Override + public Object celValue() { + return message.celValue(); + } + + @Override + public T jvmValue(Class clazz) { + return clazz.cast(message.celValue()); + } + + @Override + public List repeatedValue() { + return Collections.emptyList(); + } + + @Override + public Map mapValue() { + return Collections.emptyMap(); + } + } + + /** + * A {@link Value} for a map field, backed by a plain {@link Map} of raw key/value pairs. The + * key/value field descriptors come from the synthetic map-entry type, so each pair is exposed as + * an {@link ObjectValue} without needing protobuf map-entry messages. + */ + private static final class MapFieldValue implements Value { + private final Descriptors.FieldDescriptor fieldDescriptor; + private final Descriptors.FieldDescriptor keyDescriptor; + private final Descriptors.FieldDescriptor valueDescriptor; + private final Map value; + + MapFieldValue(Descriptors.FieldDescriptor fieldDescriptor, Map value) { + this.fieldDescriptor = fieldDescriptor; + this.keyDescriptor = fieldDescriptor.getMessageType().findFieldByNumber(1); + this.valueDescriptor = fieldDescriptor.getMessageType().findFieldByNumber(2); + this.value = value; + } + + @Override + public Descriptors.FieldDescriptor fieldDescriptor() { + return fieldDescriptor; + } + + @Override + public ValidateMessage messageValue() { + return null; + } + + @Override + public Object rawValue() { + return value; + } + + @Override + public Object celValue() { + // Map keys are always scalar/enum; values may be messages (backed by ValidateMessages). + Map out = new HashMap<>(value.size()); + for (Map.Entry entry : value.entrySet()) { + out.put( + ProtoAdapter.scalarToCel(keyDescriptor.getType(), entry.getKey()), + celValueOf(valueDescriptor, entry.getValue())); + } + return out; + } + + @Override + public T jvmValue(Class clazz) { + return clazz.cast(value); + } + + @Override + public List repeatedValue() { + return Collections.emptyList(); + } + + @Override + public Map mapValue() { + Map out = new HashMap<>(value.size()); + for (Map.Entry entry : value.entrySet()) { + out.put( + new ObjectValue(keyDescriptor, entry.getKey()), + mapValueElement(valueDescriptor, entry.getValue())); + } + return out; + } + } + + /** + * A {@link Value} for a repeated field, backed by a plain {@link List} of raw elements. Scalar + * elements reuse {@link ListElementValue}; message elements are backed by ValidateMessages so + * they recurse without a protobuf Message. + */ + private static final class RepeatedFieldValue implements Value { + private final Descriptors.FieldDescriptor fieldDescriptor; + private final List values; + + RepeatedFieldValue(Descriptors.FieldDescriptor fieldDescriptor, List values) { + this.fieldDescriptor = fieldDescriptor; + this.values = values; + } + + @Override + public Descriptors.FieldDescriptor fieldDescriptor() { + return fieldDescriptor; + } + + @Override + public ValidateMessage messageValue() { + return null; + } + + @Override + public Object rawValue() { + return values; + } + + @Override + public Object celValue() { + List out = new ArrayList<>(values.size()); + for (Object element : values) { + out.add(celValueOf(fieldDescriptor, element)); + } + return out; + } + + @Override + public T jvmValue(Class clazz) { + return clazz.cast(values); + } + + @Override + public List repeatedValue() { + List out = new ArrayList<>(values.size()); + for (Object element : values) { + out.add(repeatedElement(fieldDescriptor, element)); + } + return out; + } + + @Override + public Map mapValue() { + return Collections.emptyMap(); + } + } + + /** Whether a descriptor refers to a message (as opposed to a scalar or enum). */ + private static boolean isMessage(Descriptors.FieldDescriptor descriptor) { + return descriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE; + } + + /** + * Wraps a repeated element as a {@link Value}: a {@link ValidateMessageFieldValue} for messages, + * otherwise a {@link ListElementValue}, mirroring {@code ObjectValue.repeatedValue()}. + */ + private static Value repeatedElement(Descriptors.FieldDescriptor descriptor, Object value) { + if (isMessage(descriptor)) { + return new ValidateMessageFieldValue(descriptor, (ValidateMessage) value); + } + return new ListElementValue(descriptor, value); + } + + /** + * Wraps a map value as a {@link Value}: a {@link ValidateMessageFieldValue} for messages, + * otherwise an {@link ObjectValue}, mirroring {@code ObjectValue.mapValue()}. + */ + private static Value mapValueElement(Descriptors.FieldDescriptor descriptor, Object value) { + if (isMessage(descriptor)) { + return new ValidateMessageFieldValue(descriptor, (ValidateMessage) value); + } + return new ObjectValue(descriptor, value); + } + + /** Converts a single repeated element or map value to its CEL representation. */ + private static Object celValueOf(Descriptors.FieldDescriptor descriptor, Object value) { + if (isMessage(descriptor)) { + return ((ValidateMessage) value).celValue(); + } + return ProtoAdapter.scalarToCel(descriptor.getType(), value); + } +} From e93bc748f89dfbc0000e0359775645630494438f Mon Sep 17 00:00:00 2001 From: Andrew Parmet Date: Mon, 30 Nov 2026 10:48:17 -0500 Subject: [PATCH 05/23] Cover message-backed values during custom rule validation 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. --- .../java/build/buf/protovalidate/Value.java | 4 + .../protovalidate/ValidateMessageTest.java | 76 +++++++++++++++++++ 2 files changed, 80 insertions(+) diff --git a/src/main/java/build/buf/protovalidate/Value.java b/src/main/java/build/buf/protovalidate/Value.java index 296113e66..bcc81ec25 100644 --- a/src/main/java/build/buf/protovalidate/Value.java +++ b/src/main/java/build/buf/protovalidate/Value.java @@ -83,6 +83,10 @@ public interface Value { * Get the underlying value and cast it to the class type, which will be a type checkable * internally by protovalidate-java. * + *

Values returned by {@link ValidateMessage#getField}, {@link #repeatedValue}, or {@link + * #mapValue} must support {@code Object.class} for zero-value checks and violation details, + * including message-valued fields and elements. + * * @param clazz The inferred class. * @return The value cast to the inferred class type. * @param The class type. diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java index 059222520..5e3760484 100644 --- a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java +++ b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java @@ -44,8 +44,12 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import java.util.stream.Stream; import org.jspecify.annotations.Nullable; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Exercises {@link Validator#validate(ValidateMessage)} with an alternative-runtime {@link @@ -53,6 +57,78 @@ * {@code com.google.protobuf.Message}. */ public class ValidateMessageTest { + private static Stream customRuleCases() { + return Stream.of(true, false) + .flatMap(nativeRules -> + Stream.of(true, false) + .flatMap(stringResult -> + Stream.of(true, false) + .map(valid -> Arguments.of(nativeRules, stringResult, valid)))); + } + + @ParameterizedTest(name = "nativeRules={0}, stringResult={1}, valid={2}") + @MethodSource("customRuleCases") + public void customRulesDoNotReadMessageJvmValues( + boolean nativeRules, boolean stringResult, boolean valid) throws Exception { + String result = stringResult ? " ? '' : 'invalid name'" : ""; + Rule messageRule = + Rule.newBuilder() + .setId("message_rule") + .setMessage("invalid name") + .setExpression("this.name == 'alice'" + result) + .build(); + Rule fieldRule = + messageRule.toBuilder() + .setId("field_rule") + .setExpression("this == 'alice'" + result) + .build(); + DescriptorProto messageType = + DescriptorProto.newBuilder() + .setName("CustomRules") + .setOptions( + MessageOptions.newBuilder() + .setExtension( + ValidateProto.message, + MessageRules.newBuilder().addCel(messageRule).build())) + .addField( + FieldDescriptorProto.newBuilder() + .setName("name") + .setNumber(1) + .setType(FieldDescriptorProto.Type.TYPE_STRING) + .setOptions(fieldRule(FieldRules.newBuilder().addCel(fieldRule)))) + .build(); + Descriptors.Descriptor descriptor = + Descriptors.FileDescriptor.buildFrom( + FileDescriptorProto.newBuilder() + .setName("custom_rules.proto") + .setSyntax("proto3") + .addMessageType(messageType) + .build(), + new Descriptors.FileDescriptor[] {}) + .findMessageTypeByName("CustomRules"); + ValidateMessage message = + new MapValidateMessage( + descriptor, + Collections.singletonMap(descriptor.findFieldByName("name"), valid ? "alice" : "bob")); + Validator validator = + ValidatorFactory.newBuilder() + .withConfig(Config.newBuilder().setEnableNativeRules(nativeRules).build()) + .build(); + + ValidationResult resultValue = validator.validate(message); + + if (valid) { + assertThat(resultValue.getViolations()).isEmpty(); + } else { + assertThat(resultValue.getViolations()) + .extracting(violation -> violation.toProto().getRuleId()) + .containsExactlyInAnyOrder("message_rule", "field_rule"); + assertThat(resultValue.getViolations()) + .extracting(violation -> violation.toProto().getMessage()) + .containsOnly("invalid name"); + } + } + @Test public void violations() throws Exception { // "Person" has two scalar fields with buf.validate.field rules and a From 7aa122245520a35e188cdfcfafad78e6b243e1af Mon Sep 17 00:00:00 2001 From: Andrew Parmet Date: Mon, 30 Nov 2026 20:56:39 -0500 Subject: [PATCH 06/23] Fix external runtime value contracts and validation overhead 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. --- .../buf/protovalidate/EnumEvaluator.java | 4 +- .../buf/protovalidate/FieldEvaluator.java | 16 +- .../buf/protovalidate/ListElementValue.java | 8 +- .../buf/protovalidate/MapRulesEvaluator.java | 5 +- .../protovalidate/MessageOneofEvaluator.java | 2 +- .../build/buf/protovalidate/ObjectValue.java | 8 +- .../buf/protovalidate/OneofEvaluator.java | 2 +- .../ProtobufValidateMessage.java | 14 +- .../buf/protovalidate/ValidateMessage.java | 36 +- .../build/buf/protovalidate/Validator.java | 7 +- .../java/build/buf/protovalidate/Value.java | 56 +- .../buf/protovalidate/ValueEvaluator.java | 15 +- .../protovalidate/ValidateMessageTest.java | 9 +- .../external/ExternalRuntimeTest.java | 622 ++++++++++++++++++ 14 files changed, 751 insertions(+), 53 deletions(-) create mode 100644 src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java diff --git a/src/main/java/build/buf/protovalidate/EnumEvaluator.java b/src/main/java/build/buf/protovalidate/EnumEvaluator.java index 52f6e1bb1..a77613cba 100644 --- a/src/main/java/build/buf/protovalidate/EnumEvaluator.java +++ b/src/main/java/build/buf/protovalidate/EnumEvaluator.java @@ -77,11 +77,11 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - Long enumValue = val.jvmValue(Long.class); + Number enumValue = val.jvmValue(Number.class); if (enumValue == null) { return RuleViolation.NO_VIOLATIONS; } - if (!values.contains(enumValue)) { + if (!values.contains(enumValue.longValue())) { return Collections.singletonList( RuleViolation.newBuilder() .addAllRulePathElements(helper.getRulePrefixElements()) diff --git a/src/main/java/build/buf/protovalidate/FieldEvaluator.java b/src/main/java/build/buf/protovalidate/FieldEvaluator.java index 3c88eb8a9..a9310bc0f 100644 --- a/src/main/java/build/buf/protovalidate/FieldEvaluator.java +++ b/src/main/java/build/buf/protovalidate/FieldEvaluator.java @@ -98,7 +98,7 @@ public List evaluate(Value val, boolean failFast) if (message == null) { return RuleViolation.NO_VIOLATIONS; } - boolean hasField = isFieldSet(message, descriptor); + boolean hasField = message.hasField(descriptor); if (required && !hasField) { return Collections.singletonList( RuleViolation.newBuilder() @@ -114,18 +114,4 @@ public List evaluate(Value val, boolean failFast) } return valueEvaluator.evaluate(message.getField(descriptor), failFast); } - - /** - * Returns whether the given field is set on the message. Handles repeated and map fields, which - * require inspecting the list/map contents rather than a presence bit. - */ - static boolean isFieldSet(ValidateMessage message, FieldDescriptor field) { - if (field.isRepeated()) { - if (field.isMapField()) { - return !message.getField(field).mapValue().isEmpty(); - } - return !message.getField(field).repeatedValue().isEmpty(); - } - return message.hasField(field); - } } diff --git a/src/main/java/build/buf/protovalidate/ListElementValue.java b/src/main/java/build/buf/protovalidate/ListElementValue.java index ffe11f7e7..74aaafc5e 100644 --- a/src/main/java/build/buf/protovalidate/ListElementValue.java +++ b/src/main/java/build/buf/protovalidate/ListElementValue.java @@ -29,6 +29,8 @@ final class ListElementValue implements Value { /** Object type since the object type is inferred from the field descriptor. */ private final Object value; + private @Nullable ProtobufValidateMessage message; + /** * {@link com.google.protobuf.Descriptors.FieldDescriptor} is the field descriptor for the value. */ @@ -46,10 +48,10 @@ final class ListElementValue implements Value { @Override public @Nullable ValidateMessage messageValue() { - if (fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { - return new ProtobufValidateMessage((Message) value); + if (message == null && value instanceof Message) { + message = new ProtobufValidateMessage((Message) value); } - return null; + return message; } @Override diff --git a/src/main/java/build/buf/protovalidate/MapRulesEvaluator.java b/src/main/java/build/buf/protovalidate/MapRulesEvaluator.java index 39455b9e8..fea8bccda 100644 --- a/src/main/java/build/buf/protovalidate/MapRulesEvaluator.java +++ b/src/main/java/build/buf/protovalidate/MapRulesEvaluator.java @@ -18,6 +18,7 @@ import build.buf.validate.MapRules; import com.google.protobuf.Descriptors.FieldDescriptor; import java.util.List; +import java.util.Map; import org.jspecify.annotations.Nullable; /** @@ -98,8 +99,8 @@ public boolean tautology() { public List evaluate(Value val, boolean failFast) { // Java protobuf returns map fields as a List of synthetic key/value entry messages; the size // is the pair count. - List entries = (List) val.rawValue(); - long size = entries.size(); + Object entries = val.rawValue(); + long size = entries instanceof Map ? ((Map) entries).size() : ((List) entries).size(); List violations = null; if (minPairs != null && size < minPairs) { diff --git a/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java b/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java index 1613be48e..c7e9331a9 100644 --- a/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java +++ b/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java @@ -50,7 +50,7 @@ public List evaluate(Value val, boolean failFast) } int hasCount = 0; for (FieldDescriptor field : fields) { - if (FieldEvaluator.isFieldSet(msg, field)) { + if (msg.hasField(field)) { hasCount++; } } diff --git a/src/main/java/build/buf/protovalidate/ObjectValue.java b/src/main/java/build/buf/protovalidate/ObjectValue.java index b7c29d0cc..b47fbb472 100644 --- a/src/main/java/build/buf/protovalidate/ObjectValue.java +++ b/src/main/java/build/buf/protovalidate/ObjectValue.java @@ -35,6 +35,8 @@ final class ObjectValue implements Value { /** Object type since the object type is inferred from the field descriptor. */ private final Object value; + private @Nullable ProtobufValidateMessage message; + /** * Constructs a new {@link ObjectValue}. * @@ -54,10 +56,10 @@ public Descriptors.FieldDescriptor fieldDescriptor() { @Nullable @Override public ValidateMessage messageValue() { - if (fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { - return new ProtobufValidateMessage((Message) value); + if (message == null && value instanceof Message) { + message = new ProtobufValidateMessage((Message) value); } - return null; + return message; } @Override diff --git a/src/main/java/build/buf/protovalidate/OneofEvaluator.java b/src/main/java/build/buf/protovalidate/OneofEvaluator.java index 7dc091883..8a16323ab 100644 --- a/src/main/java/build/buf/protovalidate/OneofEvaluator.java +++ b/src/main/java/build/buf/protovalidate/OneofEvaluator.java @@ -51,7 +51,7 @@ public List evaluate(Value val, boolean failFast) if (message == null) { return RuleViolation.NO_VIOLATIONS; } - boolean hasField = descriptor.getFields().stream().anyMatch(message::hasField); + boolean hasField = message.getOneofFieldDescriptor(descriptor) != null; if (!required || hasField) { return RuleViolation.NO_VIOLATIONS; } diff --git a/src/main/java/build/buf/protovalidate/ProtobufValidateMessage.java b/src/main/java/build/buf/protovalidate/ProtobufValidateMessage.java index 6d21dd513..3c08fd4b6 100644 --- a/src/main/java/build/buf/protovalidate/ProtobufValidateMessage.java +++ b/src/main/java/build/buf/protovalidate/ProtobufValidateMessage.java @@ -16,7 +16,9 @@ import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Descriptors.OneofDescriptor; import com.google.protobuf.Message; +import org.jspecify.annotations.Nullable; class ProtobufValidateMessage implements ValidateMessage { private final Message message; @@ -36,7 +38,17 @@ public Descriptor getDescriptorForType() { @Override public boolean hasField(FieldDescriptor field) { - return message.hasField(field); + return field.isRepeated() ? message.getRepeatedFieldCount(field) > 0 : message.hasField(field); + } + + @Override + public @Nullable FieldDescriptor getOneofFieldDescriptor(OneofDescriptor oneof) { + return message.getOneofFieldDescriptor(oneof); + } + + @Override + public boolean isEmpty() { + return message.equals(message.getDefaultInstanceForType()); } @Override diff --git a/src/main/java/build/buf/protovalidate/ValidateMessage.java b/src/main/java/build/buf/protovalidate/ValidateMessage.java index b637fe674..807203402 100644 --- a/src/main/java/build/buf/protovalidate/ValidateMessage.java +++ b/src/main/java/build/buf/protovalidate/ValidateMessage.java @@ -16,6 +16,8 @@ import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Descriptors.OneofDescriptor; +import org.jspecify.annotations.Nullable; /** * {@link ValidateMessage} is a wrapper around a protobuf message that provides reflective access to @@ -33,13 +35,45 @@ public interface ValidateMessage { Descriptor getDescriptorForType(); /** - * Whether the wrapped message has the field described by the provided field descriptor. + * 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; + } + /** * Get the value described by the provided field descriptor. * diff --git a/src/main/java/build/buf/protovalidate/Validator.java b/src/main/java/build/buf/protovalidate/Validator.java index 31ba0a48a..f9151a11d 100644 --- a/src/main/java/build/buf/protovalidate/Validator.java +++ b/src/main/java/build/buf/protovalidate/Validator.java @@ -39,11 +39,14 @@ public interface Validator { /** * 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}. + * 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. */ - ValidationResult validate(ValidateMessage message) throws ValidationException; + default ValidationResult validate(ValidateMessage message) throws ValidationException { + throw new ValidationException("ValidateMessage validation is unsupported"); + } } diff --git a/src/main/java/build/buf/protovalidate/Value.java b/src/main/java/build/buf/protovalidate/Value.java index bcc81ec25..c9ce70dc9 100644 --- a/src/main/java/build/buf/protovalidate/Value.java +++ b/src/main/java/build/buf/protovalidate/Value.java @@ -22,6 +22,33 @@ /** * {@link Value} is a wrapper around a protobuf value that provides helper methods for accessing the * value. + * + *

Field values and collection elements use the following representations. Unsigned raw integers + * use the signed Java type with the same bit pattern. Enum numbers must fit in a signed 32-bit + * integer. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Value representations by protobuf type
Protobuf type{@code rawValue()}{@code jvmValue(Object.class)}
32-bit signed integers{@link Integer}{@link Integer} or {@link Long}
64-bit signed integers{@link Long}{@link Long}
32-bit unsigned integers{@link Integer}{@link com.google.common.primitives.UnsignedLong}
64-bit unsigned integers{@link Long}{@link com.google.common.primitives.UnsignedLong}
float{@link Float}{@link Double}
double{@link Double}{@link Double}
bool{@link Boolean}{@link Boolean}
string{@link String}{@link String}
bytes{@link com.google.protobuf.ByteString}{@link dev.cel.common.values.CelByteString}
enum{@link Descriptors.EnumValueDescriptor}, {@link Integer}, or {@link Long}{@link Integer} or {@link Long}
message or groupThe runtime's message objectThe runtime's message object or its adapted representation
repeated{@link List} of raw elements{@link List} of JVM elements
map{@link Map} of raw keys and values, or a {@link List} of protobuf-java entry messages{@link Map} of JVM keys and values
+ * + *

Message validation and emptiness checks use {@link #messageValue()}, so message objects need + * not implement protobuf-java's {@code Message} or compare equal across runtimes. The + * representation returned by {@link #celValue()} must independently satisfy CEL's type + * requirements. */ public interface Value { /** @@ -35,24 +62,15 @@ public interface Value { /** * Get the underlying value as a {@link ValidateMessage} type. * - * @return The underlying {@link ValidateMessage} value. null if the underlying value is not a - * {@link ValidateMessage} type. + * @return A non-null view for a singular message or message element; null for scalar and + * collection values. */ @Nullable ValidateMessage messageValue(); /** - * Returns the underlying protobuf Java value without any CEL-specific adaptation. + * Returns the raw representation specified in the {@link Value} type table for native rules. * - *

{@link #jvmValue(Class)} routes scalars through {@code ProtoAdapter.toCel}, which converts - * {@code int32→Long}, {@code uint32→UnsignedLong}, {@code float→Double}, {@code bytes→ - * CelByteString}, etc. — appropriate for the CEL evaluation path but lossy for native rule - * evaluators that compare against raw protobuf field values. Native evaluators in {@code - * build.buf.protovalidate.rules} use this method to obtain values they can compare directly with - * the values they read off the typed rule message. - * - * @return The underlying value as protobuf-java provides it. Non-null for all values produced by - * the evaluator pipeline (field reads, list elements, message wrappers — all guarantee a - * value). + * @return The non-null raw value. */ Object rawValue(); @@ -68,7 +86,7 @@ public interface Value { * Get the underlying value as a map. * * @return The underlying value as a map. Empty map is returned if the underlying type is not a - * list. + * map. */ Map mapValue(); @@ -80,12 +98,14 @@ public interface Value { Object celValue(); /** - * Get the underlying value and cast it to the class type, which will be a type checkable - * internally by protovalidate-java. + * Returns the JVM representation specified in the {@link Value} type table, cast to {@code + * clazz}. * *

Values returned by {@link ValidateMessage#getField}, {@link #repeatedValue}, or {@link - * #mapValue} must support {@code Object.class} for zero-value checks and violation details, - * including message-valued fields and elements. + * #mapValue} must support {@code Object.class} for violation details, including message-valued + * fields and elements. Scalars must also support their compatible Java supertypes: numeric values + * accept {@code Number.class}, booleans accept {@code Boolean.class}, and strings accept {@code + * String.class}. Scalar zero-value checks use this representation. * * @param clazz The inferred class. * @return The value cast to the inferred class type. diff --git a/src/main/java/build/buf/protovalidate/ValueEvaluator.java b/src/main/java/build/buf/protovalidate/ValueEvaluator.java index 2408b0049..51f50c1ef 100644 --- a/src/main/java/build/buf/protovalidate/ValueEvaluator.java +++ b/src/main/java/build/buf/protovalidate/ValueEvaluator.java @@ -17,6 +17,7 @@ import build.buf.protovalidate.exceptions.ExecutionException; import build.buf.validate.FieldPath; import com.google.protobuf.Descriptors; +import com.google.protobuf.Message; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -71,7 +72,7 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - if (this.shouldIgnore(val.jvmValue(Object.class))) { + if (ignoreEmpty && isZeroValue(val)) { return RuleViolation.NO_VIOLATIONS; } List allViolations = new ArrayList<>(); @@ -104,7 +105,15 @@ void setIgnoreEmpty(Object zero) { this.zero = zero; } - private boolean shouldIgnore(Object value) { - return this.ignoreEmpty && Objects.equals(value, this.zero); + private boolean isZeroValue(Value val) { + if (zero instanceof Message) { + ValidateMessage message = val.messageValue(); + return message != null && message.isEmpty(); + } + Object value = val.jvmValue(Object.class); + if (zero instanceof Long && value instanceof Number) { + return ((Number) value).longValue() == (Long) zero; + } + return Objects.equals(value, zero); } } diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java index 5e3760484..e6471a456 100644 --- a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java +++ b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java @@ -827,7 +827,14 @@ public Descriptors.Descriptor getDescriptorForType() { @Override public boolean hasField(Descriptors.FieldDescriptor field) { - return fields.containsKey(field); + Object value = fields.get(field); + if (value instanceof Map) { + return !((Map) value).isEmpty(); + } + if (value instanceof List) { + return !((List) value).isEmpty(); + } + return value != null && (field.hasPresence() || !value.equals(field.getDefaultValue())); } @Override diff --git a/src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java b/src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java new file mode 100644 index 000000000..77974a9aa --- /dev/null +++ b/src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java @@ -0,0 +1,622 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate.external; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import build.buf.protovalidate.Config; +import build.buf.protovalidate.ValidateMessage; +import build.buf.protovalidate.ValidationResult; +import build.buf.protovalidate.Validator; +import build.buf.protovalidate.ValidatorFactory; +import build.buf.protovalidate.Value; +import build.buf.protovalidate.exceptions.ValidationException; +import build.buf.validate.BytesRules; +import build.buf.validate.EnumRules; +import build.buf.validate.FieldRules; +import build.buf.validate.FloatRules; +import build.buf.validate.Ignore; +import build.buf.validate.Int32Rules; +import build.buf.validate.MapRules; +import build.buf.validate.OneofRules; +import build.buf.validate.RepeatedRules; +import build.buf.validate.StringRules; +import build.buf.validate.UInt32Rules; +import build.buf.validate.UInt64Rules; +import build.buf.validate.ValidateProto; +import com.google.common.primitives.UnsignedLong; +import com.google.protobuf.ByteString; +import com.google.protobuf.DescriptorProtos.DescriptorProto; +import com.google.protobuf.DescriptorProtos.EnumDescriptorProto; +import com.google.protobuf.DescriptorProtos.EnumValueDescriptorProto; +import com.google.protobuf.DescriptorProtos.FieldDescriptorProto; +import com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Label; +import com.google.protobuf.DescriptorProtos.FieldOptions; +import com.google.protobuf.DescriptorProtos.FileDescriptorProto; +import com.google.protobuf.DescriptorProtos.MessageOptions; +import com.google.protobuf.DescriptorProtos.OneofDescriptorProto; +import com.google.protobuf.DescriptorProtos.OneofOptions; +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Descriptors.FileDescriptor; +import com.google.protobuf.DynamicMessage; +import com.google.protobuf.UnknownFieldSet; +import dev.cel.common.values.CelByteString; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class ExternalRuntimeTest { + @Test + void legacyValidatorRemainsImplementable() throws Exception { + Validator legacy = message -> ValidationResult.EMPTY; + Descriptor descriptor = + descriptor(field("s", FieldDescriptorProto.Type.TYPE_STRING, FieldRules.newBuilder())); + ExternalMessage message = message(descriptor, "s", "abc"); + assertThat(legacy.validate(toProtobuf(message))).isSameAs(ValidationResult.EMPTY); + assertThatThrownBy(() -> legacy.validate(message)) + .isInstanceOf(ValidationException.class) + .hasMessageContaining("unsupported"); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void mapCardinality(boolean nativeRules) throws Exception { + Descriptor descriptor = + descriptor( + field( + "values", + FieldDescriptorProto.Type.TYPE_MESSAGE, + FieldRules.newBuilder() + .setMap(MapRules.newBuilder().setMinPairs(1).setMaxPairs(1))) + .setTypeName(".external.Record.Entry") + .setLabel(Label.LABEL_REPEATED), + mapEntry(FieldDescriptorProto.Type.TYPE_INT32)); + for (int size = 0; size <= 2; size++) { + Map entries = new HashMap<>(); + for (int i = 0; i < size; i++) { + entries.put("key" + i, i); + } + assertParity(nativeRules, message(descriptor, "values", entries), size == 1 ? 0 : 1); + } + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void integerEnums(boolean nativeRules) throws Exception { + Descriptor descriptor = + descriptor( + field( + "kind", + FieldDescriptorProto.Type.TYPE_ENUM, + FieldRules.newBuilder() + .setEnum(EnumRules.newBuilder().setDefinedOnly(true).addNotIn(-1))) + .setTypeName(".external.Record.Kind")); + for (int number : new int[] {0, 1, 2, -1}) { + assertParity( + nativeRules, message(descriptor, "kind", number), number < 0 ? 2 : number == 2 ? 1 : 0); + } + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void ignoreZeroScalarItems(boolean nativeRules) throws Exception { + assertIgnoredItems( + nativeRules, + FieldDescriptorProto.Type.TYPE_INT32, + FieldRules.newBuilder().setInt32(Int32Rules.newBuilder().setConst(1)), + 0, + 1, + 2); + assertIgnoredItems( + nativeRules, + FieldDescriptorProto.Type.TYPE_ENUM, + FieldRules.newBuilder().setEnum(EnumRules.newBuilder().setConst(1)), + 0, + 1, + 2); + assertIgnoredItems( + nativeRules, + FieldDescriptorProto.Type.TYPE_UINT32, + FieldRules.newBuilder().setUint32(UInt32Rules.newBuilder().setConst(1)), + 0, + 1, + -1); + assertIgnoredItems( + nativeRules, + FieldDescriptorProto.Type.TYPE_UINT64, + FieldRules.newBuilder().setUint64(UInt64Rules.newBuilder().setConst(1)), + 0L, + 1L, + -1L); + assertIgnoredItems( + nativeRules, + FieldDescriptorProto.Type.TYPE_FLOAT, + FieldRules.newBuilder().setFloat(FloatRules.newBuilder().setConst(1)), + 0F, + 1F, + 2F); + assertIgnoredItems( + nativeRules, + FieldDescriptorProto.Type.TYPE_BYTES, + FieldRules.newBuilder() + .setBytes(BytesRules.newBuilder().setConst(ByteString.copyFromUtf8("a"))), + ByteString.EMPTY, + ByteString.copyFromUtf8("a"), + ByteString.copyFromUtf8("b")); + } + + private static void assertIgnoredItems( + boolean nativeRules, + FieldDescriptorProto.Type type, + FieldRules.Builder itemRules, + Object zero, + Object valid, + Object invalid) + throws Exception { + FieldDescriptorProto.Builder items = + field( + "items", + type, + FieldRules.newBuilder() + .setRepeated( + RepeatedRules.newBuilder() + .setItems(itemRules.setIgnore(Ignore.IGNORE_IF_ZERO_VALUE)))) + .setLabel(Label.LABEL_REPEATED); + if (type == FieldDescriptorProto.Type.TYPE_ENUM) { + items.setTypeName(".external.Record.Kind"); + } + assertParity( + nativeRules, message(descriptor(items), "items", Arrays.asList(zero, valid, invalid)), 1); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void ignoreEmptyMessageItems(boolean nativeRules) throws Exception { + Descriptor descriptor = + descriptor( + field( + "items", + FieldDescriptorProto.Type.TYPE_MESSAGE, + FieldRules.newBuilder() + .setRepeated( + RepeatedRules.newBuilder() + .setItems( + FieldRules.newBuilder() + .setIgnore(Ignore.IGNORE_IF_ZERO_VALUE)))) + .setTypeName(".external.Record.Inner") + .setLabel(Label.LABEL_REPEATED)); + Descriptor inner = descriptor.findNestedTypeByName("Inner"); + assertParity( + nativeRules, + message( + descriptor, + "items", + Collections.singletonList(new ExternalMessage(inner, Collections.emptyMap()))), + 0); + for (String value : new String[] {"", "x", "abc"}) { + assertParity( + nativeRules, + message(descriptor, "items", Collections.singletonList(message(inner, "s", value))), + value.equals("x") ? 1 : 0); + } + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void ignoreEmptyMessageMapValues(boolean nativeRules) throws Exception { + Descriptor descriptor = + descriptor( + field( + "values", + FieldDescriptorProto.Type.TYPE_MESSAGE, + FieldRules.newBuilder() + .setMap( + MapRules.newBuilder() + .setValues( + FieldRules.newBuilder() + .setIgnore(Ignore.IGNORE_IF_ZERO_VALUE)))) + .setTypeName(".external.Record.Entry") + .setLabel(Label.LABEL_REPEATED), + mapEntry(FieldDescriptorProto.Type.TYPE_MESSAGE)); + Descriptor inner = descriptor.findNestedTypeByName("Inner"); + for (String value : new String[] {"", "x", "abc"}) { + assertParity( + nativeRules, + message( + descriptor, "values", Collections.singletonMap("key", message(inner, "s", value))), + value.equals("x") ? 1 : 0); + } + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void unknownFieldsPreventIgnoringMessages(boolean nativeRules) throws Exception { + Descriptor descriptor = + descriptor( + field( + "items", + FieldDescriptorProto.Type.TYPE_MESSAGE, + FieldRules.newBuilder() + .setRepeated( + RepeatedRules.newBuilder() + .setItems( + FieldRules.newBuilder() + .setIgnore(Ignore.IGNORE_IF_ZERO_VALUE)))) + .setTypeName(".external.Record.Inner") + .setLabel(Label.LABEL_REPEATED)); + ExternalMessage inner = + new ExternalMessage( + descriptor.findNestedTypeByName("Inner"), + Collections.emptyMap(), + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()); + assertParity(nativeRules, message(descriptor, "items", Collections.singletonList(inner)), 1); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void explicitPresencePreventsIgnoringMessages(boolean nativeRules) throws Exception { + Descriptor descriptor = + descriptor( + field( + "items", + FieldDescriptorProto.Type.TYPE_MESSAGE, + FieldRules.newBuilder() + .setRepeated( + RepeatedRules.newBuilder() + .setItems( + FieldRules.newBuilder() + .setIgnore(Ignore.IGNORE_IF_ZERO_VALUE)))) + .setTypeName(".external.Record.OptionalInner") + .setLabel(Label.LABEL_REPEATED), + DescriptorProto.newBuilder() + .setName("OptionalInner") + .addOneofDecl(OneofDescriptorProto.newBuilder().setName("_s")) + .addField( + field( + "s", + FieldDescriptorProto.Type.TYPE_STRING, + FieldRules.newBuilder() + .setString(StringRules.newBuilder().setMinLen(3))) + .setProto3Optional(true) + .setOneofIndex(0)) + .build()); + Descriptor inner = descriptor.findNestedTypeByName("OptionalInner"); + assertParity( + nativeRules, + message( + descriptor, + "items", + Collections.singletonList(new ExternalMessage(inner, Collections.emptyMap()))), + 0); + assertParity( + nativeRules, + message(descriptor, "items", Collections.singletonList(message(inner, "s", ""))), + 1); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void oneofDefaultValuesArePresent(boolean nativeRules) throws Exception { + Descriptor descriptor = + descriptor( + field("s", FieldDescriptorProto.Type.TYPE_STRING, FieldRules.newBuilder()) + .setOneofIndex(0)); + ExternalMessage empty = new ExternalMessage(descriptor, Collections.emptyMap()); + ExternalMessage populated = message(descriptor, "s", ""); + assertThat(empty.getOneofFieldDescriptor(descriptor.getOneofs().get(0))).isNull(); + assertThat(populated.getOneofFieldDescriptor(descriptor.getOneofs().get(0))) + .isEqualTo(descriptor.findFieldByName("s")); + assertParity(nativeRules, empty, 1); + assertParity(nativeRules, populated, 0); + } + + private static void assertParity(boolean nativeRules, ExternalMessage message, int violations) + throws Exception { + Validator validator = + ValidatorFactory.newBuilder() + .withConfig(Config.newBuilder().setEnableNativeRules(nativeRules).build()) + .build(); + ValidationResult expected = validator.validate(toProtobuf(message)); + assertThat(expected.getViolations()).hasSize(violations); + ValidationResult actual = validator.validate(message); + assertThat(actual.getViolations().stream().map(it -> it.toProto()).collect(Collectors.toList())) + .containsExactlyInAnyOrderElementsOf( + expected.getViolations().stream().map(it -> it.toProto()).collect(Collectors.toList())); + } + + private static ExternalMessage message(Descriptor descriptor, String field, Object value) { + return new ExternalMessage(descriptor, Collections.singletonMap(field, value)); + } + + private static FieldDescriptorProto.Builder field( + String name, FieldDescriptorProto.Type type, FieldRules.Builder rules) { + return FieldDescriptorProto.newBuilder() + .setName(name) + .setNumber(1) + .setType(type) + .setOptions(FieldOptions.newBuilder().setExtension(ValidateProto.field, rules.build())); + } + + private static DescriptorProto mapEntry(FieldDescriptorProto.Type valueType) { + FieldDescriptorProto.Builder value = + FieldDescriptorProto.newBuilder().setName("value").setNumber(2).setType(valueType); + if (valueType == FieldDescriptorProto.Type.TYPE_MESSAGE) { + value.setTypeName(".external.Record.Inner"); + } + return DescriptorProto.newBuilder() + .setName("Entry") + .setOptions(MessageOptions.newBuilder().setMapEntry(true)) + .addField( + FieldDescriptorProto.newBuilder() + .setName("key") + .setNumber(1) + .setType(FieldDescriptorProto.Type.TYPE_STRING)) + .addField(value) + .build(); + } + + private static Descriptor descriptor( + FieldDescriptorProto.Builder field, DescriptorProto... nested) throws Exception { + DescriptorProto.Builder record = + DescriptorProto.newBuilder() + .setName("Record") + .addField(field) + .addEnumType( + EnumDescriptorProto.newBuilder() + .setName("Kind") + .addValue(EnumValueDescriptorProto.newBuilder().setName("ZERO").setNumber(0)) + .addValue(EnumValueDescriptorProto.newBuilder().setName("ONE").setNumber(1))) + .addNestedType( + DescriptorProto.newBuilder() + .setName("Inner") + .addField( + field( + "s", + FieldDescriptorProto.Type.TYPE_STRING, + FieldRules.newBuilder() + .setString(StringRules.newBuilder().setMinLen(3))))); + for (DescriptorProto type : nested) { + record.addNestedType(type); + } + if (field.hasOneofIndex()) { + record.addOneofDecl( + OneofDescriptorProto.newBuilder() + .setName("choice") + .setOptions( + OneofOptions.newBuilder() + .setExtension( + ValidateProto.oneof, OneofRules.newBuilder().setRequired(true).build()))); + } + return FileDescriptor.buildFrom( + FileDescriptorProto.newBuilder() + .setName("external.proto") + .setPackage("external") + .setSyntax("proto3") + .addMessageType(record) + .build(), + new FileDescriptor[0]) + .findMessageTypeByName("Record"); + } + + private static DynamicMessage toProtobuf(ExternalMessage message) { + DynamicMessage.Builder builder = DynamicMessage.newBuilder(message.descriptor); + message.fields.forEach((name, value) -> { + FieldDescriptor field = message.descriptor.findFieldByName(name); + if (field.isMapField()) { + Descriptor entryType = field.getMessageType(); + ((Map) value) + .forEach((key, item) -> + builder.addRepeatedField( + field, + DynamicMessage.newBuilder(entryType) + .setField(entryType.findFieldByNumber(1), key) + .setField( + entryType.findFieldByNumber(2), + protobufValue(entryType.findFieldByNumber(2), item)) + .build())); + } else if (field.isRepeated()) { + for (Object item : (List) value) { + builder.addRepeatedField(field, protobufValue(field, item)); + } + } else { + builder.setField(field, protobufValue(field, value)); + } + }); + return builder.setUnknownFields(message.unknownFields).build(); + } + + private static Object protobufValue(FieldDescriptor field, Object value) { + if (value instanceof ExternalMessage) { + return toProtobuf((ExternalMessage) value); + } + if (field.getJavaType() == FieldDescriptor.JavaType.ENUM) { + return field.getEnumType().findValueByNumberCreatingIfUnknown((Integer) value); + } + return value; + } + + private static final class ExternalMessage implements ValidateMessage { + private final Descriptor descriptor; + private final Map fields; + private final UnknownFieldSet unknownFields; + + ExternalMessage(Descriptor descriptor, Map fields) { + this(descriptor, fields, UnknownFieldSet.getDefaultInstance()); + } + + ExternalMessage( + Descriptor descriptor, Map fields, UnknownFieldSet unknownFields) { + this.descriptor = descriptor; + this.fields = fields; + this.unknownFields = unknownFields; + } + + @Override + public Descriptor getDescriptorForType() { + return descriptor; + } + + @Override + public boolean isEmpty() { + return unknownFields.asMap().isEmpty() && ValidateMessage.super.isEmpty(); + } + + @Override + public boolean hasField(FieldDescriptor field) { + Object value = fields.get(field.getName()); + if (value == null) { + return false; + } + if (value instanceof Map) { + return !((Map) value).isEmpty(); + } + if (value instanceof List) { + return !((List) value).isEmpty(); + } + if (field.hasPresence()) { + return true; + } + Object defaultValue = + field.getJavaType() == FieldDescriptor.JavaType.ENUM + ? field.getEnumType().getValues().get(0).getNumber() + : field.getDefaultValue(); + return !value.equals(defaultValue); + } + + @Override + public Value getField(FieldDescriptor field) { + Object value = fields.get(field.getName()); + if (value == null) { + if (field.isMapField()) { + value = Collections.emptyMap(); + } else if (field.isRepeated()) { + value = Collections.emptyList(); + } else { + value = field.getDefaultValue(); + } + } + return new ExternalValue(field, value); + } + + @Override + public Object celValue() { + Map values = new HashMap<>(); + for (FieldDescriptor field : descriptor.getFields()) { + values.put(field.getName(), getField(field).celValue()); + } + return values; + } + } + + private static final class ExternalValue implements Value { + private final FieldDescriptor field; + private final Object value; + + ExternalValue(FieldDescriptor field, Object value) { + this.field = field; + this.value = value; + } + + @Override + public FieldDescriptor fieldDescriptor() { + return field; + } + + @Override + public ValidateMessage messageValue() { + return value instanceof ExternalMessage ? (ExternalMessage) value : null; + } + + @Override + public Object rawValue() { + return value; + } + + @Override + public List repeatedValue() { + List values = new ArrayList<>(); + if (value instanceof List) { + for (Object item : (List) value) { + values.add(new ExternalValue(field, item)); + } + } + return values; + } + + @Override + public Map mapValue() { + Map values = new HashMap<>(); + if (value instanceof Map) { + ((Map) value) + .forEach((key, item) -> + values.put( + new ExternalValue(field.getMessageType().findFieldByNumber(1), key), + new ExternalValue(field.getMessageType().findFieldByNumber(2), item))); + } + return values; + } + + @Override + public Object celValue() { + if (value instanceof Integer && field.getType() == FieldDescriptor.Type.UINT32) { + return UnsignedLong.valueOf(Integer.toUnsignedLong((Integer) value)); + } + if (value instanceof Long && field.getType() == FieldDescriptor.Type.UINT64) { + return UnsignedLong.fromLongBits((Long) value); + } + if (value instanceof Integer) { + return ((Integer) value).longValue(); + } + if (value instanceof Float) { + return ((Float) value).doubleValue(); + } + if (value instanceof ByteString) { + return CelByteString.of(((ByteString) value).toByteArray()); + } + if (value instanceof ExternalMessage) { + return ((ExternalMessage) value).celValue(); + } + if (value instanceof Map) { + Map values = new HashMap<>(); + mapValue().forEach((key, item) -> values.put(key.celValue(), item.celValue())); + return values; + } + if (value instanceof List) { + return repeatedValue().stream().map(Value::celValue).collect(Collectors.toList()); + } + return value; + } + + @Override + public T jvmValue(Class clazz) { + return clazz.cast( + (value instanceof Integer && field.getJavaType() == FieldDescriptor.JavaType.ENUM) + || value instanceof ExternalMessage + ? value + : celValue()); + } + } +} From df08d32372dfd39f40981ea0c36da59c46a7b697 Mon Sep 17 00:00:00 2001 From: Andrew Parmet Date: Mon, 30 Nov 2026 21:41:53 -0500 Subject: [PATCH 07/23] Keep cached message adapters immutable Initialize each message adapter in the value constructor so messageValue is a direct accessor and all value fields remain final. --- src/main/java/build/buf/protovalidate/ListElementValue.java | 6 ++---- src/main/java/build/buf/protovalidate/ObjectValue.java | 6 ++---- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/src/main/java/build/buf/protovalidate/ListElementValue.java b/src/main/java/build/buf/protovalidate/ListElementValue.java index 74aaafc5e..b738f9867 100644 --- a/src/main/java/build/buf/protovalidate/ListElementValue.java +++ b/src/main/java/build/buf/protovalidate/ListElementValue.java @@ -29,7 +29,7 @@ final class ListElementValue implements Value { /** Object type since the object type is inferred from the field descriptor. */ private final Object value; - private @Nullable ProtobufValidateMessage message; + private final @Nullable ProtobufValidateMessage message; /** * {@link com.google.protobuf.Descriptors.FieldDescriptor} is the field descriptor for the value. @@ -39,6 +39,7 @@ final class ListElementValue implements Value { ListElementValue(Descriptors.FieldDescriptor fieldDescriptor, Object value) { this.value = value; this.fieldDescriptor = fieldDescriptor; + this.message = value instanceof Message ? new ProtobufValidateMessage((Message) value) : null; } @Override @@ -48,9 +49,6 @@ final class ListElementValue implements Value { @Override public @Nullable ValidateMessage messageValue() { - if (message == null && value instanceof Message) { - message = new ProtobufValidateMessage((Message) value); - } return message; } diff --git a/src/main/java/build/buf/protovalidate/ObjectValue.java b/src/main/java/build/buf/protovalidate/ObjectValue.java index b47fbb472..7ed0bf539 100644 --- a/src/main/java/build/buf/protovalidate/ObjectValue.java +++ b/src/main/java/build/buf/protovalidate/ObjectValue.java @@ -35,7 +35,7 @@ final class ObjectValue implements Value { /** Object type since the object type is inferred from the field descriptor. */ private final Object value; - private @Nullable ProtobufValidateMessage message; + private final @Nullable ProtobufValidateMessage message; /** * Constructs a new {@link ObjectValue}. @@ -46,6 +46,7 @@ final class ObjectValue implements Value { ObjectValue(Descriptors.FieldDescriptor fieldDescriptor, Object value) { this.fieldDescriptor = fieldDescriptor; this.value = value; + this.message = value instanceof Message ? new ProtobufValidateMessage((Message) value) : null; } @Override @@ -56,9 +57,6 @@ public Descriptors.FieldDescriptor fieldDescriptor() { @Nullable @Override public ValidateMessage messageValue() { - if (message == null && value instanceof Message) { - message = new ProtobufValidateMessage((Message) value); - } return message; } From 90e5d3e2ee12c4f7b3c2c487d05ead12824b386a Mon Sep 17 00:00:00 2001 From: Andrew Parmet Date: Mon, 30 Nov 2026 22:00:43 -0500 Subject: [PATCH 08/23] Use field descriptors to initialize message adapters Determine message fields from their descriptors when constructing immutable values, avoiding a Message interface check on every scalar value. --- src/main/java/build/buf/protovalidate/ListElementValue.java | 5 ++++- src/main/java/build/buf/protovalidate/ObjectValue.java | 6 +++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main/java/build/buf/protovalidate/ListElementValue.java b/src/main/java/build/buf/protovalidate/ListElementValue.java index b738f9867..7987aca7e 100644 --- a/src/main/java/build/buf/protovalidate/ListElementValue.java +++ b/src/main/java/build/buf/protovalidate/ListElementValue.java @@ -39,7 +39,10 @@ final class ListElementValue implements Value { ListElementValue(Descriptors.FieldDescriptor fieldDescriptor, Object value) { this.value = value; this.fieldDescriptor = fieldDescriptor; - this.message = value instanceof Message ? new ProtobufValidateMessage((Message) value) : null; + this.message = + fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE + ? new ProtobufValidateMessage((Message) value) + : null; } @Override diff --git a/src/main/java/build/buf/protovalidate/ObjectValue.java b/src/main/java/build/buf/protovalidate/ObjectValue.java index 7ed0bf539..5042f230c 100644 --- a/src/main/java/build/buf/protovalidate/ObjectValue.java +++ b/src/main/java/build/buf/protovalidate/ObjectValue.java @@ -46,7 +46,11 @@ final class ObjectValue implements Value { ObjectValue(Descriptors.FieldDescriptor fieldDescriptor, Object value) { this.fieldDescriptor = fieldDescriptor; this.value = value; - this.message = value instanceof Message ? new ProtobufValidateMessage((Message) value) : null; + this.message = + !fieldDescriptor.isRepeated() + && fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE + ? new ProtobufValidateMessage((Message) value) + : null; } @Override From 664b231bd19ae672b15066c9eb3e31503dd0af8a Mon Sep 17 00:00:00 2001 From: Jon Bodner Date: Wed, 2 Dec 2026 15:27:03 -0500 Subject: [PATCH 09/23] Return plain field values from ValidateMessage 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. --- README.md | 18 ++ .../build/buf/protovalidate/AnyEvaluator.java | 2 +- .../protovalidate/EmptyValidateMessage.java | 43 +++ .../buf/protovalidate/FieldEvaluator.java | 2 +- .../build/buf/protovalidate/PlainValue.java | 196 ++++++++++++ .../ProtobufValidateMessage.java | 53 +++- .../buf/protovalidate/ValidateMessage.java | 30 +- .../protovalidate/ValidateMessageStruct.java | 73 +++++ .../protovalidate/ValidateMessageValue.java | 2 +- .../buf/protovalidate/ValidateMessages.java | 85 +++++ .../java/build/buf/protovalidate/Value.java | 32 +- .../protovalidate/WrappedValueEvaluator.java | 2 +- .../protovalidate/ValidateMessageTest.java | 297 +----------------- .../external/ExternalRuntimeTest.java | 117 +------ 14 files changed, 491 insertions(+), 461 deletions(-) create mode 100644 src/main/java/build/buf/protovalidate/EmptyValidateMessage.java create mode 100644 src/main/java/build/buf/protovalidate/PlainValue.java create mode 100644 src/main/java/build/buf/protovalidate/ValidateMessageStruct.java create mode 100644 src/main/java/build/buf/protovalidate/ValidateMessages.java diff --git a/README.md b/README.md index 7a535db8b..00cba8bde 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,24 @@ Validator validator = ValidatorFactory.newBuilder().withConfig(config).build(); Forward compatibility is preserved by a clone-and-clear contract: when protovalidate adds a new rule that this codebase hasn't yet implemented natively, the rule remains on the residual `FieldRules` and CEL enforces it. Native evaluation is an optimization, never a replacement. +## Other Protobuf runtimes + +`protovalidate-java` validates protobuf-java messages out of the box. To validate messages from another JVM Protobuf runtime without converting them to protobuf-java first, wrap each message in a `ValidateMessage` that returns plain Java values for its fields: + +```java +final class MyMessage implements ValidateMessage { + @Override public Descriptor getDescriptorForType() { ... } + // Repeated and map fields are present when non-empty. + @Override public boolean hasField(FieldDescriptor field) { ... } + // The field's value, or null when unset; nested messages are also ValidateMessages. + @Override public @Nullable Object getField(FieldDescriptor field) { ... } +} + +ValidationResult result = validator.validate(new MyMessage(message)); +``` + +The Javadoc on `ValidateMessage.getField` lists the Java type to return for each Protobuf field type. `protovalidate-java` converts these values for CEL itself, so implementations don't depend on CEL. For a complete implementation backed by a `Map`, see [`ExternalRuntimeTest`](src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java). + ## Additional languages and repositories Protovalidate isn't just for Java! You might be interested in sibling repositories for other languages: diff --git a/src/main/java/build/buf/protovalidate/AnyEvaluator.java b/src/main/java/build/buf/protovalidate/AnyEvaluator.java index c79b55113..8498fb082 100644 --- a/src/main/java/build/buf/protovalidate/AnyEvaluator.java +++ b/src/main/java/build/buf/protovalidate/AnyEvaluator.java @@ -82,7 +82,7 @@ public List evaluate(Value val, boolean failFast) return RuleViolation.NO_VIOLATIONS; } List violationList = new ArrayList<>(); - String typeURL = anyValue.getField(typeURLDescriptor).jvmValue(String.class); + String typeURL = ValidateMessages.field(anyValue, typeURLDescriptor).jvmValue(String.class); if (!in.isEmpty() && !in.contains(typeURL)) { RuleViolation.Builder violation = RuleViolation.newBuilder() diff --git a/src/main/java/build/buf/protovalidate/EmptyValidateMessage.java b/src/main/java/build/buf/protovalidate/EmptyValidateMessage.java new file mode 100644 index 000000000..533fac668 --- /dev/null +++ b/src/main/java/build/buf/protovalidate/EmptyValidateMessage.java @@ -0,0 +1,43 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import org.jspecify.annotations.Nullable; + +/** Stands in for an unset message field, which has no runtime object of its own. */ +final class EmptyValidateMessage implements ValidateMessage { + private final Descriptor descriptor; + + EmptyValidateMessage(Descriptor descriptor) { + this.descriptor = descriptor; + } + + @Override + public Descriptor getDescriptorForType() { + return descriptor; + } + + @Override + public boolean hasField(FieldDescriptor field) { + return false; + } + + @Override + public @Nullable Object getField(FieldDescriptor field) { + return null; + } +} diff --git a/src/main/java/build/buf/protovalidate/FieldEvaluator.java b/src/main/java/build/buf/protovalidate/FieldEvaluator.java index a9310bc0f..8b83baf4e 100644 --- a/src/main/java/build/buf/protovalidate/FieldEvaluator.java +++ b/src/main/java/build/buf/protovalidate/FieldEvaluator.java @@ -112,6 +112,6 @@ public List evaluate(Value val, boolean failFast) if (this.shouldIgnoreEmpty() && !hasField) { return RuleViolation.NO_VIOLATIONS; } - return valueEvaluator.evaluate(message.getField(descriptor), failFast); + return valueEvaluator.evaluate(ValidateMessages.field(message, descriptor), failFast); } } diff --git a/src/main/java/build/buf/protovalidate/PlainValue.java b/src/main/java/build/buf/protovalidate/PlainValue.java new file mode 100644 index 000000000..7ad58f70b --- /dev/null +++ b/src/main/java/build/buf/protovalidate/PlainValue.java @@ -0,0 +1,196 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Descriptors.EnumValueDescriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Descriptors.FieldDescriptor.JavaType; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.jspecify.annotations.Nullable; + +/** + * {@link Value} over a plain field value from {@link ValidateMessage#getField}. A null value means + * the field is unset and reads as its protobuf default. + */ +final class PlainValue implements Value { + private final FieldDescriptor field; + private final @Nullable Object value; + // An element of a repeated field shares the field's descriptor but is a single value. + private final boolean element; + + PlainValue(FieldDescriptor field, @Nullable Object value, boolean element) { + this.field = field; + this.value = value; + this.element = element; + } + + @Override + public FieldDescriptor fieldDescriptor() { + return field; + } + + @Override + public @Nullable ValidateMessage messageValue() { + return isMessage() ? message() : null; + } + + @Override + public Object rawValue() { + if (isList()) { + return list(); + } + if (isMap()) { + return map(); + } + if (isMessage()) { + return message(); + } + return scalar(); + } + + @Override + public List repeatedValue() { + if (!isList()) { + return Collections.emptyList(); + } + List out = new ArrayList<>(); + for (Object item : list()) { + out.add(new PlainValue(field, item, true)); + } + return Collections.unmodifiableList(out); + } + + @Override + public Map mapValue() { + if (!isMap()) { + return Collections.emptyMap(); + } + FieldDescriptor keyField = field.getMessageType().findFieldByNumber(1); + FieldDescriptor valueField = field.getMessageType().findFieldByNumber(2); + Map out = new HashMap<>(); + for (Map.Entry entry : map().entrySet()) { + out.put( + new PlainValue(keyField, entry.getKey(), false), + new PlainValue(valueField, entry.getValue(), false)); + } + return Collections.unmodifiableMap(out); + } + + @Override + public Object celValue() { + if (isList()) { + List out = new ArrayList<>(); + for (Value item : repeatedValue()) { + out.add(item.celValue()); + } + return out; + } + if (isMap()) { + Map out = new HashMap<>(); + for (Map.Entry entry : mapValue().entrySet()) { + out.put(entry.getKey().celValue(), entry.getValue().celValue()); + } + return out; + } + if (isMessage()) { + return ValidateMessages.cel(message()); + } + return scalarCel(); + } + + @Override + public T jvmValue(Class clazz) { + if (isList()) { + List out = new ArrayList<>(); + for (Value item : repeatedValue()) { + out.add(item.jvmValue(Object.class)); + } + return clazz.cast(out); + } + if (isMap()) { + Map out = new HashMap<>(); + for (Map.Entry entry : mapValue().entrySet()) { + out.put(entry.getKey().jvmValue(Object.class), entry.getValue().jvmValue(Object.class)); + } + return clazz.cast(out); + } + if (isMessage()) { + return clazz.cast(message()); + } + return clazz.cast(scalarCel()); + } + + private boolean isList() { + return field.isRepeated() && !field.isMapField() && !element; + } + + private boolean isMap() { + return field.isMapField() && !element; + } + + private boolean isMessage() { + return !isList() && !isMap() && field.getJavaType() == JavaType.MESSAGE; + } + + private List list() { + return value == null ? Collections.emptyList() : (List) value; + } + + private Map map() { + return value == null ? Collections.emptyMap() : (Map) value; + } + + private ValidateMessage message() { + if (value == null) { + return new EmptyValidateMessage(field.getMessageType()); + } + if (!(value instanceof ValidateMessage)) { + throw new IllegalArgumentException( + "message field \"" + + field.getName() + + "\" must be provided as a ValidateMessage, but got " + + value.getClass().getName()); + } + return (ValidateMessage) value; + } + + private Object scalar() { + if (field.getJavaType() == JavaType.ENUM) { + if (value == null) { + return field.getEnumType().getValues().get(0).getNumber(); + } + return value instanceof EnumValueDescriptor + ? ((EnumValueDescriptor) value).getNumber() + : ((Number) value).intValue(); + } + if (value != null) { + return value; + } + return field.getJavaType() == JavaType.BYTE_STRING ? ByteString.EMPTY : field.getDefaultValue(); + } + + private Object scalarCel() { + Object raw = scalar(); + if (field.getJavaType() == JavaType.ENUM) { + return ((Integer) raw).longValue(); + } + return ProtoAdapter.scalarToCel(field.getType(), raw); + } +} diff --git a/src/main/java/build/buf/protovalidate/ProtobufValidateMessage.java b/src/main/java/build/buf/protovalidate/ProtobufValidateMessage.java index 3c08fd4b6..1a15b63c5 100644 --- a/src/main/java/build/buf/protovalidate/ProtobufValidateMessage.java +++ b/src/main/java/build/buf/protovalidate/ProtobufValidateMessage.java @@ -15,22 +15,33 @@ package build.buf.protovalidate; import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.EnumValueDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.OneofDescriptor; import com.google.protobuf.Message; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import org.jspecify.annotations.Nullable; -class ProtobufValidateMessage implements ValidateMessage { +/** {@link ValidateMessage} over a protobuf-java {@link Message}. */ +final class ProtobufValidateMessage implements ValidateMessage { private final Message message; ProtobufValidateMessage(Message message) { this.message = message; } - public Message getMessage() { + Message getMessage() { return message; } + /** The validator reads protobuf-java fields through this, skipping the plain conversion. */ + Value fieldValue(FieldDescriptor field) { + return new ObjectValue(field, message.getField(field)); + } + @Override public Descriptor getDescriptorForType() { return message.getDescriptorForType(); @@ -52,12 +63,40 @@ public boolean isEmpty() { } @Override - public Value getField(FieldDescriptor field) { - return new ObjectValue(field, message.getField(field)); + public @Nullable Object getField(FieldDescriptor field) { + if (!field.isRepeated() && field.hasPresence() && !message.hasField(field)) { + return null; + } + Object value = message.getField(field); + if (field.isMapField()) { + FieldDescriptor keyField = field.getMessageType().findFieldByNumber(1); + FieldDescriptor valueField = field.getMessageType().findFieldByNumber(2); + Map out = new LinkedHashMap<>(); + for (Object entry : (List) value) { + Message entryMessage = (Message) entry; + out.put( + plain(keyField, entryMessage.getField(keyField)), + plain(valueField, entryMessage.getField(valueField))); + } + return out; + } + if (field.isRepeated()) { + List out = new ArrayList<>(); + for (Object element : (List) value) { + out.add(plain(field, element)); + } + return out; + } + return plain(field, value); } - @Override - public Object celValue() { - return message; + private static Object plain(FieldDescriptor field, Object value) { + if (value instanceof EnumValueDescriptor) { + return ((EnumValueDescriptor) value).getNumber(); + } + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + return new ProtobufValidateMessage((Message) value); + } + return value; } } diff --git a/src/main/java/build/buf/protovalidate/ValidateMessage.java b/src/main/java/build/buf/protovalidate/ValidateMessage.java index 807203402..d9ffe18b3 100644 --- a/src/main/java/build/buf/protovalidate/ValidateMessage.java +++ b/src/main/java/build/buf/protovalidate/ValidateMessage.java @@ -75,19 +75,25 @@ default boolean isEmpty() { } /** - * Get the value described by the provided field descriptor. + * 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. * - * @param field The field descriptor for which to retrieve a value. - * @return The value corresponding to the field descriptor. - */ - Value getField(FieldDescriptor field); - - /** - * Returns the representation of this message to hand to CEL for {@code this}-variable rule - * evaluation. Implementations return whichever form CEL can navigate for their runtime, such as a - * {@link com.google.protobuf.Message} or a {@code dev.cel.common.values.CelValue}. + *

Singular values use these types. Unsigned integers use the signed type with the same bits. * - * @return The CEL-navigable representation of this message. + *

    + *
  • int32, sint32, sfixed32, uint32, fixed32: {@link Integer} + *
  • int64, sint64, sfixed64, uint64, fixed64: {@link Long} + *
  • float: {@link Float}; double: {@link Double}; bool: {@link Boolean} + *
  • string: {@link String}; bytes: {@link com.google.protobuf.ByteString} + *
  • enum: the number as an {@link Integer} + *
  • message: a {@link ValidateMessage} + *
+ * + *

Repeated fields are a {@link java.util.List} of those values, and map fields a {@link + * java.util.Map}. + * + * @param field The field descriptor for which to retrieve a value. + * @return The field's value, or null when the field is unset. */ - Object celValue(); + @Nullable Object getField(FieldDescriptor field); } diff --git a/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java b/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java new file mode 100644 index 000000000..f09567917 --- /dev/null +++ b/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java @@ -0,0 +1,73 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import dev.cel.common.types.CelType; +import dev.cel.common.types.StructTypeReference; +import dev.cel.common.values.NullValue; +import dev.cel.common.values.StructValue; +import java.util.Optional; + +/** + * Presents a {@link ValidateMessage} to CEL as a struct. CEL reads fields with {@link #select}, + * which returns the default for unset fields, and evaluates {@code has()} with {@link #find}. + */ +// Messages are only read during validation, so the struct is effectively immutable. +@SuppressWarnings("Immutable") +final class ValidateMessageStruct extends StructValue { + private final ValidateMessage message; + private final Descriptor descriptor; + + ValidateMessageStruct(ValidateMessage message) { + this.message = message; + this.descriptor = message.getDescriptorForType(); + } + + @Override + public ValidateMessage value() { + return message; + } + + @Override + public boolean isZeroValue() { + return message.isEmpty(); + } + + @Override + public CelType celType() { + return StructTypeReference.create(descriptor.getFullName()); + } + + @Override + public Object select(String fieldName) { + FieldDescriptor field = ValidateMessages.requiredField(descriptor, fieldName); + // CEL reads an unset wrapper field as null, not as the wrapped default. + if (!field.isRepeated() + && field.getJavaType() == FieldDescriptor.JavaType.MESSAGE + && ValidateMessages.isWrapper(field.getMessageType()) + && !message.hasField(field)) { + return NullValue.NULL_VALUE; + } + return ValidateMessages.field(message, field).celValue(); + } + + @Override + public Optional find(String fieldName) { + FieldDescriptor field = ValidateMessages.requiredField(descriptor, fieldName); + return message.hasField(field) ? Optional.of(select(fieldName)) : Optional.empty(); + } +} diff --git a/src/main/java/build/buf/protovalidate/ValidateMessageValue.java b/src/main/java/build/buf/protovalidate/ValidateMessageValue.java index 1fe8ed8ca..036bc507d 100644 --- a/src/main/java/build/buf/protovalidate/ValidateMessageValue.java +++ b/src/main/java/build/buf/protovalidate/ValidateMessageValue.java @@ -46,7 +46,7 @@ public Object rawValue() { @Override public Object celValue() { - return message.celValue(); + return ValidateMessages.cel(message); } @Override diff --git a/src/main/java/build/buf/protovalidate/ValidateMessages.java b/src/main/java/build/buf/protovalidate/ValidateMessages.java new file mode 100644 index 000000000..4e7576039 --- /dev/null +++ b/src/main/java/build/buf/protovalidate/ValidateMessages.java @@ -0,0 +1,85 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import java.time.Duration; +import java.time.Instant; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +/** Reads {@link ValidateMessage} fields as validator {@link Value}s and CEL values. */ +final class ValidateMessages { + private static final Set WRAPPER_TYPES = + new HashSet<>( + Arrays.asList( + "google.protobuf.DoubleValue", + "google.protobuf.FloatValue", + "google.protobuf.Int64Value", + "google.protobuf.UInt64Value", + "google.protobuf.Int32Value", + "google.protobuf.UInt32Value", + "google.protobuf.BoolValue", + "google.protobuf.StringValue", + "google.protobuf.BytesValue")); + + private ValidateMessages() {} + + static Value field(ValidateMessage message, FieldDescriptor field) { + if (message instanceof ProtobufValidateMessage) { + return ((ProtobufValidateMessage) message).fieldValue(field); + } + return new PlainValue(field, message.getField(field), false); + } + + /** Returns what CEL sees for a message, using CEL's own types for well-known types. */ + static Object cel(ValidateMessage message) { + if (message instanceof ProtobufValidateMessage) { + return ((ProtobufValidateMessage) message).getMessage(); + } + Descriptor descriptor = message.getDescriptorForType(); + String name = descriptor.getFullName(); + if (name.equals("google.protobuf.Timestamp")) { + return Instant.ofEpochSecond(longField(message, "seconds"), longField(message, "nanos")); + } + if (name.equals("google.protobuf.Duration")) { + return Duration.ofSeconds(longField(message, "seconds"), longField(message, "nanos")); + } + if (isWrapper(descriptor)) { + return field(message, requiredField(descriptor, "value")).celValue(); + } + return new ValidateMessageStruct(message); + } + + static boolean isWrapper(Descriptor descriptor) { + return WRAPPER_TYPES.contains(descriptor.getFullName()); + } + + static FieldDescriptor requiredField(Descriptor descriptor, String name) { + FieldDescriptor field = descriptor.findFieldByName(name); + if (field == null) { + throw new IllegalArgumentException( + "no field \"" + name + "\" in " + descriptor.getFullName()); + } + return field; + } + + private static long longField(ValidateMessage message, String name) { + FieldDescriptor field = requiredField(message.getDescriptorForType(), name); + return ((Number) field(message, field).rawValue()).longValue(); + } +} diff --git a/src/main/java/build/buf/protovalidate/Value.java b/src/main/java/build/buf/protovalidate/Value.java index c9ce70dc9..3acb4bed7 100644 --- a/src/main/java/build/buf/protovalidate/Value.java +++ b/src/main/java/build/buf/protovalidate/Value.java @@ -21,36 +21,10 @@ /** * {@link Value} is a wrapper around a protobuf value that provides helper methods for accessing the - * value. - * - *

Field values and collection elements use the following representations. Unsigned raw integers - * use the signed Java type with the same bit pattern. Enum numbers must fit in a signed 32-bit - * integer. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Value representations by protobuf type
Protobuf type{@code rawValue()}{@code jvmValue(Object.class)}
32-bit signed integers{@link Integer}{@link Integer} or {@link Long}
64-bit signed integers{@link Long}{@link Long}
32-bit unsigned integers{@link Integer}{@link com.google.common.primitives.UnsignedLong}
64-bit unsigned integers{@link Long}{@link com.google.common.primitives.UnsignedLong}
float{@link Float}{@link Double}
double{@link Double}{@link Double}
bool{@link Boolean}{@link Boolean}
string{@link String}{@link String}
bytes{@link com.google.protobuf.ByteString}{@link dev.cel.common.values.CelByteString}
enum{@link Descriptors.EnumValueDescriptor}, {@link Integer}, or {@link Long}{@link Integer} or {@link Long}
message or groupThe runtime's message objectThe runtime's message object or its adapted representation
repeated{@link List} of raw elements{@link List} of JVM elements
map{@link Map} of raw keys and values, or a {@link List} of protobuf-java entry messages{@link Map} of JVM keys and values
- * - *

Message validation and emptiness checks use {@link #messageValue()}, so message objects need - * not implement protobuf-java's {@code Message} or compare equal across runtimes. The - * representation returned by {@link #celValue()} must independently satisfy CEL's type - * requirements. + * value. Implementations convert from the runtime's representation; see {@link + * ValidateMessage#getField} for the plain representation other runtimes supply. */ -public interface Value { +interface Value { /** * Get the field descriptor that corresponds to the underlying Value, if it is a message field. * diff --git a/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java b/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java index 5dab7e67c..b767c1318 100644 --- a/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java +++ b/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java @@ -62,7 +62,7 @@ public List evaluate(Value val, boolean failFast) // proto3 message-typed field absent — no value to validate. return RuleViolation.NO_VIOLATIONS; } - Value innerValue = message.getField(innerField); + Value innerValue = ValidateMessages.field(message, innerField); return inner.evaluate(innerValue, failFast); } } diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java index e6471a456..6621ced82 100644 --- a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java +++ b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java @@ -34,9 +34,6 @@ import com.google.protobuf.DescriptorProtos.MessageOptions; import com.google.protobuf.Descriptors; import com.google.protobuf.Timestamp; -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -838,298 +835,8 @@ public boolean hasField(Descriptors.FieldDescriptor field) { } @Override - public Value getField(Descriptors.FieldDescriptor field) { - Object value = fields.get(field); - // A message-typed singular field is backed by another ValidateMessage; wrap it so the - // embedded-message evaluator can recurse without a protobuf Message. - if (value instanceof ValidateMessage) { - return new ValidateMessageFieldValue(field, (ValidateMessage) value); - } - // Map fields need a runtime-independent Value: ObjectValue.mapValue() expects - // protobuf map-entry messages, which an alternative runtime would not have. - if (field.isMapField()) { - Map map = value == null ? Collections.emptyMap() : (Map) value; - return new MapFieldValue(field, map); - } - // Repeated fields: a custom Value so message elements recurse as ValidateMessages. - if (field.isRepeated()) { - List list = value == null ? Collections.emptyList() : (List) value; - return new RepeatedFieldValue(field, list); - } - // A singular message field must be backed by a ValidateMessage (handled above). Reaching - // here means a non-ValidateMessage value was stored for a message field, which would - // otherwise fail later as a ClassCastException to com.google.protobuf.Message. - if (isMessage(field)) { - throw new IllegalArgumentException( - "message field \"" - + field.getName() - + "\" must be provided as a ValidateMessage, but got " - + (value == null ? "null" : value.getClass().getName())); - } - if (value == null) { - value = field.getDefaultValue(); - } - return new ObjectValue(field, value); - } - - @Override - public Object celValue() { - // Well-known types must surface their CEL-native form (e.g. Timestamp -> Instant) - // so the standard WKT rules, which expect `this` to be that form, can evaluate. - Object wellKnown = wellKnownCelValue(); - if (wellKnown != null) { - return wellKnown; - } - // Otherwise: CEL's runtime dispatches field selection on the actual object, so a - // plain Map keyed by field name works in place of a protobuf Message. Each field - // delegates to its Value's own CEL conversion (nested messages, repeated, maps). - Map out = new HashMap<>(); - for (Descriptors.FieldDescriptor field : fields.keySet()) { - out.put(field.getName(), getField(field).celValue()); - } - return out; - } - - /** - * Returns the CEL-native representation if this message wraps a well-known type, otherwise - * {@code null}. Mirrors how {@code ProtoAdapter} converts these messages for the protobuf - * runtime, but builds the value from the field map instead of a {@code Message}. - */ - private @Nullable Object wellKnownCelValue() { - switch (descriptor.getFullName()) { - case "google.protobuf.Timestamp": - return Instant.ofEpochSecond(longField("seconds"), longField("nanos")); - case "google.protobuf.Duration": - return Duration.ofSeconds(longField("seconds"), longField("nanos")); - case "google.protobuf.DoubleValue": - case "google.protobuf.FloatValue": - case "google.protobuf.Int64Value": - case "google.protobuf.UInt64Value": - case "google.protobuf.Int32Value": - case "google.protobuf.UInt32Value": - case "google.protobuf.BoolValue": - case "google.protobuf.StringValue": - case "google.protobuf.BytesValue": - Descriptors.FieldDescriptor valueField = descriptor.findFieldByName("value"); - Object raw = fields.get(valueField); - return ProtoAdapter.scalarToCel( - valueField.getType(), raw == null ? valueField.getDefaultValue() : raw); - default: - return null; - } - } - - /** Reads a numeric field as a long, defaulting to 0 when unset. */ - private long longField(String name) { - Object value = fields.get(descriptor.findFieldByName(name)); - return value == null ? 0L : ((Number) value).longValue(); - } - } - - /** A {@link Value} for a message-typed field, backed by a nested {@link ValidateMessage}. */ - private static final class ValidateMessageFieldValue implements Value { - private final Descriptors.FieldDescriptor fieldDescriptor; - private final ValidateMessage message; - - ValidateMessageFieldValue( - Descriptors.FieldDescriptor fieldDescriptor, ValidateMessage message) { - this.fieldDescriptor = fieldDescriptor; - this.message = message; - } - - @Override - public Descriptors.FieldDescriptor fieldDescriptor() { - return fieldDescriptor; - } - - @Override - public ValidateMessage messageValue() { - return message; - } - - @Override - public Object rawValue() { - return message; - } - - @Override - public Object celValue() { - return message.celValue(); - } - - @Override - public T jvmValue(Class clazz) { - return clazz.cast(message.celValue()); - } - - @Override - public List repeatedValue() { - return Collections.emptyList(); - } - - @Override - public Map mapValue() { - return Collections.emptyMap(); - } - } - - /** - * A {@link Value} for a map field, backed by a plain {@link Map} of raw key/value pairs. The - * key/value field descriptors come from the synthetic map-entry type, so each pair is exposed as - * an {@link ObjectValue} without needing protobuf map-entry messages. - */ - private static final class MapFieldValue implements Value { - private final Descriptors.FieldDescriptor fieldDescriptor; - private final Descriptors.FieldDescriptor keyDescriptor; - private final Descriptors.FieldDescriptor valueDescriptor; - private final Map value; - - MapFieldValue(Descriptors.FieldDescriptor fieldDescriptor, Map value) { - this.fieldDescriptor = fieldDescriptor; - this.keyDescriptor = fieldDescriptor.getMessageType().findFieldByNumber(1); - this.valueDescriptor = fieldDescriptor.getMessageType().findFieldByNumber(2); - this.value = value; - } - - @Override - public Descriptors.FieldDescriptor fieldDescriptor() { - return fieldDescriptor; - } - - @Override - public ValidateMessage messageValue() { - return null; - } - - @Override - public Object rawValue() { - return value; - } - - @Override - public Object celValue() { - // Map keys are always scalar/enum; values may be messages (backed by ValidateMessages). - Map out = new HashMap<>(value.size()); - for (Map.Entry entry : value.entrySet()) { - out.put( - ProtoAdapter.scalarToCel(keyDescriptor.getType(), entry.getKey()), - celValueOf(valueDescriptor, entry.getValue())); - } - return out; - } - - @Override - public T jvmValue(Class clazz) { - return clazz.cast(value); - } - - @Override - public List repeatedValue() { - return Collections.emptyList(); - } - - @Override - public Map mapValue() { - Map out = new HashMap<>(value.size()); - for (Map.Entry entry : value.entrySet()) { - out.put( - new ObjectValue(keyDescriptor, entry.getKey()), - mapValueElement(valueDescriptor, entry.getValue())); - } - return out; - } - } - - /** - * A {@link Value} for a repeated field, backed by a plain {@link List} of raw elements. Scalar - * elements reuse {@link ListElementValue}; message elements are backed by ValidateMessages so - * they recurse without a protobuf Message. - */ - private static final class RepeatedFieldValue implements Value { - private final Descriptors.FieldDescriptor fieldDescriptor; - private final List values; - - RepeatedFieldValue(Descriptors.FieldDescriptor fieldDescriptor, List values) { - this.fieldDescriptor = fieldDescriptor; - this.values = values; - } - - @Override - public Descriptors.FieldDescriptor fieldDescriptor() { - return fieldDescriptor; - } - - @Override - public ValidateMessage messageValue() { - return null; - } - - @Override - public Object rawValue() { - return values; - } - - @Override - public Object celValue() { - List out = new ArrayList<>(values.size()); - for (Object element : values) { - out.add(celValueOf(fieldDescriptor, element)); - } - return out; - } - - @Override - public T jvmValue(Class clazz) { - return clazz.cast(values); - } - - @Override - public List repeatedValue() { - List out = new ArrayList<>(values.size()); - for (Object element : values) { - out.add(repeatedElement(fieldDescriptor, element)); - } - return out; - } - - @Override - public Map mapValue() { - return Collections.emptyMap(); - } - } - - /** Whether a descriptor refers to a message (as opposed to a scalar or enum). */ - private static boolean isMessage(Descriptors.FieldDescriptor descriptor) { - return descriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE; - } - - /** - * Wraps a repeated element as a {@link Value}: a {@link ValidateMessageFieldValue} for messages, - * otherwise a {@link ListElementValue}, mirroring {@code ObjectValue.repeatedValue()}. - */ - private static Value repeatedElement(Descriptors.FieldDescriptor descriptor, Object value) { - if (isMessage(descriptor)) { - return new ValidateMessageFieldValue(descriptor, (ValidateMessage) value); - } - return new ListElementValue(descriptor, value); - } - - /** - * Wraps a map value as a {@link Value}: a {@link ValidateMessageFieldValue} for messages, - * otherwise an {@link ObjectValue}, mirroring {@code ObjectValue.mapValue()}. - */ - private static Value mapValueElement(Descriptors.FieldDescriptor descriptor, Object value) { - if (isMessage(descriptor)) { - return new ValidateMessageFieldValue(descriptor, (ValidateMessage) value); - } - return new ObjectValue(descriptor, value); - } - - /** Converts a single repeated element or map value to its CEL representation. */ - private static Object celValueOf(Descriptors.FieldDescriptor descriptor, Object value) { - if (isMessage(descriptor)) { - return ((ValidateMessage) value).celValue(); + public @Nullable Object getField(Descriptors.FieldDescriptor field) { + return fields.get(field); } - return ProtoAdapter.scalarToCel(descriptor.getType(), value); } } diff --git a/src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java b/src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java index 77974a9aa..b9417c521 100644 --- a/src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java +++ b/src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java @@ -22,7 +22,6 @@ import build.buf.protovalidate.ValidationResult; import build.buf.protovalidate.Validator; import build.buf.protovalidate.ValidatorFactory; -import build.buf.protovalidate.Value; import build.buf.protovalidate.exceptions.ValidationException; import build.buf.validate.BytesRules; import build.buf.validate.EnumRules; @@ -37,7 +36,6 @@ import build.buf.validate.UInt32Rules; import build.buf.validate.UInt64Rules; import build.buf.validate.ValidateProto; -import com.google.common.primitives.UnsignedLong; import com.google.protobuf.ByteString; import com.google.protobuf.DescriptorProtos.DescriptorProto; import com.google.protobuf.DescriptorProtos.EnumDescriptorProto; @@ -54,14 +52,13 @@ import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.DynamicMessage; import com.google.protobuf.UnknownFieldSet; -import dev.cel.common.values.CelByteString; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import org.jspecify.annotations.Nullable; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -507,116 +504,8 @@ public boolean hasField(FieldDescriptor field) { } @Override - public Value getField(FieldDescriptor field) { - Object value = fields.get(field.getName()); - if (value == null) { - if (field.isMapField()) { - value = Collections.emptyMap(); - } else if (field.isRepeated()) { - value = Collections.emptyList(); - } else { - value = field.getDefaultValue(); - } - } - return new ExternalValue(field, value); - } - - @Override - public Object celValue() { - Map values = new HashMap<>(); - for (FieldDescriptor field : descriptor.getFields()) { - values.put(field.getName(), getField(field).celValue()); - } - return values; - } - } - - private static final class ExternalValue implements Value { - private final FieldDescriptor field; - private final Object value; - - ExternalValue(FieldDescriptor field, Object value) { - this.field = field; - this.value = value; - } - - @Override - public FieldDescriptor fieldDescriptor() { - return field; - } - - @Override - public ValidateMessage messageValue() { - return value instanceof ExternalMessage ? (ExternalMessage) value : null; - } - - @Override - public Object rawValue() { - return value; - } - - @Override - public List repeatedValue() { - List values = new ArrayList<>(); - if (value instanceof List) { - for (Object item : (List) value) { - values.add(new ExternalValue(field, item)); - } - } - return values; - } - - @Override - public Map mapValue() { - Map values = new HashMap<>(); - if (value instanceof Map) { - ((Map) value) - .forEach((key, item) -> - values.put( - new ExternalValue(field.getMessageType().findFieldByNumber(1), key), - new ExternalValue(field.getMessageType().findFieldByNumber(2), item))); - } - return values; - } - - @Override - public Object celValue() { - if (value instanceof Integer && field.getType() == FieldDescriptor.Type.UINT32) { - return UnsignedLong.valueOf(Integer.toUnsignedLong((Integer) value)); - } - if (value instanceof Long && field.getType() == FieldDescriptor.Type.UINT64) { - return UnsignedLong.fromLongBits((Long) value); - } - if (value instanceof Integer) { - return ((Integer) value).longValue(); - } - if (value instanceof Float) { - return ((Float) value).doubleValue(); - } - if (value instanceof ByteString) { - return CelByteString.of(((ByteString) value).toByteArray()); - } - if (value instanceof ExternalMessage) { - return ((ExternalMessage) value).celValue(); - } - if (value instanceof Map) { - Map values = new HashMap<>(); - mapValue().forEach((key, item) -> values.put(key.celValue(), item.celValue())); - return values; - } - if (value instanceof List) { - return repeatedValue().stream().map(Value::celValue).collect(Collectors.toList()); - } - return value; - } - - @Override - public T jvmValue(Class clazz) { - return clazz.cast( - (value instanceof Integer && field.getJavaType() == FieldDescriptor.JavaType.ENUM) - || value instanceof ExternalMessage - ? value - : celValue()); + public @Nullable Object getField(FieldDescriptor field) { + return fields.get(field.getName()); } } } From 4790d27b71b594a955de996b5e65f44f18b460e7 Mon Sep 17 00:00:00 2001 From: Jon Bodner Date: Thu, 3 Dec 2026 11:50:23 -0500 Subject: [PATCH 10/23] Validate other runtimes' messages by converting them to DynamicMessage 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. --- README.md | 8 +- .../build/buf/protovalidate/AnyEvaluator.java | 5 +- .../build/buf/protovalidate/CelPrograms.java | 2 +- .../protovalidate/EmptyValidateMessage.java | 43 ---- .../buf/protovalidate/EnumEvaluator.java | 4 +- .../buf/protovalidate/FieldEvaluator.java | 19 +- .../buf/protovalidate/ListElementValue.java | 20 +- .../build/buf/protovalidate/MapEvaluator.java | 8 +- .../buf/protovalidate/MapRulesEvaluator.java | 5 +- .../protovalidate/MessageOneofEvaluator.java | 5 +- .../build/buf/protovalidate/MessageValue.java | 20 +- .../build/buf/protovalidate/ObjectValue.java | 24 +-- .../buf/protovalidate/OneofEvaluator.java | 9 +- .../build/buf/protovalidate/PlainValue.java | 196 ------------------ .../ProtobufValidateMessage.java | 102 --------- .../buf/protovalidate/RuleViolation.java | 2 +- .../buf/protovalidate/ValidateMessage.java | 62 ++---- .../ValidateMessageConverter.java | 93 +++++++++ .../protovalidate/ValidateMessageStruct.java | 73 ------- .../protovalidate/ValidateMessageValue.java | 69 ------ .../buf/protovalidate/ValidateMessages.java | 85 -------- .../build/buf/protovalidate/Validator.java | 10 +- .../buf/protovalidate/ValidatorImpl.java | 14 +- .../java/build/buf/protovalidate/Value.java | 59 +++--- .../buf/protovalidate/ValueEvaluator.java | 18 +- .../protovalidate/WrappedValueEvaluator.java | 11 +- .../ValidateMessageConverterTest.java | 172 +++++++++++++++ .../protovalidate/ValidateMessageTest.java | 33 +-- .../external/ExternalRuntimeTest.java | 13 +- 29 files changed, 412 insertions(+), 772 deletions(-) delete mode 100644 src/main/java/build/buf/protovalidate/EmptyValidateMessage.java delete mode 100644 src/main/java/build/buf/protovalidate/PlainValue.java delete mode 100644 src/main/java/build/buf/protovalidate/ProtobufValidateMessage.java create mode 100644 src/main/java/build/buf/protovalidate/ValidateMessageConverter.java delete mode 100644 src/main/java/build/buf/protovalidate/ValidateMessageStruct.java delete mode 100644 src/main/java/build/buf/protovalidate/ValidateMessageValue.java delete mode 100644 src/main/java/build/buf/protovalidate/ValidateMessages.java create mode 100644 src/test/java/build/buf/protovalidate/ValidateMessageConverterTest.java diff --git a/README.md b/README.md index 00cba8bde..d5db71dc0 100644 --- a/README.md +++ b/README.md @@ -79,21 +79,21 @@ Forward compatibility is preserved by a clone-and-clear contract: when protovali ## Other Protobuf runtimes -`protovalidate-java` validates protobuf-java messages out of the box. To validate messages from another JVM Protobuf runtime without converting them to protobuf-java first, wrap each message in a `ValidateMessage` that returns plain Java values for its fields: +`protovalidate-java` validates protobuf-java messages out of the box. To validate messages from another JVM Protobuf runtime, wrap each message in a `ValidateMessage` that returns plain Java values for its fields: ```java final class MyMessage implements ValidateMessage { @Override public Descriptor getDescriptorForType() { ... } // Repeated and map fields are present when non-empty. @Override public boolean hasField(FieldDescriptor field) { ... } - // The field's value, or null when unset; nested messages are also ValidateMessages. - @Override public @Nullable Object getField(FieldDescriptor field) { ... } + // The value of a present field; nested messages are also ValidateMessages. + @Override public Object getField(FieldDescriptor field) { ... } } ValidationResult result = validator.validate(new MyMessage(message)); ``` -The Javadoc on `ValidateMessage.getField` lists the Java type to return for each Protobuf field type. `protovalidate-java` converts these values for CEL itself, so implementations don't depend on CEL. For a complete implementation backed by a `Map`, see [`ExternalRuntimeTest`](src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java). +The Javadoc on `ValidateMessage.getField` lists the Java type to return for each Protobuf field type. `protovalidate-java` copies the fields into a protobuf-java `DynamicMessage` and validates that, so a message from another runtime is validated exactly like a protobuf-java one. For a complete implementation backed by a `Map`, see [`ExternalRuntimeTest`](src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java). ## Additional languages and repositories diff --git a/src/main/java/build/buf/protovalidate/AnyEvaluator.java b/src/main/java/build/buf/protovalidate/AnyEvaluator.java index 8498fb082..d7d18356d 100644 --- a/src/main/java/build/buf/protovalidate/AnyEvaluator.java +++ b/src/main/java/build/buf/protovalidate/AnyEvaluator.java @@ -19,6 +19,7 @@ import build.buf.validate.FieldPath; import build.buf.validate.FieldRules; import com.google.protobuf.Descriptors; +import com.google.protobuf.Message; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; @@ -77,12 +78,12 @@ final class AnyEvaluator implements Evaluator { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - ValidateMessage anyValue = val.messageValue(); + Message anyValue = val.messageValue(); if (anyValue == null) { return RuleViolation.NO_VIOLATIONS; } List violationList = new ArrayList<>(); - String typeURL = ValidateMessages.field(anyValue, typeURLDescriptor).jvmValue(String.class); + String typeURL = (String) anyValue.getField(typeURLDescriptor); if (!in.isEmpty() && !in.contains(typeURL)) { RuleViolation.Builder violation = RuleViolation.newBuilder() diff --git a/src/main/java/build/buf/protovalidate/CelPrograms.java b/src/main/java/build/buf/protovalidate/CelPrograms.java index f88e56035..ed712f796 100644 --- a/src/main/java/build/buf/protovalidate/CelPrograms.java +++ b/src/main/java/build/buf/protovalidate/CelPrograms.java @@ -45,7 +45,7 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - CelVariableResolver bindings = Variable.newThisVariable(val.celValue()); + CelVariableResolver bindings = Variable.newThisVariable(val.value(Object.class)); List violations = new ArrayList<>(); for (CompiledProgram program : programs) { RuleViolation.Builder violation = program.eval(val, bindings); diff --git a/src/main/java/build/buf/protovalidate/EmptyValidateMessage.java b/src/main/java/build/buf/protovalidate/EmptyValidateMessage.java deleted file mode 100644 index 533fac668..000000000 --- a/src/main/java/build/buf/protovalidate/EmptyValidateMessage.java +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2023-2026 Buf Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package build.buf.protovalidate; - -import com.google.protobuf.Descriptors.Descriptor; -import com.google.protobuf.Descriptors.FieldDescriptor; -import org.jspecify.annotations.Nullable; - -/** Stands in for an unset message field, which has no runtime object of its own. */ -final class EmptyValidateMessage implements ValidateMessage { - private final Descriptor descriptor; - - EmptyValidateMessage(Descriptor descriptor) { - this.descriptor = descriptor; - } - - @Override - public Descriptor getDescriptorForType() { - return descriptor; - } - - @Override - public boolean hasField(FieldDescriptor field) { - return false; - } - - @Override - public @Nullable Object getField(FieldDescriptor field) { - return null; - } -} diff --git a/src/main/java/build/buf/protovalidate/EnumEvaluator.java b/src/main/java/build/buf/protovalidate/EnumEvaluator.java index a77613cba..d2fa00df4 100644 --- a/src/main/java/build/buf/protovalidate/EnumEvaluator.java +++ b/src/main/java/build/buf/protovalidate/EnumEvaluator.java @@ -77,11 +77,11 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - Number enumValue = val.jvmValue(Number.class); + Object enumValue = val.value(Object.class); if (enumValue == null) { return RuleViolation.NO_VIOLATIONS; } - if (!values.contains(enumValue.longValue())) { + if (!values.contains(enumValue)) { return Collections.singletonList( RuleViolation.newBuilder() .addAllRulePathElements(helper.getRulePrefixElements()) diff --git a/src/main/java/build/buf/protovalidate/FieldEvaluator.java b/src/main/java/build/buf/protovalidate/FieldEvaluator.java index 8b83baf4e..877aec5ea 100644 --- a/src/main/java/build/buf/protovalidate/FieldEvaluator.java +++ b/src/main/java/build/buf/protovalidate/FieldEvaluator.java @@ -19,6 +19,7 @@ import build.buf.validate.FieldRules; import build.buf.validate.Ignore; import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Message; import java.util.Collections; import java.util.List; @@ -94,11 +95,11 @@ public List evaluate(Value val, boolean failFast) if (this.shouldIgnoreAlways()) { return RuleViolation.NO_VIOLATIONS; } - ValidateMessage message = val.messageValue(); + Message message = val.messageValue(); if (message == null) { return RuleViolation.NO_VIOLATIONS; } - boolean hasField = message.hasField(descriptor); + boolean hasField = isFieldSet(message, descriptor); if (required && !hasField) { return Collections.singletonList( RuleViolation.newBuilder() @@ -112,6 +113,18 @@ public List evaluate(Value val, boolean failFast) if (this.shouldIgnoreEmpty() && !hasField) { return RuleViolation.NO_VIOLATIONS; } - return valueEvaluator.evaluate(ValidateMessages.field(message, descriptor), failFast); + return valueEvaluator.evaluate( + new ObjectValue(descriptor, message.getField(descriptor)), failFast); + } + + /** + * Returns whether the given field is set on the message. Handles repeated and map fields, which + * are not supported by {@link Message#hasField}. + */ + static boolean isFieldSet(Message message, FieldDescriptor field) { + if (field.isRepeated()) { + return message.getRepeatedFieldCount(field) != 0; + } + return message.hasField(field); } } diff --git a/src/main/java/build/buf/protovalidate/ListElementValue.java b/src/main/java/build/buf/protovalidate/ListElementValue.java index 7987aca7e..8e397d328 100644 --- a/src/main/java/build/buf/protovalidate/ListElementValue.java +++ b/src/main/java/build/buf/protovalidate/ListElementValue.java @@ -29,8 +29,6 @@ final class ListElementValue implements Value { /** Object type since the object type is inferred from the field descriptor. */ private final Object value; - private final @Nullable ProtobufValidateMessage message; - /** * {@link com.google.protobuf.Descriptors.FieldDescriptor} is the field descriptor for the value. */ @@ -39,10 +37,6 @@ final class ListElementValue implements Value { ListElementValue(Descriptors.FieldDescriptor fieldDescriptor, Object value) { this.value = value; this.fieldDescriptor = fieldDescriptor; - this.message = - fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE - ? new ProtobufValidateMessage((Message) value) - : null; } @Override @@ -51,17 +45,15 @@ final class ListElementValue implements Value { } @Override - public @Nullable ValidateMessage messageValue() { - return message; - } - - @Override - public Object celValue() { - return ProtoAdapter.scalarToCel(fieldDescriptor.getType(), value); + public @Nullable Message messageValue() { + if (fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { + return (Message) value; + } + return null; } @Override - public T jvmValue(Class clazz) { + public T value(Class clazz) { Descriptors.FieldDescriptor.Type type = fieldDescriptor.getType(); if (type == Descriptors.FieldDescriptor.Type.MESSAGE) { return clazz.cast(value); diff --git a/src/main/java/build/buf/protovalidate/MapEvaluator.java b/src/main/java/build/buf/protovalidate/MapEvaluator.java index 0dfcecbfb..bc418e977 100644 --- a/src/main/java/build/buf/protovalidate/MapEvaluator.java +++ b/src/main/java/build/buf/protovalidate/MapEvaluator.java @@ -155,19 +155,19 @@ private List evalPairs(Value key, Value value, boolean fa case TYPE_SINT64: case TYPE_SFIXED32: case TYPE_SFIXED64: - fieldPathElementBuilder.setIntKey(key.jvmValue(Number.class).longValue()); + fieldPathElementBuilder.setIntKey(key.value(Number.class).longValue()); break; case TYPE_UINT32: case TYPE_UINT64: case TYPE_FIXED32: case TYPE_FIXED64: - fieldPathElementBuilder.setUintKey(key.jvmValue(Number.class).longValue()); + fieldPathElementBuilder.setUintKey(key.value(Number.class).longValue()); break; case TYPE_BOOL: - fieldPathElementBuilder.setBoolKey(key.jvmValue(Boolean.class)); + fieldPathElementBuilder.setBoolKey(key.value(Boolean.class)); break; case TYPE_STRING: - fieldPathElementBuilder.setStringKey(key.jvmValue(String.class)); + fieldPathElementBuilder.setStringKey(key.value(String.class)); break; default: throw new ExecutionException("Unexpected map key type"); diff --git a/src/main/java/build/buf/protovalidate/MapRulesEvaluator.java b/src/main/java/build/buf/protovalidate/MapRulesEvaluator.java index fea8bccda..39455b9e8 100644 --- a/src/main/java/build/buf/protovalidate/MapRulesEvaluator.java +++ b/src/main/java/build/buf/protovalidate/MapRulesEvaluator.java @@ -18,7 +18,6 @@ import build.buf.validate.MapRules; import com.google.protobuf.Descriptors.FieldDescriptor; import java.util.List; -import java.util.Map; import org.jspecify.annotations.Nullable; /** @@ -99,8 +98,8 @@ public boolean tautology() { public List evaluate(Value val, boolean failFast) { // Java protobuf returns map fields as a List of synthetic key/value entry messages; the size // is the pair count. - Object entries = val.rawValue(); - long size = entries instanceof Map ? ((Map) entries).size() : ((List) entries).size(); + List entries = (List) val.rawValue(); + long size = entries.size(); List violations = null; if (minPairs != null && size < minPairs) { diff --git a/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java b/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java index c7e9331a9..aecce4e92 100644 --- a/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java +++ b/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java @@ -16,6 +16,7 @@ import build.buf.protovalidate.exceptions.ExecutionException; import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Message; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @@ -44,13 +45,13 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - ValidateMessage msg = val.messageValue(); + Message msg = val.messageValue(); if (msg == null) { return RuleViolation.NO_VIOLATIONS; } int hasCount = 0; for (FieldDescriptor field : fields) { - if (msg.hasField(field)) { + if (FieldEvaluator.isFieldSet(msg, field)) { hasCount++; } } diff --git a/src/main/java/build/buf/protovalidate/MessageValue.java b/src/main/java/build/buf/protovalidate/MessageValue.java index 08012a36a..fa96e3b8c 100644 --- a/src/main/java/build/buf/protovalidate/MessageValue.java +++ b/src/main/java/build/buf/protovalidate/MessageValue.java @@ -24,7 +24,8 @@ /** The {@link Value} type that contains a {@link com.google.protobuf.Message}. */ final class MessageValue implements Value { - private final ProtobufValidateMessage value; + /** Object type since the object type is inferred from the field descriptor. */ + private final Object value; /** * Constructs a {@link MessageValue} with the provided message value. @@ -32,7 +33,7 @@ final class MessageValue implements Value { * @param value The message value. */ MessageValue(Message value) { - this.value = new ProtobufValidateMessage(value); + this.value = value; } @Override @@ -41,20 +42,13 @@ final class MessageValue implements Value { } @Override - public ValidateMessage messageValue() { - return value; - } - - @Override - public Object celValue() { - return value.getMessage(); + public Message messageValue() { + return (Message) value; } @Override - public T jvmValue(Class clazz) { - throw new UnsupportedOperationException( - "jvmValue returns a raw scalar for native rule evaluation and is not supported on a message" - + " value; use messageValue() or celValue() instead"); + public T value(Class clazz) { + return clazz.cast(value); } @Override diff --git a/src/main/java/build/buf/protovalidate/ObjectValue.java b/src/main/java/build/buf/protovalidate/ObjectValue.java index 5042f230c..9a53574ac 100644 --- a/src/main/java/build/buf/protovalidate/ObjectValue.java +++ b/src/main/java/build/buf/protovalidate/ObjectValue.java @@ -35,8 +35,6 @@ final class ObjectValue implements Value { /** Object type since the object type is inferred from the field descriptor. */ private final Object value; - private final @Nullable ProtobufValidateMessage message; - /** * Constructs a new {@link ObjectValue}. * @@ -46,11 +44,6 @@ final class ObjectValue implements Value { ObjectValue(Descriptors.FieldDescriptor fieldDescriptor, Object value) { this.fieldDescriptor = fieldDescriptor; this.value = value; - this.message = - !fieldDescriptor.isRepeated() - && fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE - ? new ProtobufValidateMessage((Message) value) - : null; } @Override @@ -60,20 +53,15 @@ public Descriptors.FieldDescriptor fieldDescriptor() { @Nullable @Override - public ValidateMessage messageValue() { - return message; - } - - @Override - public Object celValue() { - return ProtoAdapter.toCel(fieldDescriptor, value); + public Message messageValue() { + if (fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { + return (Message) value; + } + return null; } @Override - public T jvmValue(Class clazz) { - if (value instanceof Descriptors.EnumValueDescriptor) { - return clazz.cast((long) ((Descriptors.EnumValueDescriptor) value).getNumber()); - } + public T value(Class clazz) { return clazz.cast(ProtoAdapter.toCel(fieldDescriptor, value)); } diff --git a/src/main/java/build/buf/protovalidate/OneofEvaluator.java b/src/main/java/build/buf/protovalidate/OneofEvaluator.java index 8a16323ab..5ddccd6d6 100644 --- a/src/main/java/build/buf/protovalidate/OneofEvaluator.java +++ b/src/main/java/build/buf/protovalidate/OneofEvaluator.java @@ -17,6 +17,7 @@ import build.buf.protovalidate.exceptions.ExecutionException; import build.buf.validate.FieldPathElement; import com.google.protobuf.Descriptors.OneofDescriptor; +import com.google.protobuf.Message; import java.util.Collections; import java.util.List; @@ -47,12 +48,8 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - ValidateMessage message = val.messageValue(); - if (message == null) { - return RuleViolation.NO_VIOLATIONS; - } - boolean hasField = message.getOneofFieldDescriptor(descriptor) != null; - if (!required || hasField) { + Message message = val.messageValue(); + if (message == null || !required || (message.getOneofFieldDescriptor(descriptor) != null)) { return RuleViolation.NO_VIOLATIONS; } return Collections.singletonList( diff --git a/src/main/java/build/buf/protovalidate/PlainValue.java b/src/main/java/build/buf/protovalidate/PlainValue.java deleted file mode 100644 index 7ad58f70b..000000000 --- a/src/main/java/build/buf/protovalidate/PlainValue.java +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright 2023-2026 Buf Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package build.buf.protovalidate; - -import com.google.protobuf.ByteString; -import com.google.protobuf.Descriptors.EnumValueDescriptor; -import com.google.protobuf.Descriptors.FieldDescriptor; -import com.google.protobuf.Descriptors.FieldDescriptor.JavaType; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.jspecify.annotations.Nullable; - -/** - * {@link Value} over a plain field value from {@link ValidateMessage#getField}. A null value means - * the field is unset and reads as its protobuf default. - */ -final class PlainValue implements Value { - private final FieldDescriptor field; - private final @Nullable Object value; - // An element of a repeated field shares the field's descriptor but is a single value. - private final boolean element; - - PlainValue(FieldDescriptor field, @Nullable Object value, boolean element) { - this.field = field; - this.value = value; - this.element = element; - } - - @Override - public FieldDescriptor fieldDescriptor() { - return field; - } - - @Override - public @Nullable ValidateMessage messageValue() { - return isMessage() ? message() : null; - } - - @Override - public Object rawValue() { - if (isList()) { - return list(); - } - if (isMap()) { - return map(); - } - if (isMessage()) { - return message(); - } - return scalar(); - } - - @Override - public List repeatedValue() { - if (!isList()) { - return Collections.emptyList(); - } - List out = new ArrayList<>(); - for (Object item : list()) { - out.add(new PlainValue(field, item, true)); - } - return Collections.unmodifiableList(out); - } - - @Override - public Map mapValue() { - if (!isMap()) { - return Collections.emptyMap(); - } - FieldDescriptor keyField = field.getMessageType().findFieldByNumber(1); - FieldDescriptor valueField = field.getMessageType().findFieldByNumber(2); - Map out = new HashMap<>(); - for (Map.Entry entry : map().entrySet()) { - out.put( - new PlainValue(keyField, entry.getKey(), false), - new PlainValue(valueField, entry.getValue(), false)); - } - return Collections.unmodifiableMap(out); - } - - @Override - public Object celValue() { - if (isList()) { - List out = new ArrayList<>(); - for (Value item : repeatedValue()) { - out.add(item.celValue()); - } - return out; - } - if (isMap()) { - Map out = new HashMap<>(); - for (Map.Entry entry : mapValue().entrySet()) { - out.put(entry.getKey().celValue(), entry.getValue().celValue()); - } - return out; - } - if (isMessage()) { - return ValidateMessages.cel(message()); - } - return scalarCel(); - } - - @Override - public T jvmValue(Class clazz) { - if (isList()) { - List out = new ArrayList<>(); - for (Value item : repeatedValue()) { - out.add(item.jvmValue(Object.class)); - } - return clazz.cast(out); - } - if (isMap()) { - Map out = new HashMap<>(); - for (Map.Entry entry : mapValue().entrySet()) { - out.put(entry.getKey().jvmValue(Object.class), entry.getValue().jvmValue(Object.class)); - } - return clazz.cast(out); - } - if (isMessage()) { - return clazz.cast(message()); - } - return clazz.cast(scalarCel()); - } - - private boolean isList() { - return field.isRepeated() && !field.isMapField() && !element; - } - - private boolean isMap() { - return field.isMapField() && !element; - } - - private boolean isMessage() { - return !isList() && !isMap() && field.getJavaType() == JavaType.MESSAGE; - } - - private List list() { - return value == null ? Collections.emptyList() : (List) value; - } - - private Map map() { - return value == null ? Collections.emptyMap() : (Map) value; - } - - private ValidateMessage message() { - if (value == null) { - return new EmptyValidateMessage(field.getMessageType()); - } - if (!(value instanceof ValidateMessage)) { - throw new IllegalArgumentException( - "message field \"" - + field.getName() - + "\" must be provided as a ValidateMessage, but got " - + value.getClass().getName()); - } - return (ValidateMessage) value; - } - - private Object scalar() { - if (field.getJavaType() == JavaType.ENUM) { - if (value == null) { - return field.getEnumType().getValues().get(0).getNumber(); - } - return value instanceof EnumValueDescriptor - ? ((EnumValueDescriptor) value).getNumber() - : ((Number) value).intValue(); - } - if (value != null) { - return value; - } - return field.getJavaType() == JavaType.BYTE_STRING ? ByteString.EMPTY : field.getDefaultValue(); - } - - private Object scalarCel() { - Object raw = scalar(); - if (field.getJavaType() == JavaType.ENUM) { - return ((Integer) raw).longValue(); - } - return ProtoAdapter.scalarToCel(field.getType(), raw); - } -} diff --git a/src/main/java/build/buf/protovalidate/ProtobufValidateMessage.java b/src/main/java/build/buf/protovalidate/ProtobufValidateMessage.java deleted file mode 100644 index 1a15b63c5..000000000 --- a/src/main/java/build/buf/protovalidate/ProtobufValidateMessage.java +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2023-2026 Buf Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package build.buf.protovalidate; - -import com.google.protobuf.Descriptors.Descriptor; -import com.google.protobuf.Descriptors.EnumValueDescriptor; -import com.google.protobuf.Descriptors.FieldDescriptor; -import com.google.protobuf.Descriptors.OneofDescriptor; -import com.google.protobuf.Message; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import org.jspecify.annotations.Nullable; - -/** {@link ValidateMessage} over a protobuf-java {@link Message}. */ -final class ProtobufValidateMessage implements ValidateMessage { - private final Message message; - - ProtobufValidateMessage(Message message) { - this.message = message; - } - - Message getMessage() { - return message; - } - - /** The validator reads protobuf-java fields through this, skipping the plain conversion. */ - Value fieldValue(FieldDescriptor field) { - return new ObjectValue(field, message.getField(field)); - } - - @Override - public Descriptor getDescriptorForType() { - return message.getDescriptorForType(); - } - - @Override - public boolean hasField(FieldDescriptor field) { - return field.isRepeated() ? message.getRepeatedFieldCount(field) > 0 : message.hasField(field); - } - - @Override - public @Nullable FieldDescriptor getOneofFieldDescriptor(OneofDescriptor oneof) { - return message.getOneofFieldDescriptor(oneof); - } - - @Override - public boolean isEmpty() { - return message.equals(message.getDefaultInstanceForType()); - } - - @Override - public @Nullable Object getField(FieldDescriptor field) { - if (!field.isRepeated() && field.hasPresence() && !message.hasField(field)) { - return null; - } - Object value = message.getField(field); - if (field.isMapField()) { - FieldDescriptor keyField = field.getMessageType().findFieldByNumber(1); - FieldDescriptor valueField = field.getMessageType().findFieldByNumber(2); - Map out = new LinkedHashMap<>(); - for (Object entry : (List) value) { - Message entryMessage = (Message) entry; - out.put( - plain(keyField, entryMessage.getField(keyField)), - plain(valueField, entryMessage.getField(valueField))); - } - return out; - } - if (field.isRepeated()) { - List out = new ArrayList<>(); - for (Object element : (List) value) { - out.add(plain(field, element)); - } - return out; - } - return plain(field, value); - } - - private static Object plain(FieldDescriptor field, Object value) { - if (value instanceof EnumValueDescriptor) { - return ((EnumValueDescriptor) value).getNumber(); - } - if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { - return new ProtobufValidateMessage((Message) value); - } - return value; - } -} diff --git a/src/main/java/build/buf/protovalidate/RuleViolation.java b/src/main/java/build/buf/protovalidate/RuleViolation.java index 39d18930d..454d2f782 100644 --- a/src/main/java/build/buf/protovalidate/RuleViolation.java +++ b/src/main/java/build/buf/protovalidate/RuleViolation.java @@ -55,7 +55,7 @@ static class FieldValue implements Violation.FieldValue { * @param value A {@link Value} to create this {@link FieldValue} from. */ FieldValue(Value value) { - this.value = value.jvmValue(Object.class); + this.value = value.value(Object.class); this.descriptor = Objects.requireNonNull(value.fieldDescriptor()); } diff --git a/src/main/java/build/buf/protovalidate/ValidateMessage.java b/src/main/java/build/buf/protovalidate/ValidateMessage.java index d9ffe18b3..12a3ad323 100644 --- a/src/main/java/build/buf/protovalidate/ValidateMessage.java +++ b/src/main/java/build/buf/protovalidate/ValidateMessage.java @@ -16,19 +16,16 @@ import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FieldDescriptor; -import com.google.protobuf.Descriptors.OneofDescriptor; +import com.google.protobuf.UnknownFieldSet; import org.jspecify.annotations.Nullable; /** - * {@link ValidateMessage} is a wrapper around a protobuf message that provides reflective access to - * the underlying message. - * - *

{@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. + * {@link ValidateMessage} gives protovalidate-java read access to a message from another protobuf + * runtime, so that {@link Validator#validate(ValidateMessage)} can validate it. */ public interface ValidateMessage { /** - * The {@link Descriptor} of the wrapped message's type. + * The {@link Descriptor} of the message's type. * * @return The descriptor. */ @@ -45,38 +42,8 @@ public interface ValidateMessage { 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. + * Returns the plain Java value of a populated field. The validator only calls this for fields + * where {@link #hasField} returns true. * *

Singular values use these types. Unsigned integers use the signed type with the same bits. * @@ -84,16 +51,27 @@ default boolean isEmpty() { *

  • int32, sint32, sfixed32, uint32, fixed32: {@link Integer} *
  • int64, sint64, sfixed64, uint64, fixed64: {@link Long} *
  • float: {@link Float}; double: {@link Double}; bool: {@link Boolean} - *
  • string: {@link String}; bytes: {@link com.google.protobuf.ByteString} + *
  • string: {@link String}; bytes: {@link com.google.protobuf.ByteString} or {@code byte[]} *
  • enum: the number as an {@link Integer} *
  • message: a {@link ValidateMessage} * * *

    Repeated fields are a {@link java.util.List} of those values, and map fields a {@link - * java.util.Map}. + * java.util.Map}. If a value has a different type, validation throws {@link + * IllegalArgumentException} naming 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. + * @return The field's value. */ @Nullable Object getField(FieldDescriptor field); + + /** + * The message's unknown fields. They only affect validation by making an otherwise empty message + * non-empty, which matters for rules that ignore empty messages. + * + * @return The unknown fields; empty by default. + */ + default UnknownFieldSet getUnknownFields() { + return UnknownFieldSet.getDefaultInstance(); + } } diff --git a/src/main/java/build/buf/protovalidate/ValidateMessageConverter.java b/src/main/java/build/buf/protovalidate/ValidateMessageConverter.java new file mode 100644 index 000000000..eed33bc0d --- /dev/null +++ b/src/main/java/build/buf/protovalidate/ValidateMessageConverter.java @@ -0,0 +1,93 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.EnumValueDescriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.DynamicMessage; +import com.google.protobuf.Message; +import java.util.List; +import java.util.Map; +import org.jspecify.annotations.Nullable; + +/** Converts a {@link ValidateMessage} to a protobuf-java {@link DynamicMessage}. */ +final class ValidateMessageConverter { + private ValidateMessageConverter() {} + + static Message toMessage(ValidateMessage message) { + Descriptor descriptor = message.getDescriptorForType(); + DynamicMessage.Builder builder = DynamicMessage.newBuilder(descriptor); + for (FieldDescriptor field : descriptor.getFields()) { + if (!message.hasField(field)) { + continue; + } + Object value = message.getField(field); + if (value == null) { + continue; + } + try { + setField(builder, field, value); + } catch (IllegalArgumentException | ClassCastException e) { + throw new IllegalArgumentException( + "field \"" + field.getFullName() + "\" has an invalid value: " + e.getMessage(), e); + } + } + return builder.setUnknownFields(message.getUnknownFields()).build(); + } + + private static void setField( + DynamicMessage.Builder builder, FieldDescriptor field, Object value) { + if (field.isMapField()) { + Descriptor entryType = field.getMessageType(); + FieldDescriptor keyField = entryType.findFieldByNumber(1); + FieldDescriptor valueField = entryType.findFieldByNumber(2); + for (Map.Entry entry : ((Map) value).entrySet()) { + builder.addRepeatedField( + field, + DynamicMessage.newBuilder(entryType) + .setField(keyField, toProto(keyField, entry.getKey())) + .setField(valueField, toProto(valueField, entry.getValue())) + .build()); + } + } else if (field.isRepeated()) { + for (Object element : (List) value) { + builder.addRepeatedField(field, toProto(field, element)); + } + } else { + builder.setField(field, toProto(field, value)); + } + } + + private static Object toProto(FieldDescriptor field, @Nullable Object value) { + if (value == null) { + throw new IllegalArgumentException("list elements and map keys and values must not be null"); + } + switch (field.getJavaType()) { + case BYTE_STRING: + // DynamicMessage stores a byte[] as is, but native rules read bytes as ByteString. + return value instanceof byte[] ? ByteString.copyFrom((byte[]) value) : value; + case ENUM: + return value instanceof EnumValueDescriptor + ? value + : field.getEnumType().findValueByNumberCreatingIfUnknown((Integer) value); + case MESSAGE: + return toMessage((ValidateMessage) value); + default: + return value; + } + } +} diff --git a/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java b/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java deleted file mode 100644 index f09567917..000000000 --- a/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2023-2026 Buf Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package build.buf.protovalidate; - -import com.google.protobuf.Descriptors.Descriptor; -import com.google.protobuf.Descriptors.FieldDescriptor; -import dev.cel.common.types.CelType; -import dev.cel.common.types.StructTypeReference; -import dev.cel.common.values.NullValue; -import dev.cel.common.values.StructValue; -import java.util.Optional; - -/** - * Presents a {@link ValidateMessage} to CEL as a struct. CEL reads fields with {@link #select}, - * which returns the default for unset fields, and evaluates {@code has()} with {@link #find}. - */ -// Messages are only read during validation, so the struct is effectively immutable. -@SuppressWarnings("Immutable") -final class ValidateMessageStruct extends StructValue { - private final ValidateMessage message; - private final Descriptor descriptor; - - ValidateMessageStruct(ValidateMessage message) { - this.message = message; - this.descriptor = message.getDescriptorForType(); - } - - @Override - public ValidateMessage value() { - return message; - } - - @Override - public boolean isZeroValue() { - return message.isEmpty(); - } - - @Override - public CelType celType() { - return StructTypeReference.create(descriptor.getFullName()); - } - - @Override - public Object select(String fieldName) { - FieldDescriptor field = ValidateMessages.requiredField(descriptor, fieldName); - // CEL reads an unset wrapper field as null, not as the wrapped default. - if (!field.isRepeated() - && field.getJavaType() == FieldDescriptor.JavaType.MESSAGE - && ValidateMessages.isWrapper(field.getMessageType()) - && !message.hasField(field)) { - return NullValue.NULL_VALUE; - } - return ValidateMessages.field(message, field).celValue(); - } - - @Override - public Optional find(String fieldName) { - FieldDescriptor field = ValidateMessages.requiredField(descriptor, fieldName); - return message.hasField(field) ? Optional.of(select(fieldName)) : Optional.empty(); - } -} diff --git a/src/main/java/build/buf/protovalidate/ValidateMessageValue.java b/src/main/java/build/buf/protovalidate/ValidateMessageValue.java deleted file mode 100644 index 036bc507d..000000000 --- a/src/main/java/build/buf/protovalidate/ValidateMessageValue.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2023-2026 Buf Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package build.buf.protovalidate; - -import com.google.protobuf.Descriptors; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import org.jspecify.annotations.Nullable; - -/** Top-level {@link Value} backed by a user-supplied {@link ValidateMessage}. */ -final class ValidateMessageValue implements Value { - - private final ValidateMessage message; - - ValidateMessageValue(ValidateMessage message) { - this.message = message; - } - - @Override - public Descriptors.@Nullable FieldDescriptor fieldDescriptor() { - return null; - } - - @Override - public ValidateMessage messageValue() { - return message; - } - - @Override - public Object rawValue() { - return message; - } - - @Override - public Object celValue() { - return ValidateMessages.cel(message); - } - - @Override - public T jvmValue(Class clazz) { - throw new UnsupportedOperationException( - "jvmValue returns a raw scalar for native rule evaluation and is not supported on a message" - + " value; a ValidateMessage.getField() implementation returned a message value for a" - + " field evaluated as a scalar"); - } - - @Override - public List repeatedValue() { - return Collections.emptyList(); - } - - @Override - public Map mapValue() { - return Collections.emptyMap(); - } -} diff --git a/src/main/java/build/buf/protovalidate/ValidateMessages.java b/src/main/java/build/buf/protovalidate/ValidateMessages.java deleted file mode 100644 index 4e7576039..000000000 --- a/src/main/java/build/buf/protovalidate/ValidateMessages.java +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2023-2026 Buf Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package build.buf.protovalidate; - -import com.google.protobuf.Descriptors.Descriptor; -import com.google.protobuf.Descriptors.FieldDescriptor; -import java.time.Duration; -import java.time.Instant; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -/** Reads {@link ValidateMessage} fields as validator {@link Value}s and CEL values. */ -final class ValidateMessages { - private static final Set WRAPPER_TYPES = - new HashSet<>( - Arrays.asList( - "google.protobuf.DoubleValue", - "google.protobuf.FloatValue", - "google.protobuf.Int64Value", - "google.protobuf.UInt64Value", - "google.protobuf.Int32Value", - "google.protobuf.UInt32Value", - "google.protobuf.BoolValue", - "google.protobuf.StringValue", - "google.protobuf.BytesValue")); - - private ValidateMessages() {} - - static Value field(ValidateMessage message, FieldDescriptor field) { - if (message instanceof ProtobufValidateMessage) { - return ((ProtobufValidateMessage) message).fieldValue(field); - } - return new PlainValue(field, message.getField(field), false); - } - - /** Returns what CEL sees for a message, using CEL's own types for well-known types. */ - static Object cel(ValidateMessage message) { - if (message instanceof ProtobufValidateMessage) { - return ((ProtobufValidateMessage) message).getMessage(); - } - Descriptor descriptor = message.getDescriptorForType(); - String name = descriptor.getFullName(); - if (name.equals("google.protobuf.Timestamp")) { - return Instant.ofEpochSecond(longField(message, "seconds"), longField(message, "nanos")); - } - if (name.equals("google.protobuf.Duration")) { - return Duration.ofSeconds(longField(message, "seconds"), longField(message, "nanos")); - } - if (isWrapper(descriptor)) { - return field(message, requiredField(descriptor, "value")).celValue(); - } - return new ValidateMessageStruct(message); - } - - static boolean isWrapper(Descriptor descriptor) { - return WRAPPER_TYPES.contains(descriptor.getFullName()); - } - - static FieldDescriptor requiredField(Descriptor descriptor, String name) { - FieldDescriptor field = descriptor.findFieldByName(name); - if (field == null) { - throw new IllegalArgumentException( - "no field \"" + name + "\" in " + descriptor.getFullName()); - } - return field; - } - - private static long longField(ValidateMessage message, String name) { - FieldDescriptor field = requiredField(message.getDescriptorForType(), name); - return ((Number) field(message, field).rawValue()).longValue(); - } -} diff --git a/src/main/java/build/buf/protovalidate/Validator.java b/src/main/java/build/buf/protovalidate/Validator.java index f9151a11d..2b0e9f6b5 100644 --- a/src/main/java/build/buf/protovalidate/Validator.java +++ b/src/main/java/build/buf/protovalidate/Validator.java @@ -37,16 +37,16 @@ public interface Validator { ValidationResult validate(Message msg) throws ValidationException; /** - * 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. + * Validates a message from another protobuf runtime, provided as a {@link ValidateMessage}. The + * message is copied to a protobuf-java {@link com.google.protobuf.DynamicMessage} and validated + * with {@link #validate(Message)}. * * @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. + * @throws IllegalArgumentException if a field value has the wrong type. */ default ValidationResult validate(ValidateMessage message) throws ValidationException { - throw new ValidationException("ValidateMessage validation is unsupported"); + return validate(ValidateMessageConverter.toMessage(message)); } } diff --git a/src/main/java/build/buf/protovalidate/ValidatorImpl.java b/src/main/java/build/buf/protovalidate/ValidatorImpl.java index 8c0f408ae..39613c9f8 100644 --- a/src/main/java/build/buf/protovalidate/ValidatorImpl.java +++ b/src/main/java/build/buf/protovalidate/ValidatorImpl.java @@ -48,17 +48,9 @@ public ValidationResult validate(Message msg) throws ValidationException { if (msg == null) { return ValidationResult.EMPTY; } - return validate(new ProtobufValidateMessage(msg)); - } - - @Override - public ValidationResult validate(ValidateMessage message) throws ValidationException { - if (message == null) { - return ValidationResult.EMPTY; - } - Evaluator evaluator = evaluatorBuilder.load(message.getDescriptorForType()); - List result = - evaluator.evaluate(new ValidateMessageValue(message), this.failFast); + Descriptor descriptor = msg.getDescriptorForType(); + Evaluator evaluator = evaluatorBuilder.load(descriptor); + List result = evaluator.evaluate(new MessageValue(msg), this.failFast); if (result.isEmpty()) { return ValidationResult.EMPTY; } diff --git a/src/main/java/build/buf/protovalidate/Value.java b/src/main/java/build/buf/protovalidate/Value.java index 3acb4bed7..a2bb96b29 100644 --- a/src/main/java/build/buf/protovalidate/Value.java +++ b/src/main/java/build/buf/protovalidate/Value.java @@ -15,14 +15,14 @@ package build.buf.protovalidate; import com.google.protobuf.Descriptors; +import com.google.protobuf.Message; import java.util.List; import java.util.Map; import org.jspecify.annotations.Nullable; /** * {@link Value} is a wrapper around a protobuf value that provides helper methods for accessing the - * value. Implementations convert from the runtime's representation; see {@link - * ValidateMessage#getField} for the plain representation other runtimes supply. + * value. */ interface Value { /** @@ -34,17 +34,35 @@ interface Value { Descriptors.@Nullable FieldDescriptor fieldDescriptor(); /** - * Get the underlying value as a {@link ValidateMessage} type. + * Get the underlying value as a {@link Message} type. * - * @return A non-null view for a singular message or message element; null for scalar and - * collection values. + * @return The underlying {@link Message} value. null if the underlying value is not a {@link + * Message} type. */ - @Nullable ValidateMessage messageValue(); + @Nullable Message messageValue(); /** - * Returns the raw representation specified in the {@link Value} type table for native rules. + * Get the underlying value and cast it to the class type. * - * @return The non-null raw value. + * @param clazz The inferred class. + * @return The value casted to the inferred class type. + * @param The class type. + */ + T value(Class clazz); + + /** + * Returns the underlying protobuf Java value without any CEL-specific adaptation. + * + *

    {@link #value(Class)} routes scalars through {@code ProtoAdapter.toCel}, which converts + * {@code int32→Long}, {@code uint32→UnsignedLong}, {@code float→Double}, {@code bytes→ + * CelByteString}, etc. — appropriate for the CEL evaluation path but lossy for native rule + * evaluators that compare against raw protobuf field values. Native evaluators in {@code + * build.buf.protovalidate.rules} use this method to obtain values they can compare directly with + * the values they read off the typed rule message. + * + * @return The underlying value as protobuf-java provides it. Non-null for all values produced by + * the evaluator pipeline (field reads, list elements, message wrappers — all guarantee a + * value). */ Object rawValue(); @@ -60,30 +78,7 @@ interface Value { * Get the underlying value as a map. * * @return The underlying value as a map. Empty map is returned if the underlying type is not a - * map. + * list. */ Map mapValue(); - - /** - * Get the underlying value as it should be provided to CEL. - * - * @return The underlying value as a CEL-compatible type. - */ - Object celValue(); - - /** - * Returns the JVM representation specified in the {@link Value} type table, cast to {@code - * clazz}. - * - *

    Values returned by {@link ValidateMessage#getField}, {@link #repeatedValue}, or {@link - * #mapValue} must support {@code Object.class} for violation details, including message-valued - * fields and elements. Scalars must also support their compatible Java supertypes: numeric values - * accept {@code Number.class}, booleans accept {@code Boolean.class}, and strings accept {@code - * String.class}. Scalar zero-value checks use this representation. - * - * @param clazz The inferred class. - * @return The value cast to the inferred class type. - * @param The class type. - */ - T jvmValue(Class clazz); } diff --git a/src/main/java/build/buf/protovalidate/ValueEvaluator.java b/src/main/java/build/buf/protovalidate/ValueEvaluator.java index 51f50c1ef..633339bf8 100644 --- a/src/main/java/build/buf/protovalidate/ValueEvaluator.java +++ b/src/main/java/build/buf/protovalidate/ValueEvaluator.java @@ -17,7 +17,6 @@ import build.buf.protovalidate.exceptions.ExecutionException; import build.buf.validate.FieldPath; import com.google.protobuf.Descriptors; -import com.google.protobuf.Message; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -72,7 +71,7 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - if (ignoreEmpty && isZeroValue(val)) { + if (this.shouldIgnore(val.value(Object.class))) { return RuleViolation.NO_VIOLATIONS; } List allViolations = new ArrayList<>(); @@ -105,15 +104,14 @@ void setIgnoreEmpty(Object zero) { this.zero = zero; } - private boolean isZeroValue(Value val) { - if (zero instanceof Message) { - ValidateMessage message = val.messageValue(); - return message != null && message.isEmpty(); + private boolean shouldIgnore(Object value) { + if (!this.ignoreEmpty) { + return false; } - Object value = val.jvmValue(Object.class); - if (zero instanceof Long && value instanceof Number) { - return ((Number) value).longValue() == (Long) zero; + // Unsigned list items are UnsignedLong, but their zero value is a Long. + if (this.zero instanceof Long && value instanceof Number) { + return ((Number) value).longValue() == (Long) this.zero; } - return Objects.equals(value, zero); + return Objects.equals(value, this.zero); } } diff --git a/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java b/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java index b767c1318..6cba9a242 100644 --- a/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java +++ b/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java @@ -16,6 +16,7 @@ import build.buf.protovalidate.exceptions.ExecutionException; import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Message; import java.util.List; /** @@ -25,8 +26,8 @@ * *

    CEL's runtime auto-unwraps wrappers to their inner primitive type, so the CEL path doesn't * need this adapter. Native evaluators expect the underlying scalar (e.g. {@code Long} for {@code - * Int64Value.value}); without unwrapping they'd see the wrapper message and misbehave. Mirrors - * {@code wrappedValueEval} in protovalidate-go's {@code builder.go}. + * Int64Value.value}); without unwrapping they'd see the wrapper {@link Message} and misbehave. + * Mirrors {@code wrappedValueEval} in protovalidate-go's {@code builder.go}. * *

    The wrapped evaluator's {@link RuleBase} is constructed against the OUTER wrapper field's * {@code ValueEvaluator}, so violation field paths point at the user's wrapper-typed field rather @@ -57,12 +58,12 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - ValidateMessage message = val.messageValue(); + Message message = val.messageValue(); if (message == null) { // proto3 message-typed field absent — no value to validate. return RuleViolation.NO_VIOLATIONS; } - Value innerValue = ValidateMessages.field(message, innerField); - return inner.evaluate(innerValue, failFast); + Object innerValue = message.getField(innerField); + return inner.evaluate(new ObjectValue(innerField, innerValue), failFast); } } diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageConverterTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageConverterTest.java new file mode 100644 index 000000000..9aa13c78d --- /dev/null +++ b/src/test/java/build/buf/protovalidate/ValidateMessageConverterTest.java @@ -0,0 +1,172 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import build.buf.validate.BytesRules; +import build.buf.validate.FieldRules; +import build.buf.validate.ValidateProto; +import com.google.protobuf.BoolValue; +import com.google.protobuf.ByteString; +import com.google.protobuf.BytesValue; +import com.google.protobuf.DescriptorProtos.DescriptorProto; +import com.google.protobuf.DescriptorProtos.FieldDescriptorProto; +import com.google.protobuf.DescriptorProtos.FieldOptions; +import com.google.protobuf.DescriptorProtos.FileDescriptorProto; +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Descriptors.FileDescriptor; +import com.google.protobuf.DoubleValue; +import com.google.protobuf.FloatValue; +import com.google.protobuf.Int32Value; +import com.google.protobuf.Int64Value; +import com.google.protobuf.Message; +import com.google.protobuf.StringValue; +import com.google.protobuf.Struct; +import com.google.protobuf.UInt32Value; +import java.util.Collections; +import java.util.stream.Stream; +import org.jspecify.annotations.Nullable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +public class ValidateMessageConverterTest { + private static Stream wrongTypes() { + return Stream.of( + Arguments.of(field(Int32Value.getDescriptor(), "value"), 1L), + Arguments.of(field(UInt32Value.getDescriptor(), "value"), 1L), + Arguments.of(field(Int64Value.getDescriptor(), "value"), 1), + Arguments.of(field(FloatValue.getDescriptor(), "value"), 1.0d), + Arguments.of(field(DoubleValue.getDescriptor(), "value"), 1.0f), + Arguments.of(field(BoolValue.getDescriptor(), "value"), "true"), + Arguments.of(field(StringValue.getDescriptor(), "value"), 1), + Arguments.of(field(FieldDescriptorProto.getDescriptor(), "type"), "TYPE_INT32"), + Arguments.of( + field(FieldDescriptorProto.getDescriptor(), "options"), + FieldOptions.getDefaultInstance()), + Arguments.of(field(DescriptorProto.getDescriptor(), "field"), Collections.emptySet()), + // protobuf-java returns map fields as a list of entries; the plain API wants a Map. + Arguments.of(field(Struct.getDescriptor(), "fields"), Collections.emptyList()), + Arguments.of( + field(DescriptorProto.getDescriptor(), "reserved_name"), Collections.singletonList(1)), + Arguments.of( + field(DescriptorProto.getDescriptor(), "reserved_name"), + Collections.singletonList(null)), + Arguments.of( + field(Struct.getDescriptor(), "fields"), Collections.singletonMap("key", null))); + } + + @ParameterizedTest(name = "{0} = {1}") + @MethodSource("wrongTypes") + public void rejectsWrongType(FieldDescriptor field, Object value) { + assertThatThrownBy(() -> ValidateMessageConverter.toMessage(new OneField(field, value))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("field \"" + field.getFullName() + "\" has an invalid value"); + } + + @Test + public void acceptsDocumentedTypes() { + FieldDescriptor enumField = field(FieldDescriptorProto.getDescriptor(), "type"); + Object enumValue = FieldDescriptorProto.Type.TYPE_INT32.getValueDescriptor(); + Object number = FieldDescriptorProto.Type.TYPE_INT32.getNumber(); + FieldDescriptor bytesField = field(BytesValue.getDescriptor(), "value"); + + assertThat(convert(enumField, number)).isEqualTo(enumValue); + assertThat(convert(enumField, enumValue)).isEqualTo(enumValue); + assertThat(convert(bytesField, ByteString.copyFromUtf8("a"))) + .isEqualTo(ByteString.copyFromUtf8("a")); + assertThat(convert(bytesField, new byte[] {'a'})).isEqualTo(ByteString.copyFromUtf8("a")); + } + + // Native rules read bytes as ByteString, so a byte[] once failed only with native rules on. + @ParameterizedTest(name = "nativeRules={0}") + @ValueSource(booleans = {true, false}) + public void validatesByteArrayBytes(boolean nativeRules) throws Exception { + FieldDescriptorProto data = + FieldDescriptorProto.newBuilder() + .setName("data") + .setNumber(1) + .setType(FieldDescriptorProto.Type.TYPE_BYTES) + .setOptions( + FieldOptions.newBuilder() + .setExtension( + ValidateProto.field, + FieldRules.newBuilder() + .setBytes(BytesRules.newBuilder().setMinLen(3)) + .build())) + .build(); + Descriptor descriptor = + FileDescriptor.buildFrom( + FileDescriptorProto.newBuilder() + .setName("blob.proto") + .setSyntax("proto3") + .addDependency(ValidateProto.getDescriptor().getName()) + .addMessageType(DescriptorProto.newBuilder().setName("Blob").addField(data)) + .build(), + new FileDescriptor[] {ValidateProto.getDescriptor()}) + .findMessageTypeByName("Blob"); + Validator validator = + ValidatorFactory.newBuilder() + .withConfig(Config.newBuilder().setEnableNativeRules(nativeRules).build()) + .build(); + + ValidationResult result = + validator.validate(new OneField(descriptor.findFieldByName("data"), new byte[] {1})); + + assertThat(result.getViolations()) + .extracting(violation -> violation.toProto().getRuleId()) + .containsExactly("bytes.min_len"); + } + + private static Object convert(FieldDescriptor field, Object value) { + Message message = ValidateMessageConverter.toMessage(new OneField(field, value)); + return message.getField(field); + } + + private static FieldDescriptor field(Descriptor descriptor, String name) { + return descriptor.findFieldByName(name); + } + + /** A {@link ValidateMessage} with one populated field. */ + private static final class OneField implements ValidateMessage { + private final FieldDescriptor field; + private final Object value; + + OneField(FieldDescriptor field, Object value) { + this.field = field; + this.value = value; + } + + @Override + public Descriptor getDescriptorForType() { + return field.getContainingType(); + } + + @Override + public boolean hasField(FieldDescriptor other) { + return other.equals(field); + } + + @Override + public @Nullable Object getField(FieldDescriptor other) { + return other.equals(field) ? value : null; + } + } +} diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java index 6621ced82..b088965f4 100644 --- a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java +++ b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java @@ -47,6 +47,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; /** * Exercises {@link Validator#validate(ValidateMessage)} with an alternative-runtime {@link @@ -304,26 +305,26 @@ public void messageFieldRequiresValidateMessage() throws Exception { .hasMessageContaining("ValidateMessage"); } - @Test - public void messageValueJvmValueUnsupported() throws Exception { - // A message has no raw scalar form, so jvmValue is unsupported on a message-backed Value. + @ParameterizedTest(name = "nativeRules={0}") + @ValueSource(booleans = {true, false}) + public void scalarFieldRequiresDocumentedType(boolean nativeRules) throws Exception { Descriptors.Descriptor descriptor = buildPersonDescriptor(); Descriptors.Descriptor addressDescriptor = descriptor.findFieldByName("address").getMessageType(); - Value messageValue = new ValidateMessageValue(address(addressDescriptor, "Main Street")); - assertThatThrownBy(() -> messageValue.jvmValue(Object.class)) - .isInstanceOf(UnsupportedOperationException.class) - .hasMessageContaining("jvmValue returns a raw scalar for native rule evaluation") - .hasMessageContaining("not supported on a message value") - .hasMessageContaining("ValidateMessage.getField() implementation returned a message value"); - - Value protobufMessageValue = new MessageValue(Timestamp.getDefaultInstance()); - assertThatThrownBy(() -> protobufMessageValue.jvmValue(Object.class)) - .isInstanceOf(UnsupportedOperationException.class) - .hasMessageContaining("jvmValue returns a raw scalar for native rule evaluation") - .hasMessageContaining("not supported on a message value") - .hasMessageContaining("use messageValue() or celValue() instead"); + // age is an int32; a Long must fail with an error naming the field. + Map fields = + personFields(descriptor, "alice", 30, address(addressDescriptor, "Main Street")); + fields.put(descriptor.findFieldByName("age"), 30L); + ValidateMessage message = new MapValidateMessage(descriptor, fields); + + Validator validator = + ValidatorFactory.newBuilder() + .withConfig(Config.newBuilder().setEnableNativeRules(nativeRules).build()) + .build(); + assertThatThrownBy(() -> validator.validate(message)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("field \"example.Person.age\" has an invalid value"); } @Test diff --git a/src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java b/src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java index b9417c521..055f6b0dc 100644 --- a/src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java +++ b/src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java @@ -15,14 +15,12 @@ package build.buf.protovalidate.external; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import build.buf.protovalidate.Config; import build.buf.protovalidate.ValidateMessage; import build.buf.protovalidate.ValidationResult; import build.buf.protovalidate.Validator; import build.buf.protovalidate.ValidatorFactory; -import build.buf.protovalidate.exceptions.ValidationException; import build.buf.validate.BytesRules; import build.buf.validate.EnumRules; import build.buf.validate.FieldRules; @@ -71,9 +69,7 @@ void legacyValidatorRemainsImplementable() throws Exception { descriptor(field("s", FieldDescriptorProto.Type.TYPE_STRING, FieldRules.newBuilder())); ExternalMessage message = message(descriptor, "s", "abc"); assertThat(legacy.validate(toProtobuf(message))).isSameAs(ValidationResult.EMPTY); - assertThatThrownBy(() -> legacy.validate(message)) - .isInstanceOf(ValidationException.class) - .hasMessageContaining("unsupported"); + assertThat(legacy.validate(message)).isSameAs(ValidationResult.EMPTY); } @ParameterizedTest @@ -323,9 +319,6 @@ void oneofDefaultValuesArePresent(boolean nativeRules) throws Exception { .setOneofIndex(0)); ExternalMessage empty = new ExternalMessage(descriptor, Collections.emptyMap()); ExternalMessage populated = message(descriptor, "s", ""); - assertThat(empty.getOneofFieldDescriptor(descriptor.getOneofs().get(0))).isNull(); - assertThat(populated.getOneofFieldDescriptor(descriptor.getOneofs().get(0))) - .isEqualTo(descriptor.findFieldByName("s")); assertParity(nativeRules, empty, 1); assertParity(nativeRules, populated, 0); } @@ -477,8 +470,8 @@ public Descriptor getDescriptorForType() { } @Override - public boolean isEmpty() { - return unknownFields.asMap().isEmpty() && ValidateMessage.super.isEmpty(); + public UnknownFieldSet getUnknownFields() { + return unknownFields; } @Override From 25b70c3867d11a00f95e1c7921072425ef76fd30 Mon Sep 17 00:00:00 2001 From: Jon Bodner Date: Thu, 3 Dec 2026 13:28:18 -0500 Subject: [PATCH 11/23] Revert "Validate other runtimes' messages by converting them to DynamicMessage" This reverts commit 4790d27b71b594a955de996b5e65f44f18b460e7. --- README.md | 8 +- .../build/buf/protovalidate/AnyEvaluator.java | 5 +- .../build/buf/protovalidate/CelPrograms.java | 2 +- .../protovalidate/EmptyValidateMessage.java | 43 ++++ .../buf/protovalidate/EnumEvaluator.java | 4 +- .../buf/protovalidate/FieldEvaluator.java | 19 +- .../buf/protovalidate/ListElementValue.java | 20 +- .../build/buf/protovalidate/MapEvaluator.java | 8 +- .../buf/protovalidate/MapRulesEvaluator.java | 5 +- .../protovalidate/MessageOneofEvaluator.java | 5 +- .../build/buf/protovalidate/MessageValue.java | 20 +- .../build/buf/protovalidate/ObjectValue.java | 24 ++- .../buf/protovalidate/OneofEvaluator.java | 9 +- .../build/buf/protovalidate/PlainValue.java | 196 ++++++++++++++++++ .../ProtobufValidateMessage.java | 102 +++++++++ .../buf/protovalidate/RuleViolation.java | 2 +- .../buf/protovalidate/ValidateMessage.java | 62 ++++-- .../ValidateMessageConverter.java | 93 --------- .../protovalidate/ValidateMessageStruct.java | 73 +++++++ .../protovalidate/ValidateMessageValue.java | 69 ++++++ .../buf/protovalidate/ValidateMessages.java | 85 ++++++++ .../build/buf/protovalidate/Validator.java | 10 +- .../buf/protovalidate/ValidatorImpl.java | 14 +- .../java/build/buf/protovalidate/Value.java | 59 +++--- .../buf/protovalidate/ValueEvaluator.java | 18 +- .../protovalidate/WrappedValueEvaluator.java | 11 +- .../ValidateMessageConverterTest.java | 172 --------------- .../protovalidate/ValidateMessageTest.java | 33 ++- .../external/ExternalRuntimeTest.java | 13 +- 29 files changed, 772 insertions(+), 412 deletions(-) create mode 100644 src/main/java/build/buf/protovalidate/EmptyValidateMessage.java create mode 100644 src/main/java/build/buf/protovalidate/PlainValue.java create mode 100644 src/main/java/build/buf/protovalidate/ProtobufValidateMessage.java delete mode 100644 src/main/java/build/buf/protovalidate/ValidateMessageConverter.java create mode 100644 src/main/java/build/buf/protovalidate/ValidateMessageStruct.java create mode 100644 src/main/java/build/buf/protovalidate/ValidateMessageValue.java create mode 100644 src/main/java/build/buf/protovalidate/ValidateMessages.java delete mode 100644 src/test/java/build/buf/protovalidate/ValidateMessageConverterTest.java diff --git a/README.md b/README.md index d5db71dc0..00cba8bde 100644 --- a/README.md +++ b/README.md @@ -79,21 +79,21 @@ Forward compatibility is preserved by a clone-and-clear contract: when protovali ## Other Protobuf runtimes -`protovalidate-java` validates protobuf-java messages out of the box. To validate messages from another JVM Protobuf runtime, wrap each message in a `ValidateMessage` that returns plain Java values for its fields: +`protovalidate-java` validates protobuf-java messages out of the box. To validate messages from another JVM Protobuf runtime without converting them to protobuf-java first, wrap each message in a `ValidateMessage` that returns plain Java values for its fields: ```java final class MyMessage implements ValidateMessage { @Override public Descriptor getDescriptorForType() { ... } // Repeated and map fields are present when non-empty. @Override public boolean hasField(FieldDescriptor field) { ... } - // The value of a present field; nested messages are also ValidateMessages. - @Override public Object getField(FieldDescriptor field) { ... } + // The field's value, or null when unset; nested messages are also ValidateMessages. + @Override public @Nullable Object getField(FieldDescriptor field) { ... } } ValidationResult result = validator.validate(new MyMessage(message)); ``` -The Javadoc on `ValidateMessage.getField` lists the Java type to return for each Protobuf field type. `protovalidate-java` copies the fields into a protobuf-java `DynamicMessage` and validates that, so a message from another runtime is validated exactly like a protobuf-java one. For a complete implementation backed by a `Map`, see [`ExternalRuntimeTest`](src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java). +The Javadoc on `ValidateMessage.getField` lists the Java type to return for each Protobuf field type. `protovalidate-java` converts these values for CEL itself, so implementations don't depend on CEL. For a complete implementation backed by a `Map`, see [`ExternalRuntimeTest`](src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java). ## Additional languages and repositories diff --git a/src/main/java/build/buf/protovalidate/AnyEvaluator.java b/src/main/java/build/buf/protovalidate/AnyEvaluator.java index d7d18356d..8498fb082 100644 --- a/src/main/java/build/buf/protovalidate/AnyEvaluator.java +++ b/src/main/java/build/buf/protovalidate/AnyEvaluator.java @@ -19,7 +19,6 @@ import build.buf.validate.FieldPath; import build.buf.validate.FieldRules; import com.google.protobuf.Descriptors; -import com.google.protobuf.Message; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; @@ -78,12 +77,12 @@ final class AnyEvaluator implements Evaluator { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - Message anyValue = val.messageValue(); + ValidateMessage anyValue = val.messageValue(); if (anyValue == null) { return RuleViolation.NO_VIOLATIONS; } List violationList = new ArrayList<>(); - String typeURL = (String) anyValue.getField(typeURLDescriptor); + String typeURL = ValidateMessages.field(anyValue, typeURLDescriptor).jvmValue(String.class); if (!in.isEmpty() && !in.contains(typeURL)) { RuleViolation.Builder violation = RuleViolation.newBuilder() diff --git a/src/main/java/build/buf/protovalidate/CelPrograms.java b/src/main/java/build/buf/protovalidate/CelPrograms.java index ed712f796..f88e56035 100644 --- a/src/main/java/build/buf/protovalidate/CelPrograms.java +++ b/src/main/java/build/buf/protovalidate/CelPrograms.java @@ -45,7 +45,7 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - CelVariableResolver bindings = Variable.newThisVariable(val.value(Object.class)); + CelVariableResolver bindings = Variable.newThisVariable(val.celValue()); List violations = new ArrayList<>(); for (CompiledProgram program : programs) { RuleViolation.Builder violation = program.eval(val, bindings); diff --git a/src/main/java/build/buf/protovalidate/EmptyValidateMessage.java b/src/main/java/build/buf/protovalidate/EmptyValidateMessage.java new file mode 100644 index 000000000..533fac668 --- /dev/null +++ b/src/main/java/build/buf/protovalidate/EmptyValidateMessage.java @@ -0,0 +1,43 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import org.jspecify.annotations.Nullable; + +/** Stands in for an unset message field, which has no runtime object of its own. */ +final class EmptyValidateMessage implements ValidateMessage { + private final Descriptor descriptor; + + EmptyValidateMessage(Descriptor descriptor) { + this.descriptor = descriptor; + } + + @Override + public Descriptor getDescriptorForType() { + return descriptor; + } + + @Override + public boolean hasField(FieldDescriptor field) { + return false; + } + + @Override + public @Nullable Object getField(FieldDescriptor field) { + return null; + } +} diff --git a/src/main/java/build/buf/protovalidate/EnumEvaluator.java b/src/main/java/build/buf/protovalidate/EnumEvaluator.java index d2fa00df4..a77613cba 100644 --- a/src/main/java/build/buf/protovalidate/EnumEvaluator.java +++ b/src/main/java/build/buf/protovalidate/EnumEvaluator.java @@ -77,11 +77,11 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - Object enumValue = val.value(Object.class); + Number enumValue = val.jvmValue(Number.class); if (enumValue == null) { return RuleViolation.NO_VIOLATIONS; } - if (!values.contains(enumValue)) { + if (!values.contains(enumValue.longValue())) { return Collections.singletonList( RuleViolation.newBuilder() .addAllRulePathElements(helper.getRulePrefixElements()) diff --git a/src/main/java/build/buf/protovalidate/FieldEvaluator.java b/src/main/java/build/buf/protovalidate/FieldEvaluator.java index 877aec5ea..8b83baf4e 100644 --- a/src/main/java/build/buf/protovalidate/FieldEvaluator.java +++ b/src/main/java/build/buf/protovalidate/FieldEvaluator.java @@ -19,7 +19,6 @@ import build.buf.validate.FieldRules; import build.buf.validate.Ignore; import com.google.protobuf.Descriptors.FieldDescriptor; -import com.google.protobuf.Message; import java.util.Collections; import java.util.List; @@ -95,11 +94,11 @@ public List evaluate(Value val, boolean failFast) if (this.shouldIgnoreAlways()) { return RuleViolation.NO_VIOLATIONS; } - Message message = val.messageValue(); + ValidateMessage message = val.messageValue(); if (message == null) { return RuleViolation.NO_VIOLATIONS; } - boolean hasField = isFieldSet(message, descriptor); + boolean hasField = message.hasField(descriptor); if (required && !hasField) { return Collections.singletonList( RuleViolation.newBuilder() @@ -113,18 +112,6 @@ public List evaluate(Value val, boolean failFast) if (this.shouldIgnoreEmpty() && !hasField) { return RuleViolation.NO_VIOLATIONS; } - return valueEvaluator.evaluate( - new ObjectValue(descriptor, message.getField(descriptor)), failFast); - } - - /** - * Returns whether the given field is set on the message. Handles repeated and map fields, which - * are not supported by {@link Message#hasField}. - */ - static boolean isFieldSet(Message message, FieldDescriptor field) { - if (field.isRepeated()) { - return message.getRepeatedFieldCount(field) != 0; - } - return message.hasField(field); + return valueEvaluator.evaluate(ValidateMessages.field(message, descriptor), failFast); } } diff --git a/src/main/java/build/buf/protovalidate/ListElementValue.java b/src/main/java/build/buf/protovalidate/ListElementValue.java index 8e397d328..7987aca7e 100644 --- a/src/main/java/build/buf/protovalidate/ListElementValue.java +++ b/src/main/java/build/buf/protovalidate/ListElementValue.java @@ -29,6 +29,8 @@ final class ListElementValue implements Value { /** Object type since the object type is inferred from the field descriptor. */ private final Object value; + private final @Nullable ProtobufValidateMessage message; + /** * {@link com.google.protobuf.Descriptors.FieldDescriptor} is the field descriptor for the value. */ @@ -37,6 +39,10 @@ final class ListElementValue implements Value { ListElementValue(Descriptors.FieldDescriptor fieldDescriptor, Object value) { this.value = value; this.fieldDescriptor = fieldDescriptor; + this.message = + fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE + ? new ProtobufValidateMessage((Message) value) + : null; } @Override @@ -45,15 +51,17 @@ final class ListElementValue implements Value { } @Override - public @Nullable Message messageValue() { - if (fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { - return (Message) value; - } - return null; + public @Nullable ValidateMessage messageValue() { + return message; + } + + @Override + public Object celValue() { + return ProtoAdapter.scalarToCel(fieldDescriptor.getType(), value); } @Override - public T value(Class clazz) { + public T jvmValue(Class clazz) { Descriptors.FieldDescriptor.Type type = fieldDescriptor.getType(); if (type == Descriptors.FieldDescriptor.Type.MESSAGE) { return clazz.cast(value); diff --git a/src/main/java/build/buf/protovalidate/MapEvaluator.java b/src/main/java/build/buf/protovalidate/MapEvaluator.java index bc418e977..0dfcecbfb 100644 --- a/src/main/java/build/buf/protovalidate/MapEvaluator.java +++ b/src/main/java/build/buf/protovalidate/MapEvaluator.java @@ -155,19 +155,19 @@ private List evalPairs(Value key, Value value, boolean fa case TYPE_SINT64: case TYPE_SFIXED32: case TYPE_SFIXED64: - fieldPathElementBuilder.setIntKey(key.value(Number.class).longValue()); + fieldPathElementBuilder.setIntKey(key.jvmValue(Number.class).longValue()); break; case TYPE_UINT32: case TYPE_UINT64: case TYPE_FIXED32: case TYPE_FIXED64: - fieldPathElementBuilder.setUintKey(key.value(Number.class).longValue()); + fieldPathElementBuilder.setUintKey(key.jvmValue(Number.class).longValue()); break; case TYPE_BOOL: - fieldPathElementBuilder.setBoolKey(key.value(Boolean.class)); + fieldPathElementBuilder.setBoolKey(key.jvmValue(Boolean.class)); break; case TYPE_STRING: - fieldPathElementBuilder.setStringKey(key.value(String.class)); + fieldPathElementBuilder.setStringKey(key.jvmValue(String.class)); break; default: throw new ExecutionException("Unexpected map key type"); diff --git a/src/main/java/build/buf/protovalidate/MapRulesEvaluator.java b/src/main/java/build/buf/protovalidate/MapRulesEvaluator.java index 39455b9e8..fea8bccda 100644 --- a/src/main/java/build/buf/protovalidate/MapRulesEvaluator.java +++ b/src/main/java/build/buf/protovalidate/MapRulesEvaluator.java @@ -18,6 +18,7 @@ import build.buf.validate.MapRules; import com.google.protobuf.Descriptors.FieldDescriptor; import java.util.List; +import java.util.Map; import org.jspecify.annotations.Nullable; /** @@ -98,8 +99,8 @@ public boolean tautology() { public List evaluate(Value val, boolean failFast) { // Java protobuf returns map fields as a List of synthetic key/value entry messages; the size // is the pair count. - List entries = (List) val.rawValue(); - long size = entries.size(); + Object entries = val.rawValue(); + long size = entries instanceof Map ? ((Map) entries).size() : ((List) entries).size(); List violations = null; if (minPairs != null && size < minPairs) { diff --git a/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java b/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java index aecce4e92..c7e9331a9 100644 --- a/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java +++ b/src/main/java/build/buf/protovalidate/MessageOneofEvaluator.java @@ -16,7 +16,6 @@ import build.buf.protovalidate.exceptions.ExecutionException; import com.google.protobuf.Descriptors.FieldDescriptor; -import com.google.protobuf.Message; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @@ -45,13 +44,13 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - Message msg = val.messageValue(); + ValidateMessage msg = val.messageValue(); if (msg == null) { return RuleViolation.NO_VIOLATIONS; } int hasCount = 0; for (FieldDescriptor field : fields) { - if (FieldEvaluator.isFieldSet(msg, field)) { + if (msg.hasField(field)) { hasCount++; } } diff --git a/src/main/java/build/buf/protovalidate/MessageValue.java b/src/main/java/build/buf/protovalidate/MessageValue.java index fa96e3b8c..08012a36a 100644 --- a/src/main/java/build/buf/protovalidate/MessageValue.java +++ b/src/main/java/build/buf/protovalidate/MessageValue.java @@ -24,8 +24,7 @@ /** The {@link Value} type that contains a {@link com.google.protobuf.Message}. */ final class MessageValue implements Value { - /** Object type since the object type is inferred from the field descriptor. */ - private final Object value; + private final ProtobufValidateMessage value; /** * Constructs a {@link MessageValue} with the provided message value. @@ -33,7 +32,7 @@ final class MessageValue implements Value { * @param value The message value. */ MessageValue(Message value) { - this.value = value; + this.value = new ProtobufValidateMessage(value); } @Override @@ -42,13 +41,20 @@ final class MessageValue implements Value { } @Override - public Message messageValue() { - return (Message) value; + public ValidateMessage messageValue() { + return value; + } + + @Override + public Object celValue() { + return value.getMessage(); } @Override - public T value(Class clazz) { - return clazz.cast(value); + public T jvmValue(Class clazz) { + throw new UnsupportedOperationException( + "jvmValue returns a raw scalar for native rule evaluation and is not supported on a message" + + " value; use messageValue() or celValue() instead"); } @Override diff --git a/src/main/java/build/buf/protovalidate/ObjectValue.java b/src/main/java/build/buf/protovalidate/ObjectValue.java index 9a53574ac..5042f230c 100644 --- a/src/main/java/build/buf/protovalidate/ObjectValue.java +++ b/src/main/java/build/buf/protovalidate/ObjectValue.java @@ -35,6 +35,8 @@ final class ObjectValue implements Value { /** Object type since the object type is inferred from the field descriptor. */ private final Object value; + private final @Nullable ProtobufValidateMessage message; + /** * Constructs a new {@link ObjectValue}. * @@ -44,6 +46,11 @@ final class ObjectValue implements Value { ObjectValue(Descriptors.FieldDescriptor fieldDescriptor, Object value) { this.fieldDescriptor = fieldDescriptor; this.value = value; + this.message = + !fieldDescriptor.isRepeated() + && fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE + ? new ProtobufValidateMessage((Message) value) + : null; } @Override @@ -53,15 +60,20 @@ public Descriptors.FieldDescriptor fieldDescriptor() { @Nullable @Override - public Message messageValue() { - if (fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { - return (Message) value; - } - return null; + public ValidateMessage messageValue() { + return message; + } + + @Override + public Object celValue() { + return ProtoAdapter.toCel(fieldDescriptor, value); } @Override - public T value(Class clazz) { + public T jvmValue(Class clazz) { + if (value instanceof Descriptors.EnumValueDescriptor) { + return clazz.cast((long) ((Descriptors.EnumValueDescriptor) value).getNumber()); + } return clazz.cast(ProtoAdapter.toCel(fieldDescriptor, value)); } diff --git a/src/main/java/build/buf/protovalidate/OneofEvaluator.java b/src/main/java/build/buf/protovalidate/OneofEvaluator.java index 5ddccd6d6..8a16323ab 100644 --- a/src/main/java/build/buf/protovalidate/OneofEvaluator.java +++ b/src/main/java/build/buf/protovalidate/OneofEvaluator.java @@ -17,7 +17,6 @@ import build.buf.protovalidate.exceptions.ExecutionException; import build.buf.validate.FieldPathElement; import com.google.protobuf.Descriptors.OneofDescriptor; -import com.google.protobuf.Message; import java.util.Collections; import java.util.List; @@ -48,8 +47,12 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - Message message = val.messageValue(); - if (message == null || !required || (message.getOneofFieldDescriptor(descriptor) != null)) { + ValidateMessage message = val.messageValue(); + if (message == null) { + return RuleViolation.NO_VIOLATIONS; + } + boolean hasField = message.getOneofFieldDescriptor(descriptor) != null; + if (!required || hasField) { return RuleViolation.NO_VIOLATIONS; } return Collections.singletonList( diff --git a/src/main/java/build/buf/protovalidate/PlainValue.java b/src/main/java/build/buf/protovalidate/PlainValue.java new file mode 100644 index 000000000..7ad58f70b --- /dev/null +++ b/src/main/java/build/buf/protovalidate/PlainValue.java @@ -0,0 +1,196 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Descriptors.EnumValueDescriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Descriptors.FieldDescriptor.JavaType; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.jspecify.annotations.Nullable; + +/** + * {@link Value} over a plain field value from {@link ValidateMessage#getField}. A null value means + * the field is unset and reads as its protobuf default. + */ +final class PlainValue implements Value { + private final FieldDescriptor field; + private final @Nullable Object value; + // An element of a repeated field shares the field's descriptor but is a single value. + private final boolean element; + + PlainValue(FieldDescriptor field, @Nullable Object value, boolean element) { + this.field = field; + this.value = value; + this.element = element; + } + + @Override + public FieldDescriptor fieldDescriptor() { + return field; + } + + @Override + public @Nullable ValidateMessage messageValue() { + return isMessage() ? message() : null; + } + + @Override + public Object rawValue() { + if (isList()) { + return list(); + } + if (isMap()) { + return map(); + } + if (isMessage()) { + return message(); + } + return scalar(); + } + + @Override + public List repeatedValue() { + if (!isList()) { + return Collections.emptyList(); + } + List out = new ArrayList<>(); + for (Object item : list()) { + out.add(new PlainValue(field, item, true)); + } + return Collections.unmodifiableList(out); + } + + @Override + public Map mapValue() { + if (!isMap()) { + return Collections.emptyMap(); + } + FieldDescriptor keyField = field.getMessageType().findFieldByNumber(1); + FieldDescriptor valueField = field.getMessageType().findFieldByNumber(2); + Map out = new HashMap<>(); + for (Map.Entry entry : map().entrySet()) { + out.put( + new PlainValue(keyField, entry.getKey(), false), + new PlainValue(valueField, entry.getValue(), false)); + } + return Collections.unmodifiableMap(out); + } + + @Override + public Object celValue() { + if (isList()) { + List out = new ArrayList<>(); + for (Value item : repeatedValue()) { + out.add(item.celValue()); + } + return out; + } + if (isMap()) { + Map out = new HashMap<>(); + for (Map.Entry entry : mapValue().entrySet()) { + out.put(entry.getKey().celValue(), entry.getValue().celValue()); + } + return out; + } + if (isMessage()) { + return ValidateMessages.cel(message()); + } + return scalarCel(); + } + + @Override + public T jvmValue(Class clazz) { + if (isList()) { + List out = new ArrayList<>(); + for (Value item : repeatedValue()) { + out.add(item.jvmValue(Object.class)); + } + return clazz.cast(out); + } + if (isMap()) { + Map out = new HashMap<>(); + for (Map.Entry entry : mapValue().entrySet()) { + out.put(entry.getKey().jvmValue(Object.class), entry.getValue().jvmValue(Object.class)); + } + return clazz.cast(out); + } + if (isMessage()) { + return clazz.cast(message()); + } + return clazz.cast(scalarCel()); + } + + private boolean isList() { + return field.isRepeated() && !field.isMapField() && !element; + } + + private boolean isMap() { + return field.isMapField() && !element; + } + + private boolean isMessage() { + return !isList() && !isMap() && field.getJavaType() == JavaType.MESSAGE; + } + + private List list() { + return value == null ? Collections.emptyList() : (List) value; + } + + private Map map() { + return value == null ? Collections.emptyMap() : (Map) value; + } + + private ValidateMessage message() { + if (value == null) { + return new EmptyValidateMessage(field.getMessageType()); + } + if (!(value instanceof ValidateMessage)) { + throw new IllegalArgumentException( + "message field \"" + + field.getName() + + "\" must be provided as a ValidateMessage, but got " + + value.getClass().getName()); + } + return (ValidateMessage) value; + } + + private Object scalar() { + if (field.getJavaType() == JavaType.ENUM) { + if (value == null) { + return field.getEnumType().getValues().get(0).getNumber(); + } + return value instanceof EnumValueDescriptor + ? ((EnumValueDescriptor) value).getNumber() + : ((Number) value).intValue(); + } + if (value != null) { + return value; + } + return field.getJavaType() == JavaType.BYTE_STRING ? ByteString.EMPTY : field.getDefaultValue(); + } + + private Object scalarCel() { + Object raw = scalar(); + if (field.getJavaType() == JavaType.ENUM) { + return ((Integer) raw).longValue(); + } + return ProtoAdapter.scalarToCel(field.getType(), raw); + } +} diff --git a/src/main/java/build/buf/protovalidate/ProtobufValidateMessage.java b/src/main/java/build/buf/protovalidate/ProtobufValidateMessage.java new file mode 100644 index 000000000..1a15b63c5 --- /dev/null +++ b/src/main/java/build/buf/protovalidate/ProtobufValidateMessage.java @@ -0,0 +1,102 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.EnumValueDescriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Descriptors.OneofDescriptor; +import com.google.protobuf.Message; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.jspecify.annotations.Nullable; + +/** {@link ValidateMessage} over a protobuf-java {@link Message}. */ +final class ProtobufValidateMessage implements ValidateMessage { + private final Message message; + + ProtobufValidateMessage(Message message) { + this.message = message; + } + + Message getMessage() { + return message; + } + + /** The validator reads protobuf-java fields through this, skipping the plain conversion. */ + Value fieldValue(FieldDescriptor field) { + return new ObjectValue(field, message.getField(field)); + } + + @Override + public Descriptor getDescriptorForType() { + return message.getDescriptorForType(); + } + + @Override + public boolean hasField(FieldDescriptor field) { + return field.isRepeated() ? message.getRepeatedFieldCount(field) > 0 : message.hasField(field); + } + + @Override + public @Nullable FieldDescriptor getOneofFieldDescriptor(OneofDescriptor oneof) { + return message.getOneofFieldDescriptor(oneof); + } + + @Override + public boolean isEmpty() { + return message.equals(message.getDefaultInstanceForType()); + } + + @Override + public @Nullable Object getField(FieldDescriptor field) { + if (!field.isRepeated() && field.hasPresence() && !message.hasField(field)) { + return null; + } + Object value = message.getField(field); + if (field.isMapField()) { + FieldDescriptor keyField = field.getMessageType().findFieldByNumber(1); + FieldDescriptor valueField = field.getMessageType().findFieldByNumber(2); + Map out = new LinkedHashMap<>(); + for (Object entry : (List) value) { + Message entryMessage = (Message) entry; + out.put( + plain(keyField, entryMessage.getField(keyField)), + plain(valueField, entryMessage.getField(valueField))); + } + return out; + } + if (field.isRepeated()) { + List out = new ArrayList<>(); + for (Object element : (List) value) { + out.add(plain(field, element)); + } + return out; + } + return plain(field, value); + } + + private static Object plain(FieldDescriptor field, Object value) { + if (value instanceof EnumValueDescriptor) { + return ((EnumValueDescriptor) value).getNumber(); + } + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) { + return new ProtobufValidateMessage((Message) value); + } + return value; + } +} diff --git a/src/main/java/build/buf/protovalidate/RuleViolation.java b/src/main/java/build/buf/protovalidate/RuleViolation.java index 454d2f782..39d18930d 100644 --- a/src/main/java/build/buf/protovalidate/RuleViolation.java +++ b/src/main/java/build/buf/protovalidate/RuleViolation.java @@ -55,7 +55,7 @@ static class FieldValue implements Violation.FieldValue { * @param value A {@link Value} to create this {@link FieldValue} from. */ FieldValue(Value value) { - this.value = value.value(Object.class); + this.value = value.jvmValue(Object.class); this.descriptor = Objects.requireNonNull(value.fieldDescriptor()); } diff --git a/src/main/java/build/buf/protovalidate/ValidateMessage.java b/src/main/java/build/buf/protovalidate/ValidateMessage.java index 12a3ad323..d9ffe18b3 100644 --- a/src/main/java/build/buf/protovalidate/ValidateMessage.java +++ b/src/main/java/build/buf/protovalidate/ValidateMessage.java @@ -16,16 +16,19 @@ import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FieldDescriptor; -import com.google.protobuf.UnknownFieldSet; +import com.google.protobuf.Descriptors.OneofDescriptor; import org.jspecify.annotations.Nullable; /** - * {@link ValidateMessage} gives protovalidate-java read access to a message from another protobuf - * runtime, so that {@link Validator#validate(ValidateMessage)} can validate it. + * {@link ValidateMessage} is a wrapper around a protobuf message that provides reflective access to + * the underlying message. + * + *

    {@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 message's type. + * The {@link Descriptor} of the wrapped message's type. * * @return The descriptor. */ @@ -42,8 +45,38 @@ public interface ValidateMessage { boolean hasField(FieldDescriptor field); /** - * Returns the plain Java value of a populated field. The validator only calls this for fields - * where {@link #hasField} returns true. + * 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. * *

    Singular values use these types. Unsigned integers use the signed type with the same bits. * @@ -51,27 +84,16 @@ public interface ValidateMessage { *

  • int32, sint32, sfixed32, uint32, fixed32: {@link Integer} *
  • int64, sint64, sfixed64, uint64, fixed64: {@link Long} *
  • float: {@link Float}; double: {@link Double}; bool: {@link Boolean} - *
  • string: {@link String}; bytes: {@link com.google.protobuf.ByteString} or {@code byte[]} + *
  • string: {@link String}; bytes: {@link com.google.protobuf.ByteString} *
  • enum: the number as an {@link Integer} *
  • message: a {@link ValidateMessage} * * *

    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 throws {@link - * IllegalArgumentException} naming the field. + * java.util.Map}. * * @param field The field descriptor for which to retrieve a value. - * @return The field's value. + * @return The field's value, or null when the field is unset. */ @Nullable Object getField(FieldDescriptor field); - - /** - * The message's unknown fields. They only affect validation by making an otherwise empty message - * non-empty, which matters for rules that ignore empty messages. - * - * @return The unknown fields; empty by default. - */ - default UnknownFieldSet getUnknownFields() { - return UnknownFieldSet.getDefaultInstance(); - } } diff --git a/src/main/java/build/buf/protovalidate/ValidateMessageConverter.java b/src/main/java/build/buf/protovalidate/ValidateMessageConverter.java deleted file mode 100644 index eed33bc0d..000000000 --- a/src/main/java/build/buf/protovalidate/ValidateMessageConverter.java +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2023-2026 Buf Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package build.buf.protovalidate; - -import com.google.protobuf.ByteString; -import com.google.protobuf.Descriptors.Descriptor; -import com.google.protobuf.Descriptors.EnumValueDescriptor; -import com.google.protobuf.Descriptors.FieldDescriptor; -import com.google.protobuf.DynamicMessage; -import com.google.protobuf.Message; -import java.util.List; -import java.util.Map; -import org.jspecify.annotations.Nullable; - -/** Converts a {@link ValidateMessage} to a protobuf-java {@link DynamicMessage}. */ -final class ValidateMessageConverter { - private ValidateMessageConverter() {} - - static Message toMessage(ValidateMessage message) { - Descriptor descriptor = message.getDescriptorForType(); - DynamicMessage.Builder builder = DynamicMessage.newBuilder(descriptor); - for (FieldDescriptor field : descriptor.getFields()) { - if (!message.hasField(field)) { - continue; - } - Object value = message.getField(field); - if (value == null) { - continue; - } - try { - setField(builder, field, value); - } catch (IllegalArgumentException | ClassCastException e) { - throw new IllegalArgumentException( - "field \"" + field.getFullName() + "\" has an invalid value: " + e.getMessage(), e); - } - } - return builder.setUnknownFields(message.getUnknownFields()).build(); - } - - private static void setField( - DynamicMessage.Builder builder, FieldDescriptor field, Object value) { - if (field.isMapField()) { - Descriptor entryType = field.getMessageType(); - FieldDescriptor keyField = entryType.findFieldByNumber(1); - FieldDescriptor valueField = entryType.findFieldByNumber(2); - for (Map.Entry entry : ((Map) value).entrySet()) { - builder.addRepeatedField( - field, - DynamicMessage.newBuilder(entryType) - .setField(keyField, toProto(keyField, entry.getKey())) - .setField(valueField, toProto(valueField, entry.getValue())) - .build()); - } - } else if (field.isRepeated()) { - for (Object element : (List) value) { - builder.addRepeatedField(field, toProto(field, element)); - } - } else { - builder.setField(field, toProto(field, value)); - } - } - - private static Object toProto(FieldDescriptor field, @Nullable Object value) { - if (value == null) { - throw new IllegalArgumentException("list elements and map keys and values must not be null"); - } - switch (field.getJavaType()) { - case BYTE_STRING: - // DynamicMessage stores a byte[] as is, but native rules read bytes as ByteString. - return value instanceof byte[] ? ByteString.copyFrom((byte[]) value) : value; - case ENUM: - return value instanceof EnumValueDescriptor - ? value - : field.getEnumType().findValueByNumberCreatingIfUnknown((Integer) value); - case MESSAGE: - return toMessage((ValidateMessage) value); - default: - return value; - } - } -} diff --git a/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java b/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java new file mode 100644 index 000000000..f09567917 --- /dev/null +++ b/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java @@ -0,0 +1,73 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import dev.cel.common.types.CelType; +import dev.cel.common.types.StructTypeReference; +import dev.cel.common.values.NullValue; +import dev.cel.common.values.StructValue; +import java.util.Optional; + +/** + * Presents a {@link ValidateMessage} to CEL as a struct. CEL reads fields with {@link #select}, + * which returns the default for unset fields, and evaluates {@code has()} with {@link #find}. + */ +// Messages are only read during validation, so the struct is effectively immutable. +@SuppressWarnings("Immutable") +final class ValidateMessageStruct extends StructValue { + private final ValidateMessage message; + private final Descriptor descriptor; + + ValidateMessageStruct(ValidateMessage message) { + this.message = message; + this.descriptor = message.getDescriptorForType(); + } + + @Override + public ValidateMessage value() { + return message; + } + + @Override + public boolean isZeroValue() { + return message.isEmpty(); + } + + @Override + public CelType celType() { + return StructTypeReference.create(descriptor.getFullName()); + } + + @Override + public Object select(String fieldName) { + FieldDescriptor field = ValidateMessages.requiredField(descriptor, fieldName); + // CEL reads an unset wrapper field as null, not as the wrapped default. + if (!field.isRepeated() + && field.getJavaType() == FieldDescriptor.JavaType.MESSAGE + && ValidateMessages.isWrapper(field.getMessageType()) + && !message.hasField(field)) { + return NullValue.NULL_VALUE; + } + return ValidateMessages.field(message, field).celValue(); + } + + @Override + public Optional find(String fieldName) { + FieldDescriptor field = ValidateMessages.requiredField(descriptor, fieldName); + return message.hasField(field) ? Optional.of(select(fieldName)) : Optional.empty(); + } +} diff --git a/src/main/java/build/buf/protovalidate/ValidateMessageValue.java b/src/main/java/build/buf/protovalidate/ValidateMessageValue.java new file mode 100644 index 000000000..036bc507d --- /dev/null +++ b/src/main/java/build/buf/protovalidate/ValidateMessageValue.java @@ -0,0 +1,69 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import com.google.protobuf.Descriptors; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import org.jspecify.annotations.Nullable; + +/** Top-level {@link Value} backed by a user-supplied {@link ValidateMessage}. */ +final class ValidateMessageValue implements Value { + + private final ValidateMessage message; + + ValidateMessageValue(ValidateMessage message) { + this.message = message; + } + + @Override + public Descriptors.@Nullable FieldDescriptor fieldDescriptor() { + return null; + } + + @Override + public ValidateMessage messageValue() { + return message; + } + + @Override + public Object rawValue() { + return message; + } + + @Override + public Object celValue() { + return ValidateMessages.cel(message); + } + + @Override + public T jvmValue(Class clazz) { + throw new UnsupportedOperationException( + "jvmValue returns a raw scalar for native rule evaluation and is not supported on a message" + + " value; a ValidateMessage.getField() implementation returned a message value for a" + + " field evaluated as a scalar"); + } + + @Override + public List repeatedValue() { + return Collections.emptyList(); + } + + @Override + public Map mapValue() { + return Collections.emptyMap(); + } +} diff --git a/src/main/java/build/buf/protovalidate/ValidateMessages.java b/src/main/java/build/buf/protovalidate/ValidateMessages.java new file mode 100644 index 000000000..4e7576039 --- /dev/null +++ b/src/main/java/build/buf/protovalidate/ValidateMessages.java @@ -0,0 +1,85 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import java.time.Duration; +import java.time.Instant; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +/** Reads {@link ValidateMessage} fields as validator {@link Value}s and CEL values. */ +final class ValidateMessages { + private static final Set WRAPPER_TYPES = + new HashSet<>( + Arrays.asList( + "google.protobuf.DoubleValue", + "google.protobuf.FloatValue", + "google.protobuf.Int64Value", + "google.protobuf.UInt64Value", + "google.protobuf.Int32Value", + "google.protobuf.UInt32Value", + "google.protobuf.BoolValue", + "google.protobuf.StringValue", + "google.protobuf.BytesValue")); + + private ValidateMessages() {} + + static Value field(ValidateMessage message, FieldDescriptor field) { + if (message instanceof ProtobufValidateMessage) { + return ((ProtobufValidateMessage) message).fieldValue(field); + } + return new PlainValue(field, message.getField(field), false); + } + + /** Returns what CEL sees for a message, using CEL's own types for well-known types. */ + static Object cel(ValidateMessage message) { + if (message instanceof ProtobufValidateMessage) { + return ((ProtobufValidateMessage) message).getMessage(); + } + Descriptor descriptor = message.getDescriptorForType(); + String name = descriptor.getFullName(); + if (name.equals("google.protobuf.Timestamp")) { + return Instant.ofEpochSecond(longField(message, "seconds"), longField(message, "nanos")); + } + if (name.equals("google.protobuf.Duration")) { + return Duration.ofSeconds(longField(message, "seconds"), longField(message, "nanos")); + } + if (isWrapper(descriptor)) { + return field(message, requiredField(descriptor, "value")).celValue(); + } + return new ValidateMessageStruct(message); + } + + static boolean isWrapper(Descriptor descriptor) { + return WRAPPER_TYPES.contains(descriptor.getFullName()); + } + + static FieldDescriptor requiredField(Descriptor descriptor, String name) { + FieldDescriptor field = descriptor.findFieldByName(name); + if (field == null) { + throw new IllegalArgumentException( + "no field \"" + name + "\" in " + descriptor.getFullName()); + } + return field; + } + + private static long longField(ValidateMessage message, String name) { + FieldDescriptor field = requiredField(message.getDescriptorForType(), name); + return ((Number) field(message, field).rawValue()).longValue(); + } +} diff --git a/src/main/java/build/buf/protovalidate/Validator.java b/src/main/java/build/buf/protovalidate/Validator.java index 2b0e9f6b5..f9151a11d 100644 --- a/src/main/java/build/buf/protovalidate/Validator.java +++ b/src/main/java/build/buf/protovalidate/Validator.java @@ -37,16 +37,16 @@ public interface Validator { ValidationResult validate(Message msg) throws ValidationException; /** - * Validates a message from another protobuf runtime, provided as a {@link ValidateMessage}. The - * message is copied to a protobuf-java {@link com.google.protobuf.DynamicMessage} and validated - * with {@link #validate(Message)}. + * 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. - * @throws IllegalArgumentException if a field value has the wrong type. */ default ValidationResult validate(ValidateMessage message) throws ValidationException { - return validate(ValidateMessageConverter.toMessage(message)); + throw new ValidationException("ValidateMessage validation is unsupported"); } } diff --git a/src/main/java/build/buf/protovalidate/ValidatorImpl.java b/src/main/java/build/buf/protovalidate/ValidatorImpl.java index 39613c9f8..8c0f408ae 100644 --- a/src/main/java/build/buf/protovalidate/ValidatorImpl.java +++ b/src/main/java/build/buf/protovalidate/ValidatorImpl.java @@ -48,9 +48,17 @@ public ValidationResult validate(Message msg) throws ValidationException { if (msg == null) { return ValidationResult.EMPTY; } - Descriptor descriptor = msg.getDescriptorForType(); - Evaluator evaluator = evaluatorBuilder.load(descriptor); - List result = evaluator.evaluate(new MessageValue(msg), this.failFast); + return validate(new ProtobufValidateMessage(msg)); + } + + @Override + public ValidationResult validate(ValidateMessage message) throws ValidationException { + if (message == null) { + return ValidationResult.EMPTY; + } + Evaluator evaluator = evaluatorBuilder.load(message.getDescriptorForType()); + List result = + evaluator.evaluate(new ValidateMessageValue(message), this.failFast); if (result.isEmpty()) { return ValidationResult.EMPTY; } diff --git a/src/main/java/build/buf/protovalidate/Value.java b/src/main/java/build/buf/protovalidate/Value.java index a2bb96b29..3acb4bed7 100644 --- a/src/main/java/build/buf/protovalidate/Value.java +++ b/src/main/java/build/buf/protovalidate/Value.java @@ -15,14 +15,14 @@ package build.buf.protovalidate; import com.google.protobuf.Descriptors; -import com.google.protobuf.Message; import java.util.List; import java.util.Map; import org.jspecify.annotations.Nullable; /** * {@link Value} is a wrapper around a protobuf value that provides helper methods for accessing the - * value. + * value. Implementations convert from the runtime's representation; see {@link + * ValidateMessage#getField} for the plain representation other runtimes supply. */ interface Value { /** @@ -34,35 +34,17 @@ interface Value { Descriptors.@Nullable FieldDescriptor fieldDescriptor(); /** - * Get the underlying value as a {@link Message} type. + * Get the underlying value as a {@link ValidateMessage} type. * - * @return The underlying {@link Message} value. null if the underlying value is not a {@link - * Message} type. + * @return A non-null view for a singular message or message element; null for scalar and + * collection values. */ - @Nullable Message messageValue(); + @Nullable ValidateMessage messageValue(); /** - * Get the underlying value and cast it to the class type. + * Returns the raw representation specified in the {@link Value} type table for native rules. * - * @param clazz The inferred class. - * @return The value casted to the inferred class type. - * @param The class type. - */ - T value(Class clazz); - - /** - * Returns the underlying protobuf Java value without any CEL-specific adaptation. - * - *

    {@link #value(Class)} routes scalars through {@code ProtoAdapter.toCel}, which converts - * {@code int32→Long}, {@code uint32→UnsignedLong}, {@code float→Double}, {@code bytes→ - * CelByteString}, etc. — appropriate for the CEL evaluation path but lossy for native rule - * evaluators that compare against raw protobuf field values. Native evaluators in {@code - * build.buf.protovalidate.rules} use this method to obtain values they can compare directly with - * the values they read off the typed rule message. - * - * @return The underlying value as protobuf-java provides it. Non-null for all values produced by - * the evaluator pipeline (field reads, list elements, message wrappers — all guarantee a - * value). + * @return The non-null raw value. */ Object rawValue(); @@ -78,7 +60,30 @@ interface Value { * Get the underlying value as a map. * * @return The underlying value as a map. Empty map is returned if the underlying type is not a - * list. + * map. */ Map mapValue(); + + /** + * Get the underlying value as it should be provided to CEL. + * + * @return The underlying value as a CEL-compatible type. + */ + Object celValue(); + + /** + * Returns the JVM representation specified in the {@link Value} type table, cast to {@code + * clazz}. + * + *

    Values returned by {@link ValidateMessage#getField}, {@link #repeatedValue}, or {@link + * #mapValue} must support {@code Object.class} for violation details, including message-valued + * fields and elements. Scalars must also support their compatible Java supertypes: numeric values + * accept {@code Number.class}, booleans accept {@code Boolean.class}, and strings accept {@code + * String.class}. Scalar zero-value checks use this representation. + * + * @param clazz The inferred class. + * @return The value cast to the inferred class type. + * @param The class type. + */ + T jvmValue(Class clazz); } diff --git a/src/main/java/build/buf/protovalidate/ValueEvaluator.java b/src/main/java/build/buf/protovalidate/ValueEvaluator.java index 633339bf8..51f50c1ef 100644 --- a/src/main/java/build/buf/protovalidate/ValueEvaluator.java +++ b/src/main/java/build/buf/protovalidate/ValueEvaluator.java @@ -17,6 +17,7 @@ import build.buf.protovalidate.exceptions.ExecutionException; import build.buf.validate.FieldPath; import com.google.protobuf.Descriptors; +import com.google.protobuf.Message; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -71,7 +72,7 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - if (this.shouldIgnore(val.value(Object.class))) { + if (ignoreEmpty && isZeroValue(val)) { return RuleViolation.NO_VIOLATIONS; } List allViolations = new ArrayList<>(); @@ -104,14 +105,15 @@ void setIgnoreEmpty(Object zero) { this.zero = zero; } - private boolean shouldIgnore(Object value) { - if (!this.ignoreEmpty) { - return false; + private boolean isZeroValue(Value val) { + if (zero instanceof Message) { + ValidateMessage message = val.messageValue(); + return message != null && message.isEmpty(); } - // Unsigned list items are UnsignedLong, but their zero value is a Long. - if (this.zero instanceof Long && value instanceof Number) { - return ((Number) value).longValue() == (Long) this.zero; + Object value = val.jvmValue(Object.class); + if (zero instanceof Long && value instanceof Number) { + return ((Number) value).longValue() == (Long) zero; } - return Objects.equals(value, this.zero); + return Objects.equals(value, zero); } } diff --git a/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java b/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java index 6cba9a242..b767c1318 100644 --- a/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java +++ b/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java @@ -16,7 +16,6 @@ import build.buf.protovalidate.exceptions.ExecutionException; import com.google.protobuf.Descriptors.FieldDescriptor; -import com.google.protobuf.Message; import java.util.List; /** @@ -26,8 +25,8 @@ * *

    CEL's runtime auto-unwraps wrappers to their inner primitive type, so the CEL path doesn't * need this adapter. Native evaluators expect the underlying scalar (e.g. {@code Long} for {@code - * Int64Value.value}); without unwrapping they'd see the wrapper {@link Message} and misbehave. - * Mirrors {@code wrappedValueEval} in protovalidate-go's {@code builder.go}. + * Int64Value.value}); without unwrapping they'd see the wrapper message and misbehave. Mirrors + * {@code wrappedValueEval} in protovalidate-go's {@code builder.go}. * *

    The wrapped evaluator's {@link RuleBase} is constructed against the OUTER wrapper field's * {@code ValueEvaluator}, so violation field paths point at the user's wrapper-typed field rather @@ -58,12 +57,12 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - Message message = val.messageValue(); + ValidateMessage message = val.messageValue(); if (message == null) { // proto3 message-typed field absent — no value to validate. return RuleViolation.NO_VIOLATIONS; } - Object innerValue = message.getField(innerField); - return inner.evaluate(new ObjectValue(innerField, innerValue), failFast); + Value innerValue = ValidateMessages.field(message, innerField); + return inner.evaluate(innerValue, failFast); } } diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageConverterTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageConverterTest.java deleted file mode 100644 index 9aa13c78d..000000000 --- a/src/test/java/build/buf/protovalidate/ValidateMessageConverterTest.java +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright 2023-2026 Buf Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package build.buf.protovalidate; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import build.buf.validate.BytesRules; -import build.buf.validate.FieldRules; -import build.buf.validate.ValidateProto; -import com.google.protobuf.BoolValue; -import com.google.protobuf.ByteString; -import com.google.protobuf.BytesValue; -import com.google.protobuf.DescriptorProtos.DescriptorProto; -import com.google.protobuf.DescriptorProtos.FieldDescriptorProto; -import com.google.protobuf.DescriptorProtos.FieldOptions; -import com.google.protobuf.DescriptorProtos.FileDescriptorProto; -import com.google.protobuf.Descriptors.Descriptor; -import com.google.protobuf.Descriptors.FieldDescriptor; -import com.google.protobuf.Descriptors.FileDescriptor; -import com.google.protobuf.DoubleValue; -import com.google.protobuf.FloatValue; -import com.google.protobuf.Int32Value; -import com.google.protobuf.Int64Value; -import com.google.protobuf.Message; -import com.google.protobuf.StringValue; -import com.google.protobuf.Struct; -import com.google.protobuf.UInt32Value; -import java.util.Collections; -import java.util.stream.Stream; -import org.jspecify.annotations.Nullable; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; -import org.junit.jupiter.params.provider.ValueSource; - -public class ValidateMessageConverterTest { - private static Stream wrongTypes() { - return Stream.of( - Arguments.of(field(Int32Value.getDescriptor(), "value"), 1L), - Arguments.of(field(UInt32Value.getDescriptor(), "value"), 1L), - Arguments.of(field(Int64Value.getDescriptor(), "value"), 1), - Arguments.of(field(FloatValue.getDescriptor(), "value"), 1.0d), - Arguments.of(field(DoubleValue.getDescriptor(), "value"), 1.0f), - Arguments.of(field(BoolValue.getDescriptor(), "value"), "true"), - Arguments.of(field(StringValue.getDescriptor(), "value"), 1), - Arguments.of(field(FieldDescriptorProto.getDescriptor(), "type"), "TYPE_INT32"), - Arguments.of( - field(FieldDescriptorProto.getDescriptor(), "options"), - FieldOptions.getDefaultInstance()), - Arguments.of(field(DescriptorProto.getDescriptor(), "field"), Collections.emptySet()), - // protobuf-java returns map fields as a list of entries; the plain API wants a Map. - Arguments.of(field(Struct.getDescriptor(), "fields"), Collections.emptyList()), - Arguments.of( - field(DescriptorProto.getDescriptor(), "reserved_name"), Collections.singletonList(1)), - Arguments.of( - field(DescriptorProto.getDescriptor(), "reserved_name"), - Collections.singletonList(null)), - Arguments.of( - field(Struct.getDescriptor(), "fields"), Collections.singletonMap("key", null))); - } - - @ParameterizedTest(name = "{0} = {1}") - @MethodSource("wrongTypes") - public void rejectsWrongType(FieldDescriptor field, Object value) { - assertThatThrownBy(() -> ValidateMessageConverter.toMessage(new OneField(field, value))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("field \"" + field.getFullName() + "\" has an invalid value"); - } - - @Test - public void acceptsDocumentedTypes() { - FieldDescriptor enumField = field(FieldDescriptorProto.getDescriptor(), "type"); - Object enumValue = FieldDescriptorProto.Type.TYPE_INT32.getValueDescriptor(); - Object number = FieldDescriptorProto.Type.TYPE_INT32.getNumber(); - FieldDescriptor bytesField = field(BytesValue.getDescriptor(), "value"); - - assertThat(convert(enumField, number)).isEqualTo(enumValue); - assertThat(convert(enumField, enumValue)).isEqualTo(enumValue); - assertThat(convert(bytesField, ByteString.copyFromUtf8("a"))) - .isEqualTo(ByteString.copyFromUtf8("a")); - assertThat(convert(bytesField, new byte[] {'a'})).isEqualTo(ByteString.copyFromUtf8("a")); - } - - // Native rules read bytes as ByteString, so a byte[] once failed only with native rules on. - @ParameterizedTest(name = "nativeRules={0}") - @ValueSource(booleans = {true, false}) - public void validatesByteArrayBytes(boolean nativeRules) throws Exception { - FieldDescriptorProto data = - FieldDescriptorProto.newBuilder() - .setName("data") - .setNumber(1) - .setType(FieldDescriptorProto.Type.TYPE_BYTES) - .setOptions( - FieldOptions.newBuilder() - .setExtension( - ValidateProto.field, - FieldRules.newBuilder() - .setBytes(BytesRules.newBuilder().setMinLen(3)) - .build())) - .build(); - Descriptor descriptor = - FileDescriptor.buildFrom( - FileDescriptorProto.newBuilder() - .setName("blob.proto") - .setSyntax("proto3") - .addDependency(ValidateProto.getDescriptor().getName()) - .addMessageType(DescriptorProto.newBuilder().setName("Blob").addField(data)) - .build(), - new FileDescriptor[] {ValidateProto.getDescriptor()}) - .findMessageTypeByName("Blob"); - Validator validator = - ValidatorFactory.newBuilder() - .withConfig(Config.newBuilder().setEnableNativeRules(nativeRules).build()) - .build(); - - ValidationResult result = - validator.validate(new OneField(descriptor.findFieldByName("data"), new byte[] {1})); - - assertThat(result.getViolations()) - .extracting(violation -> violation.toProto().getRuleId()) - .containsExactly("bytes.min_len"); - } - - private static Object convert(FieldDescriptor field, Object value) { - Message message = ValidateMessageConverter.toMessage(new OneField(field, value)); - return message.getField(field); - } - - private static FieldDescriptor field(Descriptor descriptor, String name) { - return descriptor.findFieldByName(name); - } - - /** A {@link ValidateMessage} with one populated field. */ - private static final class OneField implements ValidateMessage { - private final FieldDescriptor field; - private final Object value; - - OneField(FieldDescriptor field, Object value) { - this.field = field; - this.value = value; - } - - @Override - public Descriptor getDescriptorForType() { - return field.getContainingType(); - } - - @Override - public boolean hasField(FieldDescriptor other) { - return other.equals(field); - } - - @Override - public @Nullable Object getField(FieldDescriptor other) { - return other.equals(field) ? value : null; - } - } -} diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java index b088965f4..6621ced82 100644 --- a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java +++ b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java @@ -47,7 +47,6 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import org.junit.jupiter.params.provider.ValueSource; /** * Exercises {@link Validator#validate(ValidateMessage)} with an alternative-runtime {@link @@ -305,26 +304,26 @@ public void messageFieldRequiresValidateMessage() throws Exception { .hasMessageContaining("ValidateMessage"); } - @ParameterizedTest(name = "nativeRules={0}") - @ValueSource(booleans = {true, false}) - public void scalarFieldRequiresDocumentedType(boolean nativeRules) throws Exception { + @Test + public void messageValueJvmValueUnsupported() throws Exception { + // A message has no raw scalar form, so jvmValue is unsupported on a message-backed Value. Descriptors.Descriptor descriptor = buildPersonDescriptor(); Descriptors.Descriptor addressDescriptor = descriptor.findFieldByName("address").getMessageType(); - // age is an int32; a Long must fail with an error naming the field. - Map fields = - personFields(descriptor, "alice", 30, address(addressDescriptor, "Main Street")); - fields.put(descriptor.findFieldByName("age"), 30L); - ValidateMessage message = new MapValidateMessage(descriptor, fields); - - Validator validator = - ValidatorFactory.newBuilder() - .withConfig(Config.newBuilder().setEnableNativeRules(nativeRules).build()) - .build(); - assertThatThrownBy(() -> validator.validate(message)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("field \"example.Person.age\" has an invalid value"); + Value messageValue = new ValidateMessageValue(address(addressDescriptor, "Main Street")); + assertThatThrownBy(() -> messageValue.jvmValue(Object.class)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("jvmValue returns a raw scalar for native rule evaluation") + .hasMessageContaining("not supported on a message value") + .hasMessageContaining("ValidateMessage.getField() implementation returned a message value"); + + Value protobufMessageValue = new MessageValue(Timestamp.getDefaultInstance()); + assertThatThrownBy(() -> protobufMessageValue.jvmValue(Object.class)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("jvmValue returns a raw scalar for native rule evaluation") + .hasMessageContaining("not supported on a message value") + .hasMessageContaining("use messageValue() or celValue() instead"); } @Test diff --git a/src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java b/src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java index 055f6b0dc..b9417c521 100644 --- a/src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java +++ b/src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java @@ -15,12 +15,14 @@ package build.buf.protovalidate.external; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import build.buf.protovalidate.Config; import build.buf.protovalidate.ValidateMessage; import build.buf.protovalidate.ValidationResult; import build.buf.protovalidate.Validator; import build.buf.protovalidate.ValidatorFactory; +import build.buf.protovalidate.exceptions.ValidationException; import build.buf.validate.BytesRules; import build.buf.validate.EnumRules; import build.buf.validate.FieldRules; @@ -69,7 +71,9 @@ void legacyValidatorRemainsImplementable() throws Exception { descriptor(field("s", FieldDescriptorProto.Type.TYPE_STRING, FieldRules.newBuilder())); ExternalMessage message = message(descriptor, "s", "abc"); assertThat(legacy.validate(toProtobuf(message))).isSameAs(ValidationResult.EMPTY); - assertThat(legacy.validate(message)).isSameAs(ValidationResult.EMPTY); + assertThatThrownBy(() -> legacy.validate(message)) + .isInstanceOf(ValidationException.class) + .hasMessageContaining("unsupported"); } @ParameterizedTest @@ -319,6 +323,9 @@ void oneofDefaultValuesArePresent(boolean nativeRules) throws Exception { .setOneofIndex(0)); ExternalMessage empty = new ExternalMessage(descriptor, Collections.emptyMap()); ExternalMessage populated = message(descriptor, "s", ""); + assertThat(empty.getOneofFieldDescriptor(descriptor.getOneofs().get(0))).isNull(); + assertThat(populated.getOneofFieldDescriptor(descriptor.getOneofs().get(0))) + .isEqualTo(descriptor.findFieldByName("s")); assertParity(nativeRules, empty, 1); assertParity(nativeRules, populated, 0); } @@ -470,8 +477,8 @@ public Descriptor getDescriptorForType() { } @Override - public UnknownFieldSet getUnknownFields() { - return unknownFields; + public boolean isEmpty() { + return unknownFields.asMap().isEmpty() && ValidateMessage.super.isEmpty(); } @Override From 85720eb46fc5d34334272b813828a883821fb7c1 Mon Sep 17 00:00:00 2001 From: Jon Bodner Date: Thu, 3 Dec 2026 13:29:11 -0500 Subject: [PATCH 12/23] Check plain field value types when wrapping them 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. --- .../build/buf/protovalidate/PlainValue.java | 59 ++++++++-- .../buf/protovalidate/ValidateMessage.java | 3 +- .../buf/protovalidate/PlainValueTest.java | 102 ++++++++++++++++++ .../protovalidate/ValidateMessageTest.java | 24 +++++ 4 files changed, 179 insertions(+), 9 deletions(-) create mode 100644 src/test/java/build/buf/protovalidate/PlainValueTest.java diff --git a/src/main/java/build/buf/protovalidate/PlainValue.java b/src/main/java/build/buf/protovalidate/PlainValue.java index 7ad58f70b..f8df407d1 100644 --- a/src/main/java/build/buf/protovalidate/PlainValue.java +++ b/src/main/java/build/buf/protovalidate/PlainValue.java @@ -39,6 +39,56 @@ final class PlainValue implements Value { this.field = field; this.value = value; this.element = element; + checkType(); + } + + // Fails here, naming the field, instead of as a ClassCastException in a rule evaluator. + private void checkType() { + if (value == null) { + return; + } + Class expected = expectedType(); + if (expected.isInstance(value) + || (field.getJavaType() == JavaType.ENUM && value instanceof EnumValueDescriptor)) { + return; + } + throw new IllegalArgumentException( + "field \"" + + field.getFullName() + + "\" must be of type " + + expected.getSimpleName() + + ", but got " + + value.getClass().getName()); + } + + private Class expectedType() { + if (isList()) { + return List.class; + } + if (isMap()) { + return Map.class; + } + switch (field.getJavaType()) { + case INT: + case ENUM: + return Integer.class; + case LONG: + return Long.class; + case FLOAT: + return Float.class; + case DOUBLE: + return Double.class; + case BOOLEAN: + return Boolean.class; + case STRING: + return String.class; + case BYTE_STRING: + return ByteString.class; + case MESSAGE: + return ValidateMessage.class; + } + throw new IllegalStateException( + "field \"" + field.getFullName() + "\" has unknown java type " + field.getJavaType()); } @Override @@ -161,13 +211,6 @@ private ValidateMessage message() { if (value == null) { return new EmptyValidateMessage(field.getMessageType()); } - if (!(value instanceof ValidateMessage)) { - throw new IllegalArgumentException( - "message field \"" - + field.getName() - + "\" must be provided as a ValidateMessage, but got " - + value.getClass().getName()); - } return (ValidateMessage) value; } @@ -178,7 +221,7 @@ private Object scalar() { } return value instanceof EnumValueDescriptor ? ((EnumValueDescriptor) value).getNumber() - : ((Number) value).intValue(); + : value; } if (value != null) { return value; diff --git a/src/main/java/build/buf/protovalidate/ValidateMessage.java b/src/main/java/build/buf/protovalidate/ValidateMessage.java index d9ffe18b3..143cb0d6d 100644 --- a/src/main/java/build/buf/protovalidate/ValidateMessage.java +++ b/src/main/java/build/buf/protovalidate/ValidateMessage.java @@ -90,7 +90,8 @@ default boolean isEmpty() { * * *

    Repeated fields are a {@link java.util.List} of those values, and map fields a {@link - * java.util.Map}. + * 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. diff --git a/src/test/java/build/buf/protovalidate/PlainValueTest.java b/src/test/java/build/buf/protovalidate/PlainValueTest.java new file mode 100644 index 000000000..c9df7a8b3 --- /dev/null +++ b/src/test/java/build/buf/protovalidate/PlainValueTest.java @@ -0,0 +1,102 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.BoolValue; +import com.google.protobuf.ByteString; +import com.google.protobuf.BytesValue; +import com.google.protobuf.DescriptorProtos.DescriptorProto; +import com.google.protobuf.DescriptorProtos.FieldDescriptorProto; +import com.google.protobuf.DescriptorProtos.FieldOptions; +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.DoubleValue; +import com.google.protobuf.FloatValue; +import com.google.protobuf.Int32Value; +import com.google.protobuf.Int64Value; +import com.google.protobuf.StringValue; +import com.google.protobuf.Struct; +import com.google.protobuf.UInt32Value; +import java.util.Collections; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +public class PlainValueTest { + private static Stream wrongTypes() { + return Stream.of( + Arguments.of(field(Int32Value.getDescriptor(), "value"), 1L, "Integer"), + Arguments.of(field(UInt32Value.getDescriptor(), "value"), 1L, "Integer"), + Arguments.of(field(Int64Value.getDescriptor(), "value"), 1, "Long"), + Arguments.of(field(FloatValue.getDescriptor(), "value"), 1.0d, "Float"), + Arguments.of(field(DoubleValue.getDescriptor(), "value"), 1.0f, "Double"), + Arguments.of(field(BoolValue.getDescriptor(), "value"), "true", "Boolean"), + Arguments.of(field(StringValue.getDescriptor(), "value"), 1, "String"), + Arguments.of(field(BytesValue.getDescriptor(), "value"), new byte[] {1}, "ByteString"), + Arguments.of(field(FieldDescriptorProto.getDescriptor(), "type"), "TYPE_INT32", "Integer"), + Arguments.of( + field(FieldDescriptorProto.getDescriptor(), "options"), + FieldOptions.getDefaultInstance(), + "ValidateMessage"), + Arguments.of( + field(DescriptorProto.getDescriptor(), "field"), Collections.emptySet(), "List"), + // protobuf-java returns map fields as a list of entries; the plain API wants a Map. + Arguments.of(field(Struct.getDescriptor(), "fields"), Collections.emptyList(), "Map")); + } + + @ParameterizedTest(name = "{0} = {1}") + @MethodSource("wrongTypes") + public void rejectsWrongType(FieldDescriptor field, Object value, String expected) { + assertThatThrownBy(() -> new PlainValue(field, value, false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(field.getFullName()) + .hasMessageContaining("must be of type " + expected) + .hasMessageContaining(value.getClass().getName()); + } + + @Test + public void rejectsWrongElementType() { + FieldDescriptor field = field(DescriptorProto.getDescriptor(), "reserved_name"); + PlainValue list = new PlainValue(field, Collections.singletonList(1), false); + + assertThatThrownBy(list::repeatedValue) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must be of type String"); + } + + @Test + public void acceptsDocumentedTypes() { + FieldDescriptor enumField = field(FieldDescriptorProto.getDescriptor(), "type"); + Object number = FieldDescriptorProto.Type.TYPE_INT32.getNumber(); + Object descriptor = FieldDescriptorProto.Type.TYPE_INT32.getValueDescriptor(); + + assertThat(new PlainValue(enumField, number, false).rawValue()).isEqualTo(number); + assertThat(new PlainValue(enumField, descriptor, false).rawValue()).isEqualTo(number); + assertThat(new PlainValue(enumField, null, false).rawValue()).isEqualTo(1); + assertThat( + new PlainValue(field(BytesValue.getDescriptor(), "value"), ByteString.EMPTY, false) + .rawValue()) + .isEqualTo(ByteString.EMPTY); + } + + private static FieldDescriptor field(Descriptor descriptor, String name) { + return descriptor.findFieldByName(name); + } +} diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java index 6621ced82..7b386fa79 100644 --- a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java +++ b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java @@ -47,6 +47,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; /** * Exercises {@link Validator#validate(ValidateMessage)} with an alternative-runtime {@link @@ -304,6 +305,29 @@ public void messageFieldRequiresValidateMessage() throws Exception { .hasMessageContaining("ValidateMessage"); } + @ParameterizedTest(name = "nativeRules={0}") + @ValueSource(booleans = {true, false}) + public void scalarFieldRequiresDocumentedType(boolean nativeRules) throws Exception { + Descriptors.Descriptor descriptor = buildPersonDescriptor(); + Descriptors.Descriptor addressDescriptor = + descriptor.findFieldByName("address").getMessageType(); + + // age is an int32; a Long must fail with a clear error, not a ClassCastException. + Map fields = + personFields(descriptor, "alice", 30, address(addressDescriptor, "Main Street")); + fields.put(descriptor.findFieldByName("age"), 30L); + ValidateMessage message = new MapValidateMessage(descriptor, fields); + + Validator validator = + ValidatorFactory.newBuilder() + .withConfig(Config.newBuilder().setEnableNativeRules(nativeRules).build()) + .build(); + // The message-level CEL rule reads age first, so the error arrives wrapped by CEL. + assertThatThrownBy(() -> validator.validate(message)) + .hasMessageContaining("field \"example.Person.age\" must be of type Integer") + .hasMessageContaining("but got java.lang.Long"); + } + @Test public void messageValueJvmValueUnsupported() throws Exception { // A message has no raw scalar form, so jvmValue is unsupported on a message-backed Value. From ac4f2f7c3c38d489b49ebbcbff5566bc8688bcdb Mon Sep 17 00:00:00 2001 From: Jon Bodner Date: Thu, 3 Dec 2026 14:10:56 -0500 Subject: [PATCH 13/23] Keep nested ValidateMessages readable and comparable in CEL 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. --- .../protovalidate/ValidateMessageStruct.java | 89 ++++- .../ValidateMessageCelCollectionTest.java | 341 ++++++++++++++++++ 2 files changed, 427 insertions(+), 3 deletions(-) create mode 100644 src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java diff --git a/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java b/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java index f09567917..bb54a3300 100644 --- a/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java +++ b/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java @@ -16,11 +16,16 @@ import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Message; import dev.cel.common.types.CelType; import dev.cel.common.types.StructTypeReference; import dev.cel.common.values.NullValue; import dev.cel.common.values.StructValue; +import java.util.List; +import java.util.Map; +import java.util.Objects; import java.util.Optional; +import org.jspecify.annotations.Nullable; /** * Presents a {@link ValidateMessage} to CEL as a struct. CEL reads fields with {@link #select}, @@ -28,7 +33,7 @@ */ // Messages are only read during validation, so the struct is effectively immutable. @SuppressWarnings("Immutable") -final class ValidateMessageStruct extends StructValue { +final class ValidateMessageStruct extends StructValue { private final ValidateMessage message; private final Descriptor descriptor; @@ -37,9 +42,11 @@ final class ValidateMessageStruct extends StructValue { this.descriptor = message.getDescriptorForType(); } + // CEL unwraps a struct to value() when it ends a select chain. Returning the struct keeps the + // message readable and comparable by contents after that, as protobuf-java messages are. @Override - public ValidateMessage value() { - return message; + public ValidateMessageStruct value() { + return this; } @Override @@ -70,4 +77,80 @@ public Optional find(String fieldName) { FieldDescriptor field = ValidateMessages.requiredField(descriptor, fieldName); return message.hasField(field) ? Optional.of(select(fieldName)) : Optional.empty(); } + + @Override + public boolean equals(@Nullable Object other) { + ValidateMessageStruct that = asStruct(other); + if (that == null || !descriptor.getFullName().equals(that.descriptor.getFullName())) { + return false; + } + for (FieldDescriptor field : descriptor.getFields()) { + boolean present = message.hasField(field); + if (present != that.message.hasField(field)) { + return false; + } + if (present && !celEquals(select(field.getName()), that.select(field.getName()))) { + return false; + } + } + return true; + } + + @Override + public int hashCode() { + int hash = descriptor.getFullName().hashCode(); + for (FieldDescriptor field : descriptor.getFields()) { + if (message.hasField(field)) { + hash = 31 * hash + field.getNumber(); + } + } + return hash; + } + + // A protobuf-java message is compared field by field, so CEL message literals and nested + // protobuf-java values compare equal to structs with the same contents. + private static @Nullable ValidateMessageStruct asStruct(@Nullable Object value) { + if (value instanceof ValidateMessageStruct) { + return (ValidateMessageStruct) value; + } + if (value instanceof Message) { + return new ValidateMessageStruct(new ProtobufValidateMessage((Message) value)); + } + return null; + } + + private static boolean celEquals(Object left, Object right) { + ValidateMessageStruct struct = asStruct(left); + if (struct != null) { + return struct.equals(right); + } + if (left instanceof List && right instanceof List) { + List leftList = (List) left; + List rightList = (List) right; + if (leftList.size() != rightList.size()) { + return false; + } + for (int i = 0; i < leftList.size(); i++) { + if (!celEquals(leftList.get(i), rightList.get(i))) { + return false; + } + } + return true; + } + if (left instanceof Map && right instanceof Map) { + Map leftMap = (Map) left; + Map rightMap = (Map) right; + if (leftMap.size() != rightMap.size()) { + return false; + } + for (Map.Entry entry : leftMap.entrySet()) { + if (!rightMap.containsKey(entry.getKey()) + || !celEquals(entry.getValue(), rightMap.get(entry.getKey()))) { + return false; + } + } + return true; + } + return Objects.equals(left, right); + } } diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java new file mode 100644 index 000000000..310ec800d --- /dev/null +++ b/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java @@ -0,0 +1,341 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import static org.assertj.core.api.Assertions.assertThat; + +import build.buf.validate.MessageRules; +import build.buf.validate.Rule; +import build.buf.validate.ValidateProto; +import com.google.protobuf.ByteString; +import com.google.protobuf.DescriptorProtos.DescriptorProto; +import com.google.protobuf.DescriptorProtos.EnumDescriptorProto; +import com.google.protobuf.DescriptorProtos.EnumValueDescriptorProto; +import com.google.protobuf.DescriptorProtos.FieldDescriptorProto; +import com.google.protobuf.DescriptorProtos.FileDescriptorProto; +import com.google.protobuf.DescriptorProtos.MessageOptions; +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Descriptors.FileDescriptor; +import com.google.protobuf.DynamicMessage; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import org.jspecify.annotations.Nullable; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** CEL rules that use nested messages of a {@link ValidateMessage} as values. */ +public class ValidateMessageCelCollectionTest { + private final Validator validator = ValidatorFactory.newBuilder().build(); + + // Each expression is true for the test data. CEL unwraps a message that ends a select chain, so + // these check reading and comparing that message, and scalars in lists and maps. + @ParameterizedTest(name = "{0}") + @ValueSource( + strings = { + "this.target.name == 'alice'", + "this.items.all(i, i.name.size() > 0)", + "this.items[0].name == 'alice'", + "this.by_name.all(k, this.by_name[k].name.size() > 0)", + "this.items.all(i, has(i.name))", + "this.items.all(i, !has(i.child))", + "this.items.map(i, i.name) == ['alice']", + "this.items.filter(i, i.name == 'alice')[0].name == 'alice'", + "[this.target][0].name == 'alice'", + "{'a': this.target}['a'].name == 'alice'", + "dyn(this.target).name == 'alice'", + "this.target == this.items[0]", + "this.target != this.other", + "this.target in this.items", + "this.items.exists(i, i == this.target)", + "this.by_name.exists(k, this.by_name[k] == this.target)", + "this.items == [this.target]", + "type(this.target) == test.v1.Inner", + "this.target.child == test.v1.Inner{}", + "this.target == this.target", + "this.target != test.v1.Inner{name: 'bob'}", + "this.scalars.u32s == [1u]", + "1u in this.scalars.u32s", + "this.scalars.es == [1]", + "this.scalars.bs == [b'a']", + "this.scalars.fs == [1.5]", + "this.scalars.by_u32[1u] == 'x'", + "1u in this.scalars.by_u32", + "this.scalars.by_i64[1] == 'x'", + "this.scalars.by_bool[true] == 'x'", + "this.scalars == this.scalars", + }) + public void matchesProtobufJava(String expression) { + Descriptor outer = buildOuterDescriptor(expression); + + String plain = outcome(plainOuter(outer)); + String protobuf = outcome(dynamicOuter(outer)); + + assertThat(protobuf).as("protobuf-java").isEqualTo("[]"); + assertThat(plain).as("ValidateMessage").isEqualTo(protobuf); + } + + // protobuf-java messages get these wrong: cel-java 0.15.0 reads repeated unsigned fields as + // signed. They pin the correct behavior for other runtimes. + @ParameterizedTest(name = "{0}") + @ValueSource( + strings = { + "this.scalars.u32s.all(u, u > 0u)", + "this.scalars.u64s[0] == 18446744073709551615u", + }) + public void readsUnsignedListElements(String expression) { + assertThat(outcome(plainOuter(buildOuterDescriptor(expression)))).isEqualTo("[]"); + } + + private String outcome(Object message) { + try { + ValidationResult result = + message instanceof ValidateMessage + ? validator.validate((ValidateMessage) message) + : validator.validate((com.google.protobuf.Message) message); + return result.getViolations().stream() + .map(violation -> violation.toProto().getRuleId()) + .collect(Collectors.toList()) + .toString(); + } catch (Exception e) { + return e.toString(); + } + } + + private static ValidateMessage plainOuter(Descriptor outer) { + Descriptor inner = outer.getFile().findMessageTypeByName("Inner"); + FieldDescriptor name = inner.findFieldByName("name"); + // Distinct instances with equal contents, as a runtime adapter returns for each read. + Map fields = new HashMap<>(); + fields.put( + outer.findFieldByName("items"), + Collections.singletonList( + new MapValidateMessage(inner, Collections.singletonMap(name, "alice")))); + fields.put( + outer.findFieldByName("by_name"), + Collections.singletonMap( + "key", new MapValidateMessage(inner, Collections.singletonMap(name, "alice")))); + fields.put( + outer.findFieldByName("target"), + new MapValidateMessage(inner, Collections.singletonMap(name, "alice"))); + fields.put( + outer.findFieldByName("other"), + new MapValidateMessage(inner, Collections.singletonMap(name, "bob"))); + Descriptor scalars = outer.getFile().findMessageTypeByName("Scalars"); + Map scalarFields = new HashMap<>(); + scalarFields.put(scalars.findFieldByName("u32s"), Collections.singletonList(1)); + scalarFields.put(scalars.findFieldByName("u64s"), Collections.singletonList(-1L)); + scalarFields.put(scalars.findFieldByName("es"), Collections.singletonList(1)); + scalarFields.put( + scalars.findFieldByName("bs"), Collections.singletonList(ByteString.copyFromUtf8("a"))); + scalarFields.put(scalars.findFieldByName("fs"), Collections.singletonList(1.5f)); + scalarFields.put(scalars.findFieldByName("by_u32"), Collections.singletonMap(1, "x")); + scalarFields.put(scalars.findFieldByName("by_i64"), Collections.singletonMap(1L, "x")); + scalarFields.put(scalars.findFieldByName("by_bool"), Collections.singletonMap(true, "x")); + fields.put(outer.findFieldByName("scalars"), new MapValidateMessage(scalars, scalarFields)); + return new MapValidateMessage(outer, fields); + } + + private static DynamicMessage dynamicScalars(Descriptor scalars) { + return DynamicMessage.newBuilder(scalars) + .addRepeatedField(scalars.findFieldByName("u32s"), 1) + .addRepeatedField(scalars.findFieldByName("u64s"), -1L) + .addRepeatedField( + scalars.findFieldByName("es"), + scalars.getFile().findEnumTypeByName("E").findValueByNumber(1)) + .addRepeatedField(scalars.findFieldByName("bs"), ByteString.copyFromUtf8("a")) + .addRepeatedField(scalars.findFieldByName("fs"), 1.5f) + .addRepeatedField(scalars.findFieldByName("by_u32"), entry(scalars, "by_u32", 1)) + .addRepeatedField(scalars.findFieldByName("by_i64"), entry(scalars, "by_i64", 1L)) + .addRepeatedField(scalars.findFieldByName("by_bool"), entry(scalars, "by_bool", true)) + .build(); + } + + private static DynamicMessage entry(Descriptor message, String field, Object key) { + Descriptor entryType = message.findFieldByName(field).getMessageType(); + return DynamicMessage.newBuilder(entryType) + .setField(entryType.findFieldByName("key"), key) + .setField(entryType.findFieldByName("value"), "x") + .build(); + } + + private static DynamicMessage dynamicOuter(Descriptor outer) { + Descriptor inner = outer.getFile().findMessageTypeByName("Inner"); + FieldDescriptor name = inner.findFieldByName("name"); + DynamicMessage alice = DynamicMessage.newBuilder(inner).setField(name, "alice").build(); + FieldDescriptor byName = outer.findFieldByName("by_name"); + Descriptor entryType = byName.getMessageType(); + DynamicMessage entry = + DynamicMessage.newBuilder(entryType) + .setField(entryType.findFieldByName("key"), "key") + .setField(entryType.findFieldByName("value"), alice) + .build(); + return DynamicMessage.newBuilder(outer) + .addRepeatedField(outer.findFieldByName("items"), alice) + .addRepeatedField(byName, entry) + .setField(outer.findFieldByName("target"), alice) + .setField( + outer.findFieldByName("other"), + DynamicMessage.newBuilder(inner).setField(name, "bob").build()) + .setField( + outer.findFieldByName("scalars"), + dynamicScalars(outer.getFile().findMessageTypeByName("Scalars"))) + .build(); + } + + private static Descriptor buildOuterDescriptor(String expression) { + DescriptorProto entry = + DescriptorProto.newBuilder() + .setName("ByNameEntry") + .setOptions(MessageOptions.newBuilder().setMapEntry(true)) + .addField(field("key", 1, FieldDescriptorProto.Type.TYPE_STRING)) + .addField(innerField("value", 2)) + .build(); + Rule rule = + Rule.newBuilder().setId("rule").setMessage("rule").setExpression(expression).build(); + DescriptorProto outer = + DescriptorProto.newBuilder() + .setName("Outer") + .setOptions( + MessageOptions.newBuilder() + .setExtension( + ValidateProto.message, MessageRules.newBuilder().addCel(rule).build())) + .addNestedType(entry) + .addField(innerField("items", 1).setLabel(FieldDescriptorProto.Label.LABEL_REPEATED)) + .addField( + field("by_name", 2, FieldDescriptorProto.Type.TYPE_MESSAGE) + .setLabel(FieldDescriptorProto.Label.LABEL_REPEATED) + .setTypeName(".test.v1.Outer.ByNameEntry")) + .addField(innerField("target", 3)) + .addField(innerField("other", 4)) + .addField( + field("scalars", 5, FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".test.v1.Scalars")) + .build(); + DescriptorProto scalars = + DescriptorProto.newBuilder() + .setName("Scalars") + .addNestedType(mapEntry("ByU32Entry", FieldDescriptorProto.Type.TYPE_UINT32)) + .addNestedType(mapEntry("ByI64Entry", FieldDescriptorProto.Type.TYPE_INT64)) + .addNestedType(mapEntry("ByBoolEntry", FieldDescriptorProto.Type.TYPE_BOOL)) + .addField(repeated("u32s", 1, FieldDescriptorProto.Type.TYPE_UINT32)) + .addField(repeated("u64s", 2, FieldDescriptorProto.Type.TYPE_UINT64)) + .addField( + repeated("es", 3, FieldDescriptorProto.Type.TYPE_ENUM).setTypeName(".test.v1.E")) + .addField(repeated("bs", 4, FieldDescriptorProto.Type.TYPE_BYTES)) + .addField(repeated("fs", 5, FieldDescriptorProto.Type.TYPE_FLOAT)) + .addField( + repeated("by_u32", 6, FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".test.v1.Scalars.ByU32Entry")) + .addField( + repeated("by_i64", 7, FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".test.v1.Scalars.ByI64Entry")) + .addField( + repeated("by_bool", 8, FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".test.v1.Scalars.ByBoolEntry")) + .build(); + EnumDescriptorProto enumType = + EnumDescriptorProto.newBuilder() + .setName("E") + .addValue(EnumValueDescriptorProto.newBuilder().setName("E_UNSPECIFIED").setNumber(0)) + .addValue(EnumValueDescriptorProto.newBuilder().setName("E_ONE").setNumber(1)) + .build(); + DescriptorProto inner = + DescriptorProto.newBuilder() + .setName("Inner") + .addField(field("name", 1, FieldDescriptorProto.Type.TYPE_STRING)) + .addField(innerField("child", 2)) + .build(); + try { + return FileDescriptor.buildFrom( + FileDescriptorProto.newBuilder() + .setName("cel_collections.proto") + .setPackage("test.v1") + .setSyntax("proto3") + .addDependency(ValidateProto.getDescriptor().getName()) + .addEnumType(enumType) + .addMessageType(inner) + .addMessageType(scalars) + .addMessageType(outer) + .build(), + new FileDescriptor[] {ValidateProto.getDescriptor()}) + .findMessageTypeByName("Outer"); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private static FieldDescriptorProto.Builder field( + String name, int number, FieldDescriptorProto.Type type) { + return FieldDescriptorProto.newBuilder().setName(name).setNumber(number).setType(type); + } + + private static FieldDescriptorProto.Builder repeated( + String name, int number, FieldDescriptorProto.Type type) { + return field(name, number, type).setLabel(FieldDescriptorProto.Label.LABEL_REPEATED); + } + + private static DescriptorProto mapEntry(String name, FieldDescriptorProto.Type keyType) { + return DescriptorProto.newBuilder() + .setName(name) + .setOptions(MessageOptions.newBuilder().setMapEntry(true)) + .addField(field("key", 1, keyType)) + .addField(field("value", 2, FieldDescriptorProto.Type.TYPE_STRING)) + .build(); + } + + private static FieldDescriptorProto.Builder innerField(String name, int number) { + return field(name, number, FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".test.v1.Inner"); + } + + private static final class MapValidateMessage implements ValidateMessage { + private final Descriptor descriptor; + private final Map fields; + + MapValidateMessage(Descriptor descriptor, Map fields) { + this.descriptor = descriptor; + this.fields = fields; + } + + @Override + public Descriptor getDescriptorForType() { + return descriptor; + } + + @Override + public boolean hasField(FieldDescriptor field) { + Object value = fields.get(field); + if (value instanceof Map) { + return !((Map) value).isEmpty(); + } + if (value instanceof List) { + return !((List) value).isEmpty(); + } + if (value instanceof ValidateMessage) { + return true; + } + return value != null && !value.equals(field.getDefaultValue()); + } + + @Override + public @Nullable Object getField(FieldDescriptor field) { + return fields.get(field); + } + } +} From 1608eccc9789d34613fe46b978a1266d8fcdd9d4 Mon Sep 17 00:00:00 2001 From: Jon Bodner Date: Thu, 3 Dec 2026 14:27:59 -0500 Subject: [PATCH 14/23] Give CEL protobuf-java copies of Any, Struct, Value and ListValue 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. --- .../buf/protovalidate/ProtobufCopies.java | 105 +++++++ .../buf/protovalidate/ValidateMessages.java | 3 +- .../buf/protovalidate/MapValidateMessage.java | 101 ++++++ .../ValidateMessageCelCollectionTest.java | 37 --- .../ValidateMessageWellKnownTypesTest.java | 289 ++++++++++++++++++ 5 files changed, 497 insertions(+), 38 deletions(-) create mode 100644 src/main/java/build/buf/protovalidate/ProtobufCopies.java create mode 100644 src/test/java/build/buf/protovalidate/MapValidateMessage.java create mode 100644 src/test/java/build/buf/protovalidate/ValidateMessageWellKnownTypesTest.java diff --git a/src/main/java/build/buf/protovalidate/ProtobufCopies.java b/src/main/java/build/buf/protovalidate/ProtobufCopies.java new file mode 100644 index 000000000..cbec6d211 --- /dev/null +++ b/src/main/java/build/buf/protovalidate/ProtobufCopies.java @@ -0,0 +1,105 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import com.google.protobuf.Any; +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.EnumValueDescriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.DynamicMessage; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.ListValue; +import com.google.protobuf.Message; +import com.google.protobuf.Parser; +import com.google.protobuf.Struct; +import java.util.HashMap; +import java.util.Map; +import org.jspecify.annotations.Nullable; + +// CEL unpacks Any and reads Struct, Value and ListValue as JSON values, but only for +// protobuf-java messages, so ValidateMessages of these types are copied into them. +final class ProtobufCopies { + private static final Map> PARSERS = new HashMap<>(); + + static { + PARSERS.put("google.protobuf.Any", Any.parser()); + PARSERS.put("google.protobuf.Struct", Struct.parser()); + PARSERS.put("google.protobuf.Value", com.google.protobuf.Value.parser()); + PARSERS.put("google.protobuf.ListValue", ListValue.parser()); + } + + private ProtobufCopies() {} + + static @Nullable Message copyIfSpecial(ValidateMessage message) { + Parser parser = PARSERS.get(message.getDescriptorForType().getFullName()); + if (parser == null) { + return null; + } + // The message's descriptor may not be the generated class's, so copy through the wire form. + try { + return parser.parseFrom(copy(message).toByteString()); + } catch (InvalidProtocolBufferException e) { + throw new IllegalStateException(e); + } + } + + private static DynamicMessage copy(ValidateMessage message) { + Descriptor descriptor = message.getDescriptorForType(); + DynamicMessage.Builder builder = DynamicMessage.newBuilder(descriptor); + for (FieldDescriptor field : descriptor.getFields()) { + if (!message.hasField(field)) { + continue; + } + Value value = ValidateMessages.field(message, field); + if (field.isMapField()) { + Descriptor entryType = field.getMessageType(); + FieldDescriptor keyField = entryType.findFieldByNumber(1); + FieldDescriptor valueField = entryType.findFieldByNumber(2); + for (Map.Entry entry : value.mapValue().entrySet()) { + builder.addRepeatedField( + field, + DynamicMessage.newBuilder(entryType) + .setField(keyField, entry.getKey().rawValue()) + .setField(valueField, element(valueField, entry.getValue())) + .build()); + } + } else if (field.isRepeated()) { + for (Value element : value.repeatedValue()) { + builder.addRepeatedField(field, element(field, element)); + } + } else { + builder.setField(field, element(field, value)); + } + } + return builder.build(); + } + + private static Object element(FieldDescriptor field, Value value) { + switch (field.getJavaType()) { + case MESSAGE: + ValidateMessage message = value.messageValue(); + return message == null + ? DynamicMessage.getDefaultInstance(field.getMessageType()) + : copy(message); + case ENUM: + Object number = value.rawValue(); + return number instanceof EnumValueDescriptor + ? number + : field.getEnumType().findValueByNumberCreatingIfUnknown((Integer) number); + default: + return value.rawValue(); + } + } +} diff --git a/src/main/java/build/buf/protovalidate/ValidateMessages.java b/src/main/java/build/buf/protovalidate/ValidateMessages.java index 4e7576039..2fe8e1c3e 100644 --- a/src/main/java/build/buf/protovalidate/ValidateMessages.java +++ b/src/main/java/build/buf/protovalidate/ValidateMessages.java @@ -62,7 +62,8 @@ static Object cel(ValidateMessage message) { if (isWrapper(descriptor)) { return field(message, requiredField(descriptor, "value")).celValue(); } - return new ValidateMessageStruct(message); + Object copy = ProtobufCopies.copyIfSpecial(message); + return copy != null ? copy : new ValidateMessageStruct(message); } static boolean isWrapper(Descriptor descriptor) { diff --git a/src/test/java/build/buf/protovalidate/MapValidateMessage.java b/src/test/java/build/buf/protovalidate/MapValidateMessage.java new file mode 100644 index 000000000..c4abee8db --- /dev/null +++ b/src/test/java/build/buf/protovalidate/MapValidateMessage.java @@ -0,0 +1,101 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.EnumValueDescriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Message; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.jspecify.annotations.Nullable; + +final class MapValidateMessage implements ValidateMessage { + private final Descriptor descriptor; + private final Map fields; + + MapValidateMessage(Descriptor descriptor, Map fields) { + this.descriptor = descriptor; + this.fields = fields; + } + + // Lets a test validate the same contents as a protobuf-java message and as plain values. + static MapValidateMessage copyOf(Message message) { + Map fields = new HashMap<>(); + for (Map.Entry entry : message.getAllFields().entrySet()) { + fields.put(entry.getKey(), plain(entry.getKey(), entry.getValue())); + } + return new MapValidateMessage(message.getDescriptorForType(), fields); + } + + private static Object plain(FieldDescriptor field, Object value) { + if (field.isMapField()) { + FieldDescriptor keyField = field.getMessageType().findFieldByNumber(1); + FieldDescriptor valueField = field.getMessageType().findFieldByNumber(2); + Map map = new HashMap<>(); + for (Object entry : (List) value) { + Message entryMessage = (Message) entry; + map.put( + element(entryMessage.getField(keyField)), element(entryMessage.getField(valueField))); + } + return map; + } + if (field.isRepeated()) { + List list = new ArrayList<>(); + for (Object element : (List) value) { + list.add(element(element)); + } + return list; + } + return element(value); + } + + private static Object element(Object value) { + if (value instanceof Message) { + return copyOf((Message) value); + } + if (value instanceof EnumValueDescriptor) { + return ((EnumValueDescriptor) value).getNumber(); + } + return value; + } + + @Override + public Descriptor getDescriptorForType() { + return descriptor; + } + + @Override + public boolean hasField(FieldDescriptor field) { + Object value = fields.get(field); + if (value instanceof Map) { + return !((Map) value).isEmpty(); + } + if (value instanceof List) { + return !((List) value).isEmpty(); + } + if (value == null || value instanceof ValidateMessage || field.hasPresence()) { + return value != null; + } + return !value.equals(field.getDefaultValue()); + } + + @Override + public @Nullable Object getField(FieldDescriptor field) { + return fields.get(field); + } +} diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java index 310ec800d..b5bdbd1d6 100644 --- a/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java +++ b/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java @@ -32,10 +32,8 @@ import com.google.protobuf.DynamicMessage; import java.util.Collections; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import org.jspecify.annotations.Nullable; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -303,39 +301,4 @@ private static FieldDescriptorProto.Builder innerField(String name, int number) return field(name, number, FieldDescriptorProto.Type.TYPE_MESSAGE) .setTypeName(".test.v1.Inner"); } - - private static final class MapValidateMessage implements ValidateMessage { - private final Descriptor descriptor; - private final Map fields; - - MapValidateMessage(Descriptor descriptor, Map fields) { - this.descriptor = descriptor; - this.fields = fields; - } - - @Override - public Descriptor getDescriptorForType() { - return descriptor; - } - - @Override - public boolean hasField(FieldDescriptor field) { - Object value = fields.get(field); - if (value instanceof Map) { - return !((Map) value).isEmpty(); - } - if (value instanceof List) { - return !((List) value).isEmpty(); - } - if (value instanceof ValidateMessage) { - return true; - } - return value != null && !value.equals(field.getDefaultValue()); - } - - @Override - public @Nullable Object getField(FieldDescriptor field) { - return fields.get(field); - } - } } diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageWellKnownTypesTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageWellKnownTypesTest.java new file mode 100644 index 000000000..73a1fa355 --- /dev/null +++ b/src/test/java/build/buf/protovalidate/ValidateMessageWellKnownTypesTest.java @@ -0,0 +1,289 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import static org.assertj.core.api.Assertions.assertThat; + +import build.buf.validate.AnyRules; +import build.buf.validate.FieldMaskRules; +import build.buf.validate.FieldRules; +import build.buf.validate.MessageRules; +import build.buf.validate.Rule; +import build.buf.validate.ValidateProto; +import com.google.protobuf.Any; +import com.google.protobuf.AnyProto; +import com.google.protobuf.DescriptorProtos.DescriptorProto; +import com.google.protobuf.DescriptorProtos.FieldDescriptorProto; +import com.google.protobuf.DescriptorProtos.FieldOptions; +import com.google.protobuf.DescriptorProtos.FileDescriptorProto; +import com.google.protobuf.DescriptorProtos.MessageOptions; +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FileDescriptor; +import com.google.protobuf.Duration; +import com.google.protobuf.DynamicMessage; +import com.google.protobuf.FieldMask; +import com.google.protobuf.FieldMaskProto; +import com.google.protobuf.ListValue; +import com.google.protobuf.Message; +import com.google.protobuf.NullValue; +import com.google.protobuf.Struct; +import com.google.protobuf.StructProto; +import com.google.protobuf.Value; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +/** Well-known types that CEL treats specially, nested in a {@link ValidateMessage}. */ +public class ValidateMessageWellKnownTypesTest { + private static final Any ANY = Any.pack(Duration.newBuilder().setSeconds(1).build()); + private static final Struct STRUCT = + Struct.newBuilder() + .putFields("k", number(1)) + .putFields("name", string("x")) + .putFields( + "nested", + Value.newBuilder() + .setStructValue( + Struct.newBuilder() + .putFields("a", Value.newBuilder().setBoolValue(true).build())) + .build()) + .putFields( + "list", + Value.newBuilder() + .setListValue(ListValue.newBuilder().addValues(number(1)).addValues(string("b"))) + .build()) + .build(); + + // Each expression is true for the test data. + @ParameterizedTest(name = "{0}") + @ValueSource( + strings = { + "this.any == duration('1s')", + "has(this.any)", + "this.s['k'] == 1.0", + "this.s.name == 'x'", + "this.s.nested.a == true", + "this.s.list[1] == 'b'", + "'k' in this.s", + "size(this.s) == 4", + "has(this.s.k)", + "this.s == {'k': 1.0, 'name': 'x', 'nested': {'a': true}, 'list': [1.0, 'b']}", + "this.v == 'hello'", + "this.v_null == null", + "this.v_unset == null", + "this.vs == [1.0, 'z']", + "this.vmap['q'] == true", + "this.lv[0] == 'a'", + "size(this.lv) == 2", + "this.lv == ['a', 2.0]", + "this.fm.paths == ['a.b', 'c']", + "'c' in this.fm.paths", + }) + public void celMatchesProtobufJava(String expression) { + Rule rule = + Rule.newBuilder().setId("rule").setMessage("rule").setExpression(expression).build(); + Descriptor outer = + buildOuter( + MessageOptions.newBuilder() + .setExtension(ValidateProto.message, MessageRules.newBuilder().addCel(rule).build()) + .build(), + FieldRules.getDefaultInstance(), + FieldRules.getDefaultInstance()); + Message message = outerMessage(outer); + Validator validator = ValidatorFactory.newBuilder().build(); + + String protobuf = outcome(validator, message); + String plain = outcome(validator, MapValidateMessage.copyOf(message)); + + assertThat(protobuf).as("protobuf-java").isEqualTo("[]"); + assertThat(plain).as("ValidateMessage").isEqualTo(protobuf); + } + + private static Stream standardRules() { + String duration = ANY.getTypeUrl(); + String other = "type.googleapis.com/google.protobuf.Timestamp"; + return Stream.of( + Arguments.of(anyRules(AnyRules.newBuilder().addIn(duration)), "[]"), + Arguments.of(anyRules(AnyRules.newBuilder().addIn(other)), "[any.in]"), + Arguments.of(anyRules(AnyRules.newBuilder().addNotIn(duration)), "[any.not_in]"), + Arguments.of(maskRules(FieldMaskRules.newBuilder().addIn("a").addIn("c")), "[]"), + Arguments.of(maskRules(FieldMaskRules.newBuilder().addIn("c")), "[field_mask.in]"), + Arguments.of( + maskRules(FieldMaskRules.newBuilder().addNotIn("a")), "[field_mask.not_in]"), + Arguments.of( + maskRules( + FieldMaskRules.newBuilder() + .setConst(FieldMask.newBuilder().addPaths("a.b").addPaths("c"))), + "[]"), + Arguments.of( + maskRules( + FieldMaskRules.newBuilder().setConst(FieldMask.newBuilder().addPaths("c"))), + "[field_mask.const]")) + .flatMap(args -> + Stream.of(true, false) + .map(nativeRules -> Arguments.of(args.get()[0], args.get()[1], nativeRules))); + } + + @ParameterizedTest(name = "{0} nativeRules={2}") + @MethodSource("standardRules") + public void standardRulesMatchProtobufJava( + FieldRules rules, String expected, boolean nativeRules) { + boolean any = rules.hasAny(); + Descriptor outer = + buildOuter( + MessageOptions.getDefaultInstance(), + any ? rules : FieldRules.getDefaultInstance(), + any ? FieldRules.getDefaultInstance() : rules); + Message message = outerMessage(outer); + Validator validator = + ValidatorFactory.newBuilder() + .withConfig(Config.newBuilder().setEnableNativeRules(nativeRules).build()) + .build(); + + String protobuf = outcome(validator, message); + String plain = outcome(validator, MapValidateMessage.copyOf(message)); + + assertThat(protobuf).as("protobuf-java").isEqualTo(expected); + assertThat(plain).as("ValidateMessage").isEqualTo(protobuf); + } + + private static FieldRules anyRules(AnyRules.Builder rules) { + return FieldRules.newBuilder().setAny(rules).build(); + } + + private static FieldRules maskRules(FieldMaskRules.Builder rules) { + return FieldRules.newBuilder().setFieldMask(rules).build(); + } + + private static String outcome(Validator validator, Object message) { + try { + ValidationResult result = + message instanceof ValidateMessage + ? validator.validate((ValidateMessage) message) + : validator.validate((Message) message); + return result.getViolations().stream() + .map(violation -> violation.toProto().getRuleId()) + .sorted() + .collect(Collectors.toList()) + .toString(); + } catch (Exception e) { + return e.toString(); + } + } + + private static Message outerMessage(Descriptor outer) { + DynamicMessage.Builder builder = DynamicMessage.newBuilder(outer); + set(builder, "any", ANY); + set(builder, "s", STRUCT); + set(builder, "v", string("hello")); + set(builder, "v_null", Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build()); + set(builder, "lv", ListValue.newBuilder().addValues(string("a")).addValues(number(2)).build()); + set(builder, "fm", FieldMask.newBuilder().addPaths("a.b").addPaths("c").build()); + builder.addRepeatedField(outer.findFieldByName("vs"), number(1)); + builder.addRepeatedField(outer.findFieldByName("vs"), string("z")); + Descriptor entry = outer.findFieldByName("vmap").getMessageType(); + builder.addRepeatedField( + outer.findFieldByName("vmap"), + DynamicMessage.newBuilder(entry) + .setField(entry.findFieldByName("key"), "q") + .setField(entry.findFieldByName("value"), Value.newBuilder().setBoolValue(true).build()) + .build()); + return builder.build(); + } + + private static void set(DynamicMessage.Builder builder, String name, Message value) { + builder.setField(builder.getDescriptorForType().findFieldByName(name), value); + } + + private static Value number(double value) { + return Value.newBuilder().setNumberValue(value).build(); + } + + private static Value string(String value) { + return Value.newBuilder().setStringValue(value).build(); + } + + private static Descriptor buildOuter( + MessageOptions options, FieldRules anyRules, FieldRules maskRules) { + DescriptorProto entry = + DescriptorProto.newBuilder() + .setName("VmapEntry") + .setOptions(MessageOptions.newBuilder().setMapEntry(true)) + .addField( + FieldDescriptorProto.newBuilder() + .setName("key") + .setNumber(1) + .setType(FieldDescriptorProto.Type.TYPE_STRING)) + .addField(messageField("value", 2, "Value")) + .build(); + DescriptorProto outer = + DescriptorProto.newBuilder() + .setName("Outer") + .setOptions(options) + .addNestedType(entry) + .addField(messageField("any", 1, "Any").setOptions(fieldOptions(anyRules))) + .addField(messageField("s", 2, "Struct")) + .addField(messageField("v", 3, "Value")) + .addField(messageField("v_null", 4, "Value")) + .addField(messageField("v_unset", 5, "Value")) + .addField(messageField("lv", 6, "ListValue")) + .addField(messageField("fm", 7, "FieldMask").setOptions(fieldOptions(maskRules))) + .addField( + messageField("vs", 8, "Value").setLabel(FieldDescriptorProto.Label.LABEL_REPEATED)) + .addField( + FieldDescriptorProto.newBuilder() + .setName("vmap") + .setNumber(9) + .setLabel(FieldDescriptorProto.Label.LABEL_REPEATED) + .setType(FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".test.v1.Outer.VmapEntry")) + .build(); + FileDescriptor[] dependencies = { + ValidateProto.getDescriptor(), + AnyProto.getDescriptor(), + StructProto.getDescriptor(), + FieldMaskProto.getDescriptor() + }; + FileDescriptorProto.Builder file = + FileDescriptorProto.newBuilder() + .setName("well_known.proto") + .setPackage("test.v1") + .setSyntax("proto3") + .addMessageType(outer); + for (FileDescriptor dependency : dependencies) { + file.addDependency(dependency.getName()); + } + try { + return FileDescriptor.buildFrom(file.build(), dependencies).findMessageTypeByName("Outer"); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private static FieldDescriptorProto.Builder messageField(String name, int number, String type) { + return FieldDescriptorProto.newBuilder() + .setName(name) + .setNumber(number) + .setType(FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".google.protobuf." + type); + } + + private static FieldOptions fieldOptions(FieldRules rules) { + return FieldOptions.newBuilder().setExtension(ValidateProto.field, rules).build(); + } +} From 1a36b3c84a108f63eaeaee89f713a90680b9ef3c Mon Sep 17 00:00:00 2001 From: Jon Bodner Date: Thu, 3 Dec 2026 14:53:58 -0500 Subject: [PATCH 15/23] Match protobuf-java for defaults, violation values and errors 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. --- .../buf/protovalidate/MapRulesEvaluator.java | 4 +- .../build/buf/protovalidate/ObjectValue.java | 5 +- .../build/buf/protovalidate/PlainValue.java | 39 ++- .../protovalidate/ValidateMessageStruct.java | 14 +- .../buf/protovalidate/ValidatorImpl.java | 16 +- .../buf/protovalidate/MapValidateMessage.java | 3 +- .../ValidateMessageCelCollectionTest.java | 24 ++ .../ValidateMessageDefaultsTest.java | 240 ++++++++++++++++++ .../ValidateMessageRulesTest.java | 189 ++++++++++++++ .../protovalidate/ValidateMessageTest.java | 3 +- 10 files changed, 514 insertions(+), 23 deletions(-) create mode 100644 src/test/java/build/buf/protovalidate/ValidateMessageDefaultsTest.java create mode 100644 src/test/java/build/buf/protovalidate/ValidateMessageRulesTest.java diff --git a/src/main/java/build/buf/protovalidate/MapRulesEvaluator.java b/src/main/java/build/buf/protovalidate/MapRulesEvaluator.java index fea8bccda..2e7bc64da 100644 --- a/src/main/java/build/buf/protovalidate/MapRulesEvaluator.java +++ b/src/main/java/build/buf/protovalidate/MapRulesEvaluator.java @@ -97,8 +97,8 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) { - // Java protobuf returns map fields as a List of synthetic key/value entry messages; the size - // is the pair count. + // protobuf-java returns map fields as a List of key/value entry messages, and other runtimes + // return a Map; either way the size is the pair count. Object entries = val.rawValue(); long size = entries instanceof Map ? ((Map) entries).size() : ((List) entries).size(); List violations = null; diff --git a/src/main/java/build/buf/protovalidate/ObjectValue.java b/src/main/java/build/buf/protovalidate/ObjectValue.java index 5042f230c..01abe5e5e 100644 --- a/src/main/java/build/buf/protovalidate/ObjectValue.java +++ b/src/main/java/build/buf/protovalidate/ObjectValue.java @@ -19,7 +19,7 @@ import com.google.protobuf.Message; import java.util.ArrayList; import java.util.Collections; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.jspecify.annotations.Nullable; @@ -103,7 +103,8 @@ public Map mapValue() { Descriptors.FieldDescriptor keyDesc = fieldDescriptor.getMessageType().findFieldByNumber(1); Descriptors.FieldDescriptor valDesc = fieldDescriptor.getMessageType().findFieldByNumber(2); - Map out = new HashMap<>(input.size()); + // Keeps the entries' order, so violations come out in the same order on every run. + Map out = new LinkedHashMap<>(input.size()); for (AbstractMessage entry : input) { Object keyValue = entry.getField(keyDesc); Value keyJavaValue = new ObjectValue(keyDesc, keyValue); diff --git a/src/main/java/build/buf/protovalidate/PlainValue.java b/src/main/java/build/buf/protovalidate/PlainValue.java index f8df407d1..7044666d9 100644 --- a/src/main/java/build/buf/protovalidate/PlainValue.java +++ b/src/main/java/build/buf/protovalidate/PlainValue.java @@ -21,6 +21,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.jspecify.annotations.Nullable; @@ -104,7 +105,7 @@ public FieldDescriptor fieldDescriptor() { @Override public Object rawValue() { if (isList()) { - return list(); + return field.getJavaType() == JavaType.ENUM ? enumNumbers() : list(); } if (isMap()) { return map(); @@ -134,7 +135,8 @@ public Map mapValue() { } FieldDescriptor keyField = field.getMessageType().findFieldByNumber(1); FieldDescriptor valueField = field.getMessageType().findFieldByNumber(2); - Map out = new HashMap<>(); + // Keeps the caller's order, so violations come out in the same order on every run. + Map out = new LinkedHashMap<>(); for (Map.Entry entry : map().entrySet()) { out.put( new PlainValue(keyField, entry.getKey(), false), @@ -182,6 +184,14 @@ public T jvmValue(Class clazz) { return clazz.cast(out); } if (isMessage()) { + // ObjectValue reports singular protobuf-java Timestamp and Duration fields as java.time + // values, and ListElementValue reports list elements as messages. + String type = field.getMessageType().getFullName(); + if (!element + && (type.equals("google.protobuf.Timestamp") + || type.equals("google.protobuf.Duration"))) { + return clazz.cast(ValidateMessages.cel(message())); + } return clazz.cast(message()); } return clazz.cast(scalarCel()); @@ -203,6 +213,16 @@ private List list() { return value == null ? Collections.emptyList() : (List) value; } + // Enum elements may be Integers or EnumValueDescriptors, so rules such as repeated.unique + // compare them by number. + private List enumNumbers() { + List out = new ArrayList<>(); + for (Value item : repeatedValue()) { + out.add(item.rawValue()); + } + return out; + } + private Map map() { return value == null ? Collections.emptyMap() : (Map) value; } @@ -216,17 +236,12 @@ private ValidateMessage message() { private Object scalar() { if (field.getJavaType() == JavaType.ENUM) { - if (value == null) { - return field.getEnumType().getValues().get(0).getNumber(); - } - return value instanceof EnumValueDescriptor - ? ((EnumValueDescriptor) value).getNumber() - : value; - } - if (value != null) { - return value; + Object number = value == null ? field.getDefaultValue() : value; + return number instanceof EnumValueDescriptor + ? ((EnumValueDescriptor) number).getNumber() + : number; } - return field.getJavaType() == JavaType.BYTE_STRING ? ByteString.EMPTY : field.getDefaultValue(); + return value != null ? value : field.getDefaultValue(); } private Object scalarCel() { diff --git a/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java b/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java index bb54a3300..cbc8f63d4 100644 --- a/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java +++ b/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java @@ -81,15 +81,23 @@ public Optional find(String fieldName) { @Override public boolean equals(@Nullable Object other) { ValidateMessageStruct that = asStruct(other); - if (that == null || !descriptor.getFullName().equals(that.descriptor.getFullName())) { + if (that == null + || !descriptor.getFullName().equals(that.descriptor.getFullName()) + || descriptor.getFields().size() != that.descriptor.getFields().size()) { return false; } for (FieldDescriptor field : descriptor.getFields()) { + // The other message may use a different descriptor instance for the same type, and + // protobuf-java rejects a FieldDescriptor from another instance. + FieldDescriptor thatField = that.descriptor.findFieldByNumber(field.getNumber()); + if (thatField == null) { + return false; + } boolean present = message.hasField(field); - if (present != that.message.hasField(field)) { + if (present != that.message.hasField(thatField)) { return false; } - if (present && !celEquals(select(field.getName()), that.select(field.getName()))) { + if (present && !celEquals(select(field.getName()), that.select(thatField.getName()))) { return false; } } diff --git a/src/main/java/build/buf/protovalidate/ValidatorImpl.java b/src/main/java/build/buf/protovalidate/ValidatorImpl.java index 8c0f408ae..4bc4f521b 100644 --- a/src/main/java/build/buf/protovalidate/ValidatorImpl.java +++ b/src/main/java/build/buf/protovalidate/ValidatorImpl.java @@ -15,6 +15,7 @@ package build.buf.protovalidate; import build.buf.protovalidate.exceptions.CompilationException; +import build.buf.protovalidate.exceptions.ExecutionException; import build.buf.protovalidate.exceptions.ValidationException; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Message; @@ -57,8 +58,19 @@ public ValidationResult validate(ValidateMessage message) throws ValidationExcep return ValidationResult.EMPTY; } Evaluator evaluator = evaluatorBuilder.load(message.getDescriptorForType()); - List result = - evaluator.evaluate(new ValidateMessageValue(message), this.failFast); + List result; + try { + result = evaluator.evaluate(new ValidateMessageValue(message), this.failFast); + } catch (IllegalArgumentException e) { + // A CEL rule that reads a field of the wrong type already reports it as an + // ExecutionException, so a native rule that reads it first does the same. + if (message instanceof ProtobufValidateMessage) { + throw e; + } + ExecutionException wrapped = new ExecutionException(String.valueOf(e.getMessage())); + wrapped.initCause(e); + throw wrapped; + } if (result.isEmpty()) { return ValidationResult.EMPTY; } diff --git a/src/test/java/build/buf/protovalidate/MapValidateMessage.java b/src/test/java/build/buf/protovalidate/MapValidateMessage.java index c4abee8db..68312434a 100644 --- a/src/test/java/build/buf/protovalidate/MapValidateMessage.java +++ b/src/test/java/build/buf/protovalidate/MapValidateMessage.java @@ -20,6 +20,7 @@ import com.google.protobuf.Message; import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.jspecify.annotations.Nullable; @@ -46,7 +47,7 @@ private static Object plain(FieldDescriptor field, Object value) { if (field.isMapField()) { FieldDescriptor keyField = field.getMessageType().findFieldByNumber(1); FieldDescriptor valueField = field.getMessageType().findFieldByNumber(2); - Map map = new HashMap<>(); + Map map = new LinkedHashMap<>(); for (Object entry : (List) value) { Message entryMessage = (Message) entry; map.put( diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java index b5bdbd1d6..f6234fe49 100644 --- a/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java +++ b/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java @@ -34,6 +34,7 @@ import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -100,6 +101,29 @@ public void readsUnsignedListElements(String expression) { assertThat(outcome(plainOuter(buildOuterDescriptor(expression)))).isEqualTo("[]"); } + // Each call builds new descriptor instances, as a runtime with its own descriptors has. + @Test + public void structEqualsMessageWithAnotherDescriptorInstance() { + Descriptor plainInner = buildOuterDescriptor("true").getFile().findMessageTypeByName("Inner"); + Descriptor protobufInner = + buildOuterDescriptor("true").getFile().findMessageTypeByName("Inner"); + ValidateMessageStruct struct = + new ValidateMessageStruct( + new MapValidateMessage( + plainInner, Collections.singletonMap(plainInner.findFieldByName("name"), "alice"))); + + assertThat(struct) + .isEqualTo( + DynamicMessage.newBuilder(protobufInner) + .setField(protobufInner.findFieldByName("name"), "alice") + .build()); + assertThat(struct) + .isNotEqualTo( + DynamicMessage.newBuilder(protobufInner) + .setField(protobufInner.findFieldByName("name"), "bob") + .build()); + } + private String outcome(Object message) { try { ValidationResult result = diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageDefaultsTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageDefaultsTest.java new file mode 100644 index 000000000..ccf3ade7a --- /dev/null +++ b/src/test/java/build/buf/protovalidate/ValidateMessageDefaultsTest.java @@ -0,0 +1,240 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import static org.assertj.core.api.Assertions.assertThat; + +import build.buf.validate.DurationRules; +import build.buf.validate.FieldRules; +import build.buf.validate.MessageRules; +import build.buf.validate.RepeatedRules; +import build.buf.validate.Rule; +import build.buf.validate.TimestampRules; +import build.buf.validate.ValidateProto; +import com.google.protobuf.DescriptorProtos.DescriptorProto; +import com.google.protobuf.DescriptorProtos.EnumDescriptorProto; +import com.google.protobuf.DescriptorProtos.EnumValueDescriptorProto; +import com.google.protobuf.DescriptorProtos.FieldDescriptorProto; +import com.google.protobuf.DescriptorProtos.FieldOptions; +import com.google.protobuf.DescriptorProtos.FileDescriptorProto; +import com.google.protobuf.DescriptorProtos.MessageOptions; +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FileDescriptor; +import com.google.protobuf.Duration; +import com.google.protobuf.DurationProto; +import com.google.protobuf.DynamicMessage; +import com.google.protobuf.Message; +import com.google.protobuf.Timestamp; +import com.google.protobuf.TimestampProto; +import java.util.List; +import java.util.stream.Collectors; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** Unset fields with explicit defaults, and violation values, for a {@link ValidateMessage}. */ +public class ValidateMessageDefaultsTest { + private static final FieldRules NO_RULES = FieldRules.getDefaultInstance(); + + // Each expression is true for a message with every field unset. + @ParameterizedTest(name = "{0}") + @ValueSource( + strings = { + "this.e == 2", + "this.e_implicit == 1", + "this.b == b'abc'", + "this.s == 'xyz'", + "this.i == 7", + }) + public void unsetFieldsReadExplicitDefaults(String expression) { + Rule rule = + Rule.newBuilder().setId("rule").setMessage("rule").setExpression(expression).build(); + Descriptor descriptor = + build( + MessageOptions.newBuilder() + .setExtension(ValidateProto.message, MessageRules.newBuilder().addCel(rule).build()) + .build(), + NO_RULES, + NO_RULES); + Message message = DynamicMessage.getDefaultInstance(descriptor); + + assertThat(violations(true, message)).isEmpty(); + for (boolean nativeRules : new boolean[] {true, false}) { + assertThat(violations(nativeRules, MapValidateMessage.copyOf(message))) + .isEqualTo(violations(nativeRules, message)); + } + } + + // Violations report protobuf-java Timestamp and Duration values as java.time values. + @ParameterizedTest(name = "nativeRules={0}") + @ValueSource(booleans = {true, false}) + public void violationValuesMatchProtobufJava(boolean nativeRules) { + Descriptor descriptor = + build( + MessageOptions.getDefaultInstance(), + FieldRules.newBuilder() + .setTimestamp( + TimestampRules.newBuilder().setGt(Timestamp.newBuilder().setSeconds(100))) + .build(), + FieldRules.newBuilder() + .setDuration( + DurationRules.newBuilder().setGt(Duration.newBuilder().setSeconds(100))) + .build()); + Message message = + DynamicMessage.newBuilder(descriptor) + .setField( + descriptor.findFieldByName("ts"), Timestamp.newBuilder().setSeconds(1).build()) + .setField(descriptor.findFieldByName("d"), Duration.newBuilder().setSeconds(1).build()) + .build(); + + List protobuf = violations(nativeRules, message); + + assertThat(protobuf) + .containsExactly("duration.gt=Duration:PT1S", "timestamp.gt=Instant:1970-01-01T00:00:01Z"); + assertThat(violations(nativeRules, MapValidateMessage.copyOf(message))).isEqualTo(protobuf); + } + + // List elements are reported as each runtime's own message, as protobuf-java reports them. + @ParameterizedTest(name = "nativeRules={0}") + @ValueSource(booleans = {true, false}) + public void listElementViolationValuesAreMessages(boolean nativeRules) throws Exception { + Descriptor descriptor = build(MessageOptions.getDefaultInstance(), NO_RULES, NO_RULES); + Message message = + DynamicMessage.newBuilder(descriptor) + .addRepeatedField( + descriptor.findFieldByName("tss"), Timestamp.newBuilder().setSeconds(1).build()) + .build(); + Validator validator = + ValidatorFactory.newBuilder() + .withConfig(Config.newBuilder().setEnableNativeRules(nativeRules).build()) + .build(); + + Object protobuf = validator.validate(message).getViolations().get(0).getFieldValue().getValue(); + Object plain = + validator + .validate(MapValidateMessage.copyOf(message)) + .getViolations() + .get(0) + .getFieldValue() + .getValue(); + + assertThat(protobuf).isInstanceOf(Timestamp.class); + assertThat(plain).isInstanceOf(ValidateMessage.class); + } + + private static List violations(boolean nativeRules, Object message) { + Validator validator = + ValidatorFactory.newBuilder() + .withConfig(Config.newBuilder().setEnableNativeRules(nativeRules).build()) + .build(); + try { + ValidationResult result = + message instanceof ValidateMessage + ? validator.validate((ValidateMessage) message) + : validator.validate((Message) message); + return result.getViolations().stream() + .map(violation -> { + Object value = violation.getFieldValue().getValue(); + return violation.toProto().getRuleId() + + "=" + + (value == null ? "null" : value.getClass().getSimpleName() + ":" + value); + }) + .sorted() + .collect(Collectors.toList()); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private static Descriptor build( + MessageOptions options, FieldRules timestampRules, FieldRules durationRules) { + EnumDescriptorProto enumType = + EnumDescriptorProto.newBuilder() + .setName("E") + .addValue(EnumValueDescriptorProto.newBuilder().setName("E_ONE").setNumber(1)) + .addValue(EnumValueDescriptorProto.newBuilder().setName("E_TWO").setNumber(2)) + .build(); + DescriptorProto message = + DescriptorProto.newBuilder() + .setName("Defaults") + .setOptions(options) + .addField( + field("e", 1, FieldDescriptorProto.Type.TYPE_ENUM) + .setTypeName(".test.v1.E") + .setDefaultValue("E_TWO")) + .addField( + field("e_implicit", 2, FieldDescriptorProto.Type.TYPE_ENUM) + .setTypeName(".test.v1.E")) + .addField(field("b", 3, FieldDescriptorProto.Type.TYPE_BYTES).setDefaultValue("abc")) + .addField(field("s", 4, FieldDescriptorProto.Type.TYPE_STRING).setDefaultValue("xyz")) + .addField(field("i", 5, FieldDescriptorProto.Type.TYPE_INT32).setDefaultValue("7")) + .addField( + field("ts", 6, FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".google.protobuf.Timestamp") + .setOptions(rules(timestampRules))) + .addField( + field("d", 7, FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".google.protobuf.Duration") + .setOptions(rules(durationRules))) + .addField( + field("tss", 8, FieldDescriptorProto.Type.TYPE_MESSAGE) + .setLabel(FieldDescriptorProto.Label.LABEL_REPEATED) + .setTypeName(".google.protobuf.Timestamp") + .setOptions( + rules( + FieldRules.newBuilder() + .setRepeated( + RepeatedRules.newBuilder() + .setItems( + FieldRules.newBuilder() + .setTimestamp( + TimestampRules.newBuilder() + .setGt( + Timestamp.newBuilder() + .setSeconds(100))))) + .build()))) + .build(); + FileDescriptor[] dependencies = { + ValidateProto.getDescriptor(), TimestampProto.getDescriptor(), DurationProto.getDescriptor() + }; + FileDescriptorProto.Builder file = + FileDescriptorProto.newBuilder() + .setName("defaults.proto") + .setPackage("test.v1") + .setSyntax("proto2") + .addEnumType(enumType) + .addMessageType(message); + for (FileDescriptor dependency : dependencies) { + file.addDependency(dependency.getName()); + } + try { + return FileDescriptor.buildFrom(file.build(), dependencies).findMessageTypeByName("Defaults"); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private static FieldDescriptorProto.Builder field( + String name, int number, FieldDescriptorProto.Type type) { + return FieldDescriptorProto.newBuilder() + .setName(name) + .setNumber(number) + .setType(type) + .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL); + } + + private static FieldOptions rules(FieldRules rules) { + return FieldOptions.newBuilder().setExtension(ValidateProto.field, rules).build(); + } +} diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageRulesTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageRulesTest.java new file mode 100644 index 000000000..676578b8e --- /dev/null +++ b/src/test/java/build/buf/protovalidate/ValidateMessageRulesTest.java @@ -0,0 +1,189 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import build.buf.protovalidate.exceptions.ValidationException; +import build.buf.validate.FieldRules; +import build.buf.validate.Int32Rules; +import build.buf.validate.MapRules; +import build.buf.validate.RepeatedRules; +import build.buf.validate.StringRules; +import build.buf.validate.ValidateProto; +import com.google.protobuf.DescriptorProtos.DescriptorProto; +import com.google.protobuf.DescriptorProtos.EnumDescriptorProto; +import com.google.protobuf.DescriptorProtos.EnumValueDescriptorProto; +import com.google.protobuf.DescriptorProtos.FieldDescriptorProto; +import com.google.protobuf.DescriptorProtos.FieldOptions; +import com.google.protobuf.DescriptorProtos.FileDescriptorProto; +import com.google.protobuf.DescriptorProtos.MessageOptions; +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Descriptors.FileDescriptor; +import com.google.protobuf.DynamicMessage; +import com.google.protobuf.Message; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** Native and standard rules over {@link ValidateMessage} values. */ +public class ValidateMessageRulesTest { + private static final Descriptor RULES = buildRulesDescriptor(); + private static final FieldDescriptor NUMBER = RULES.findFieldByName("number"); + private static final FieldDescriptor LABELS = RULES.findFieldByName("labels"); + private static final FieldDescriptor KINDS = RULES.findFieldByName("kinds"); + + // A native rule can read the wrong type before any CEL rule does, so CEL can't wrap the error. + @ParameterizedTest(name = "nativeRules={0}") + @ValueSource(booleans = {true, false}) + public void wrongValueTypeThrowsValidationException(boolean nativeRules) { + ValidateMessage message = new MapValidateMessage(RULES, Collections.singletonMap(NUMBER, 1L)); + + assertThatThrownBy(() -> validator(nativeRules).validate(message)) + .isInstanceOf(ValidationException.class) + .hasMessageContaining("field \"test.v1.Rules.number\" must be of type Integer"); + } + + // Violations follow the map's order, so they come out the same on every run. + @ParameterizedTest(name = "nativeRules={0}") + @ValueSource(booleans = {true, false}) + public void mapViolationsFollowMapOrder(boolean nativeRules) throws Exception { + List keys = new ArrayList<>(); + DynamicMessage.Builder builder = DynamicMessage.newBuilder(RULES); + Descriptor entryType = LABELS.getMessageType(); + for (int i = 0; i < 20; i++) { + String key = String.format("k%02d", i); + keys.add(key); + builder.addRepeatedField( + LABELS, + DynamicMessage.newBuilder(entryType) + .setField(entryType.findFieldByName("key"), key) + .setField(entryType.findFieldByName("value"), "x") + .build()); + } + Message message = builder.build(); + Validator validator = validator(nativeRules); + + assertThat(violatedKeys(validator.validate(message))).isEqualTo(keys); + assertThat(violatedKeys(validator.validate(MapValidateMessage.copyOf(message)))) + .isEqualTo(keys); + } + + // A list may hold an enum number as an Integer or an EnumValueDescriptor. + @ParameterizedTest(name = "nativeRules={0}") + @ValueSource(booleans = {true, false}) + public void uniqueComparesEnumsByNumber(boolean nativeRules) throws Exception { + Object one = 1; + Object oneDescriptor = KINDS.getEnumType().findValueByNumber(1); + ValidateMessage message = + new MapValidateMessage( + RULES, Collections.singletonMap(KINDS, Arrays.asList(one, oneDescriptor))); + + ValidationResult result = validator(nativeRules).validate(message); + + assertThat(result.getViolations()) + .extracting(violation -> violation.toProto().getRuleId()) + .containsExactly("repeated.unique"); + } + + private static List violatedKeys(ValidationResult result) { + return result.getViolations().stream() + .map(violation -> violation.toProto().getField().getElements(0).getStringKey()) + .collect(Collectors.toList()); + } + + private static Validator validator(boolean nativeRules) { + return ValidatorFactory.newBuilder() + .withConfig(Config.newBuilder().setEnableNativeRules(nativeRules).build()) + .build(); + } + + private static Descriptor buildRulesDescriptor() { + EnumDescriptorProto kind = + EnumDescriptorProto.newBuilder() + .setName("Kind") + .addValue( + EnumValueDescriptorProto.newBuilder().setName("KIND_UNSPECIFIED").setNumber(0)) + .addValue(EnumValueDescriptorProto.newBuilder().setName("KIND_ONE").setNumber(1)) + .build(); + DescriptorProto entry = + DescriptorProto.newBuilder() + .setName("LabelsEntry") + .setOptions(MessageOptions.newBuilder().setMapEntry(true)) + .addField(field("key", 1, FieldDescriptorProto.Type.TYPE_STRING)) + .addField(field("value", 2, FieldDescriptorProto.Type.TYPE_STRING)) + .build(); + DescriptorProto rules = + DescriptorProto.newBuilder() + .setName("Rules") + .addNestedType(entry) + .addField( + field("number", 1, FieldDescriptorProto.Type.TYPE_INT32) + .setOptions( + rules(FieldRules.newBuilder().setInt32(Int32Rules.newBuilder().setGte(0))))) + .addField( + field("labels", 2, FieldDescriptorProto.Type.TYPE_MESSAGE) + .setLabel(FieldDescriptorProto.Label.LABEL_REPEATED) + .setTypeName(".test.v1.Rules.LabelsEntry") + .setOptions( + rules( + FieldRules.newBuilder() + .setMap( + MapRules.newBuilder() + .setValues( + FieldRules.newBuilder() + .setString( + StringRules.newBuilder().setMinLen(5))))))) + .addField( + field("kinds", 3, FieldDescriptorProto.Type.TYPE_ENUM) + .setLabel(FieldDescriptorProto.Label.LABEL_REPEATED) + .setTypeName(".test.v1.Kind") + .setOptions( + rules( + FieldRules.newBuilder() + .setRepeated(RepeatedRules.newBuilder().setUnique(true))))) + .build(); + try { + return FileDescriptor.buildFrom( + FileDescriptorProto.newBuilder() + .setName("rules.proto") + .setPackage("test.v1") + .setSyntax("proto3") + .addDependency(ValidateProto.getDescriptor().getName()) + .addEnumType(kind) + .addMessageType(rules) + .build(), + new FileDescriptor[] {ValidateProto.getDescriptor()}) + .findMessageTypeByName("Rules"); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private static FieldDescriptorProto.Builder field( + String name, int number, FieldDescriptorProto.Type type) { + return FieldDescriptorProto.newBuilder().setName(name).setNumber(number).setType(type); + } + + private static FieldOptions rules(FieldRules.Builder rules) { + return FieldOptions.newBuilder().setExtension(ValidateProto.field, rules.build()).build(); + } +} diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java index 7b386fa79..2dc942185 100644 --- a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java +++ b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java @@ -17,6 +17,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import build.buf.protovalidate.exceptions.ValidationException; import build.buf.validate.FieldPathElement; import build.buf.validate.FieldRules; import build.buf.validate.Int32Rules; @@ -300,7 +301,7 @@ public void messageFieldRequiresValidateMessage() throws Exception { Validator validator = ValidatorFactory.newBuilder().build(); assertThatThrownBy(() -> validator.validate(message)) - .isInstanceOf(IllegalArgumentException.class) + .isInstanceOf(ValidationException.class) .hasMessageContaining("address") .hasMessageContaining("ValidateMessage"); } From eecfd72ada2736e7bc85b2ac36510cd90ce129b3 Mon Sep 17 00:00:00 2001 From: Jon Bodner Date: Thu, 3 Dec 2026 15:36:08 -0500 Subject: [PATCH 16/23] Check nested and element types and cache CEL field reads 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. --- .../buf/protovalidate/ListElementValue.java | 11 +- .../build/buf/protovalidate/ObjectValue.java | 13 +-- .../build/buf/protovalidate/PlainValue.java | 101 +++++++++++++----- .../buf/protovalidate/ProtobufCopies.java | 9 +- .../protovalidate/ValidateMessageStruct.java | 27 +++++ .../buf/protovalidate/ValidateMessages.java | 17 ++- .../buf/protovalidate/PlainValueTest.java | 4 +- .../ValidateMessageCelCollectionTest.java | 76 ++++++++++++- .../ValidateMessageDefaultsTest.java | 72 +++++++++++++ .../ValidateMessageRulesTest.java | 51 +++++++++ .../ValidateMessageWellKnownTypesTest.java | 33 ++++++ 11 files changed, 366 insertions(+), 48 deletions(-) diff --git a/src/main/java/build/buf/protovalidate/ListElementValue.java b/src/main/java/build/buf/protovalidate/ListElementValue.java index 7987aca7e..86cbfb397 100644 --- a/src/main/java/build/buf/protovalidate/ListElementValue.java +++ b/src/main/java/build/buf/protovalidate/ListElementValue.java @@ -29,7 +29,8 @@ final class ListElementValue implements Value { /** Object type since the object type is inferred from the field descriptor. */ private final Object value; - private final @Nullable ProtobufValidateMessage message; + // Created on first use, because most evaluators never ask for the message wrapper. + private @Nullable ProtobufValidateMessage message; /** * {@link com.google.protobuf.Descriptors.FieldDescriptor} is the field descriptor for the value. @@ -39,10 +40,6 @@ final class ListElementValue implements Value { ListElementValue(Descriptors.FieldDescriptor fieldDescriptor, Object value) { this.value = value; this.fieldDescriptor = fieldDescriptor; - this.message = - fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE - ? new ProtobufValidateMessage((Message) value) - : null; } @Override @@ -52,6 +49,10 @@ final class ListElementValue implements Value { @Override public @Nullable ValidateMessage messageValue() { + if (message == null + && fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { + message = new ProtobufValidateMessage((Message) value); + } return message; } diff --git a/src/main/java/build/buf/protovalidate/ObjectValue.java b/src/main/java/build/buf/protovalidate/ObjectValue.java index 01abe5e5e..e187bd32e 100644 --- a/src/main/java/build/buf/protovalidate/ObjectValue.java +++ b/src/main/java/build/buf/protovalidate/ObjectValue.java @@ -35,7 +35,8 @@ final class ObjectValue implements Value { /** Object type since the object type is inferred from the field descriptor. */ private final Object value; - private final @Nullable ProtobufValidateMessage message; + // Created on first use, because most evaluators never ask for the message wrapper. + private @Nullable ProtobufValidateMessage message; /** * Constructs a new {@link ObjectValue}. @@ -46,11 +47,6 @@ final class ObjectValue implements Value { ObjectValue(Descriptors.FieldDescriptor fieldDescriptor, Object value) { this.fieldDescriptor = fieldDescriptor; this.value = value; - this.message = - !fieldDescriptor.isRepeated() - && fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE - ? new ProtobufValidateMessage((Message) value) - : null; } @Override @@ -61,6 +57,11 @@ public Descriptors.FieldDescriptor fieldDescriptor() { @Nullable @Override public ValidateMessage messageValue() { + if (message == null + && !fieldDescriptor.isRepeated() + && fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { + message = new ProtobufValidateMessage((Message) value); + } return message; } diff --git a/src/main/java/build/buf/protovalidate/PlainValue.java b/src/main/java/build/buf/protovalidate/PlainValue.java index 7044666d9..fb2524998 100644 --- a/src/main/java/build/buf/protovalidate/PlainValue.java +++ b/src/main/java/build/buf/protovalidate/PlainValue.java @@ -43,32 +43,75 @@ final class PlainValue implements Value { checkType(); } - // Fails here, naming the field, instead of as a ClassCastException in a rule evaluator. + // Fails here, naming the field, instead of as a ClassCastException in a rule evaluator. Lists + // and maps are checked whole, because list-level rules read them without wrapping each element. private void checkType() { if (value == null) { return; } - Class expected = expectedType(); - if (expected.isInstance(value) - || (field.getJavaType() == JavaType.ENUM && value instanceof EnumValueDescriptor)) { + if (isList()) { + requireType(field, List.class, value); + for (Object item : (List) value) { + requireElement(field, item); + } + } else if (isMap()) { + requireType(field, Map.class, value); + FieldDescriptor keyField = field.getMessageType().findFieldByNumber(1); + FieldDescriptor valueField = field.getMessageType().findFieldByNumber(2); + for (Map.Entry entry : ((Map) value).entrySet()) { + requireElement(keyField, entry.getKey()); + requireElement(valueField, entry.getValue()); + } + } else { + requireElement(field, value); + } + } + + private void requireElement(FieldDescriptor typeField, @Nullable Object item) { + if (item == null) { + throw new IllegalArgumentException( + "field \"" + field.getFullName() + "\" must not contain null values"); + } + if (typeField.getJavaType() == JavaType.ENUM && item instanceof EnumValueDescriptor) { + requireTypeName( + typeField.getEnumType().getFullName(), + ((EnumValueDescriptor) item).getType().getFullName()); return; } - throw new IllegalArgumentException( - "field \"" - + field.getFullName() - + "\" must be of type " - + expected.getSimpleName() - + ", but got " - + value.getClass().getName()); + requireType(field, scalarType(typeField), item); + if (typeField.getJavaType() == JavaType.MESSAGE) { + // Rules for the declared type would read another type's fields as unset. + requireTypeName( + typeField.getMessageType().getFullName(), + ((ValidateMessage) item).getDescriptorForType().getFullName()); + } } - private Class expectedType() { - if (isList()) { - return List.class; + private void requireTypeName(String expected, String actual) { + if (!expected.equals(actual)) { + throw new IllegalArgumentException( + "field \"" + + field.getFullName() + + "\" must be of type " + + expected + + ", but got " + + actual); } - if (isMap()) { - return Map.class; + } + + private static void requireType(FieldDescriptor field, Class expected, Object item) { + if (!expected.isInstance(item)) { + throw new IllegalArgumentException( + "field \"" + + field.getFullName() + + "\" must be of type " + + expected.getSimpleName() + + ", but got " + + item.getClass().getName()); } + } + + private static Class scalarType(FieldDescriptor field) { switch (field.getJavaType()) { case INT: case ENUM: @@ -169,10 +212,16 @@ public Object celValue() { @Override public T jvmValue(Class clazz) { + // ObjectValue reports protobuf-java Timestamp and Duration values as java.time values, + // including inside a whole list, but ListElementValue reports a single element as a message. if (isList()) { List out = new ArrayList<>(); for (Value item : repeatedValue()) { - out.add(item.jvmValue(Object.class)); + ValidateMessage itemMessage = item.messageValue(); + out.add( + itemMessage != null && isTimeType() + ? ValidateMessages.cel(itemMessage) + : item.jvmValue(Object.class)); } return clazz.cast(out); } @@ -184,19 +233,19 @@ public T jvmValue(Class clazz) { return clazz.cast(out); } if (isMessage()) { - // ObjectValue reports singular protobuf-java Timestamp and Duration fields as java.time - // values, and ListElementValue reports list elements as messages. - String type = field.getMessageType().getFullName(); - if (!element - && (type.equals("google.protobuf.Timestamp") - || type.equals("google.protobuf.Duration"))) { - return clazz.cast(ValidateMessages.cel(message())); - } - return clazz.cast(message()); + return clazz.cast(!element && isTimeType() ? ValidateMessages.cel(message()) : message()); } return clazz.cast(scalarCel()); } + private boolean isTimeType() { + if (field.getJavaType() != JavaType.MESSAGE) { + return false; + } + String type = field.getMessageType().getFullName(); + return type.equals("google.protobuf.Timestamp") || type.equals("google.protobuf.Duration"); + } + private boolean isList() { return field.isRepeated() && !field.isMapField() && !element; } diff --git a/src/main/java/build/buf/protovalidate/ProtobufCopies.java b/src/main/java/build/buf/protovalidate/ProtobufCopies.java index cbec6d211..3319d9b3b 100644 --- a/src/main/java/build/buf/protovalidate/ProtobufCopies.java +++ b/src/main/java/build/buf/protovalidate/ProtobufCopies.java @@ -15,6 +15,7 @@ package build.buf.protovalidate; import com.google.protobuf.Any; +import com.google.protobuf.CodedInputStream; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.EnumValueDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor; @@ -48,10 +49,14 @@ private ProtobufCopies() {} return null; } // The message's descriptor may not be the generated class's, so copy through the wire form. + // protobuf-java has no depth limit for messages built in memory, so neither does the copy. + CodedInputStream input = copy(message).toByteString().newCodedInput(); + input.setRecursionLimit(Integer.MAX_VALUE); try { - return parser.parseFrom(copy(message).toByteString()); + return parser.parseFrom(input); } catch (InvalidProtocolBufferException e) { - throw new IllegalStateException(e); + throw new IllegalArgumentException( + "can't copy " + message.getDescriptorForType().getFullName() + ": " + e.getMessage(), e); } } diff --git a/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java b/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java index cbc8f63d4..9f1975bfb 100644 --- a/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java +++ b/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java @@ -21,6 +21,7 @@ import dev.cel.common.types.StructTypeReference; import dev.cel.common.values.NullValue; import dev.cel.common.values.StructValue; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -36,6 +37,9 @@ final class ValidateMessageStruct extends StructValue { private final ValidateMessage message; private final Descriptor descriptor; + // A rule may read the same field many times, for example a list inside a comprehension, and + // each read would otherwise check and convert the whole value again. + private final Map selected = new HashMap<>(); ValidateMessageStruct(ValidateMessage message) { this.message = message; @@ -61,6 +65,15 @@ public CelType celType() { @Override public Object select(String fieldName) { + Object value = selected.get(fieldName); + if (value == null) { + value = read(fieldName); + selected.put(fieldName, value); + } + return value; + } + + private Object read(String fieldName) { FieldDescriptor field = ValidateMessages.requiredField(descriptor, fieldName); // CEL reads an unset wrapper field as null, not as the wrapped default. if (!field.isRepeated() @@ -127,7 +140,21 @@ public int hashCode() { return null; } + // A ValidateMessage's wrapper fields read as their scalar, but a protobuf-java message's read + // as the wrapper message, so compare wrappers by the value they hold. + private static Object unwrap(Object value) { + if (value instanceof Message + && ValidateMessages.isWrapper(((Message) value).getDescriptorForType())) { + Message wrapper = (Message) value; + FieldDescriptor field = wrapper.getDescriptorForType().findFieldByName("value"); + return ProtoAdapter.scalarToCel(field.getType(), wrapper.getField(field)); + } + return value; + } + private static boolean celEquals(Object left, Object right) { + left = unwrap(left); + right = unwrap(right); ValidateMessageStruct struct = asStruct(left); if (struct != null) { return struct.equals(right); diff --git a/src/main/java/build/buf/protovalidate/ValidateMessages.java b/src/main/java/build/buf/protovalidate/ValidateMessages.java index 2fe8e1c3e..c5ca973f5 100644 --- a/src/main/java/build/buf/protovalidate/ValidateMessages.java +++ b/src/main/java/build/buf/protovalidate/ValidateMessages.java @@ -16,6 +16,7 @@ import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FieldDescriptor; +import java.time.DateTimeException; import java.time.Duration; import java.time.Instant; import java.util.Arrays; @@ -53,11 +54,17 @@ static Object cel(ValidateMessage message) { } Descriptor descriptor = message.getDescriptorForType(); String name = descriptor.getFullName(); - if (name.equals("google.protobuf.Timestamp")) { - return Instant.ofEpochSecond(longField(message, "seconds"), longField(message, "nanos")); - } - if (name.equals("google.protobuf.Duration")) { - return Duration.ofSeconds(longField(message, "seconds"), longField(message, "nanos")); + try { + if (name.equals("google.protobuf.Timestamp")) { + return Instant.ofEpochSecond(longField(message, "seconds"), longField(message, "nanos")); + } + if (name.equals("google.protobuf.Duration")) { + return Duration.ofSeconds(longField(message, "seconds"), longField(message, "nanos")); + } + } catch (DateTimeException | ArithmeticException e) { + // The validator reports IllegalArgumentExceptions from other runtimes' values as + // ExecutionExceptions. + throw new IllegalArgumentException(name + " value is out of range: " + e.getMessage(), e); } if (isWrapper(descriptor)) { return field(message, requiredField(descriptor, "value")).celValue(); diff --git a/src/test/java/build/buf/protovalidate/PlainValueTest.java b/src/test/java/build/buf/protovalidate/PlainValueTest.java index c9df7a8b3..01da58bf8 100644 --- a/src/test/java/build/buf/protovalidate/PlainValueTest.java +++ b/src/test/java/build/buf/protovalidate/PlainValueTest.java @@ -74,9 +74,7 @@ public void rejectsWrongType(FieldDescriptor field, Object value, String expecte @Test public void rejectsWrongElementType() { FieldDescriptor field = field(DescriptorProto.getDescriptor(), "reserved_name"); - PlainValue list = new PlainValue(field, Collections.singletonList(1), false); - - assertThatThrownBy(list::repeatedValue) + assertThatThrownBy(() -> new PlainValue(field, Collections.singletonList(1), false)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("must be of type String"); } diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java index f6234fe49..db6e37170 100644 --- a/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java +++ b/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java @@ -30,10 +30,17 @@ import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.DynamicMessage; +import com.google.protobuf.Int64Value; +import com.google.protobuf.Message; +import com.google.protobuf.WrappersProto; +import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; +import org.jspecify.annotations.Nullable; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -101,6 +108,65 @@ public void readsUnsignedListElements(String expression) { assertThat(outcome(plainOuter(buildOuterDescriptor(expression)))).isEqualTo("[]"); } + // Reading a list inside a comprehension once checked and converted the whole list per element. + @Test + public void ruleReadsEachFieldOnce() throws Exception { + Descriptor outer = + buildOuterDescriptor("this.items.all(i, this.items.exists(j, j.name == i.name))"); + Descriptor inner = outer.getFile().findMessageTypeByName("Inner"); + FieldDescriptor items = outer.findFieldByName("items"); + List elements = new ArrayList<>(); + for (int i = 0; i < 20; i++) { + elements.add( + new MapValidateMessage( + inner, Collections.singletonMap(inner.findFieldByName("name"), "n" + i))); + } + MapValidateMessage fields = + new MapValidateMessage(outer, Collections.singletonMap(items, elements)); + AtomicInteger reads = new AtomicInteger(); + ValidateMessage counting = + new ValidateMessage() { + @Override + public Descriptor getDescriptorForType() { + return outer; + } + + @Override + public boolean hasField(FieldDescriptor field) { + return fields.hasField(field); + } + + @Override + public @Nullable Object getField(FieldDescriptor field) { + if (field.equals(items)) { + reads.incrementAndGet(); + } + return fields.getField(field); + } + }; + + assertThat(validator.validate(counting).getViolations()).isEmpty(); + assertThat(reads.get()).isLessThan(elements.size()); + } + + // A ValidateMessage's wrapper fields read as scalars, but a protobuf-java message's read as + // wrapper messages. + @Test + public void structEqualsMessageWithWrapperFields() { + Descriptor inner = buildOuterDescriptor("true").getFile().findMessageTypeByName("Inner"); + Message protobuf = + DynamicMessage.newBuilder(inner) + .setField(inner.findFieldByName("w"), Int64Value.of(5)) + .addRepeatedField(inner.findFieldByName("ws"), Int64Value.of(6)) + .build(); + ValidateMessageStruct struct = new ValidateMessageStruct(MapValidateMessage.copyOf(protobuf)); + + assertThat(struct).isEqualTo(protobuf); + assertThat(struct) + .isNotEqualTo( + protobuf.toBuilder().setField(inner.findFieldByName("w"), Int64Value.of(7)).build()); + } + // Each call builds new descriptor instances, as a runtime with its own descriptors has. @Test public void structEqualsMessageWithAnotherDescriptorInstance() { @@ -282,6 +348,13 @@ private static Descriptor buildOuterDescriptor(String expression) { .setName("Inner") .addField(field("name", 1, FieldDescriptorProto.Type.TYPE_STRING)) .addField(innerField("child", 2)) + .addField( + field("w", 3, FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".google.protobuf.Int64Value")) + .addField( + field("ws", 4, FieldDescriptorProto.Type.TYPE_MESSAGE) + .setLabel(FieldDescriptorProto.Label.LABEL_REPEATED) + .setTypeName(".google.protobuf.Int64Value")) .build(); try { return FileDescriptor.buildFrom( @@ -290,12 +363,13 @@ private static Descriptor buildOuterDescriptor(String expression) { .setPackage("test.v1") .setSyntax("proto3") .addDependency(ValidateProto.getDescriptor().getName()) + .addDependency(WrappersProto.getDescriptor().getName()) .addEnumType(enumType) .addMessageType(inner) .addMessageType(scalars) .addMessageType(outer) .build(), - new FileDescriptor[] {ValidateProto.getDescriptor()}) + new FileDescriptor[] {ValidateProto.getDescriptor(), WrappersProto.getDescriptor()}) .findMessageTypeByName("Outer"); } catch (Exception e) { throw new IllegalStateException(e); diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageDefaultsTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageDefaultsTest.java index ccf3ade7a..032869a3d 100644 --- a/src/test/java/build/buf/protovalidate/ValidateMessageDefaultsTest.java +++ b/src/test/java/build/buf/protovalidate/ValidateMessageDefaultsTest.java @@ -15,9 +15,12 @@ package build.buf.protovalidate; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import build.buf.protovalidate.exceptions.ValidationException; import build.buf.validate.DurationRules; import build.buf.validate.FieldRules; +import build.buf.validate.Ignore; import build.buf.validate.MessageRules; import build.buf.validate.RepeatedRules; import build.buf.validate.Rule; @@ -38,6 +41,8 @@ import com.google.protobuf.Message; import com.google.protobuf.Timestamp; import com.google.protobuf.TimestampProto; +import java.time.Instant; +import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.junit.jupiter.params.ParameterizedTest; @@ -133,6 +138,63 @@ public void listElementViolationValuesAreMessages(boolean nativeRules) throws Ex assertThat(plain).isInstanceOf(ValidateMessage.class); } + // A whole list is reported with java.time values, as protobuf-java's ObjectValue reports it. + @ParameterizedTest(name = "nativeRules={0}") + @ValueSource(booleans = {true, false}) + public void wholeListViolationValuesMatchProtobufJava(boolean nativeRules) throws Exception { + Descriptor descriptor = build(MessageOptions.getDefaultInstance(), NO_RULES, NO_RULES); + Message message = + DynamicMessage.newBuilder(descriptor) + .addRepeatedField( + descriptor.findFieldByName("tss_min"), + Timestamp.newBuilder().setSeconds(1000).build()) + .build(); + Validator validator = validator(nativeRules); + + Object protobuf = validator.validate(message).getViolations().get(0).getFieldValue().getValue(); + Object plain = + validator + .validate(MapValidateMessage.copyOf(message)) + .getViolations() + .get(0) + .getFieldValue() + .getValue(); + + assertThat(protobuf).isEqualTo(Collections.singletonList(Instant.ofEpochSecond(1000))); + assertThat(plain).isEqualTo(protobuf); + } + + // Converting a value java.time can't hold reports a ValidationException, not a DateTimeException. + @ParameterizedTest(name = "nativeRules={0}") + @ValueSource(booleans = {true, false}) + public void outOfRangeTimestampThrowsValidationException(boolean nativeRules) { + Descriptor descriptor = + build( + MessageOptions.getDefaultInstance(), + FieldRules.newBuilder() + .setTimestamp( + TimestampRules.newBuilder().setGt(Timestamp.newBuilder().setSeconds(100))) + .build(), + NO_RULES); + ValidateMessage message = + MapValidateMessage.copyOf( + DynamicMessage.newBuilder(descriptor) + .setField( + descriptor.findFieldByName("ts"), + Timestamp.newBuilder().setSeconds(Long.MAX_VALUE).build()) + .build()); + + assertThatThrownBy(() -> validator(nativeRules).validate(message)) + .isInstanceOf(ValidationException.class) + .hasMessageContaining("google.protobuf.Timestamp value is out of range"); + } + + private static Validator validator(boolean nativeRules) { + return ValidatorFactory.newBuilder() + .withConfig(Config.newBuilder().setEnableNativeRules(nativeRules).build()) + .build(); + } + private static List violations(boolean nativeRules, Object message) { Validator validator = ValidatorFactory.newBuilder() @@ -187,6 +249,16 @@ private static Descriptor build( field("d", 7, FieldDescriptorProto.Type.TYPE_MESSAGE) .setTypeName(".google.protobuf.Duration") .setOptions(rules(durationRules))) + .addField( + field("tss_min", 9, FieldDescriptorProto.Type.TYPE_MESSAGE) + .setLabel(FieldDescriptorProto.Label.LABEL_REPEATED) + .setTypeName(".google.protobuf.Timestamp") + .setOptions( + rules( + FieldRules.newBuilder() + .setIgnore(Ignore.IGNORE_IF_ZERO_VALUE) + .setRepeated(RepeatedRules.newBuilder().setMinItems(2)) + .build()))) .addField( field("tss", 8, FieldDescriptorProto.Type.TYPE_MESSAGE) .setLabel(FieldDescriptorProto.Label.LABEL_REPEATED) diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageRulesTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageRulesTest.java index 676578b8e..2caf6cc8d 100644 --- a/src/test/java/build/buf/protovalidate/ValidateMessageRulesTest.java +++ b/src/test/java/build/buf/protovalidate/ValidateMessageRulesTest.java @@ -50,6 +50,7 @@ public class ValidateMessageRulesTest { private static final FieldDescriptor NUMBER = RULES.findFieldByName("number"); private static final FieldDescriptor LABELS = RULES.findFieldByName("labels"); private static final FieldDescriptor KINDS = RULES.findFieldByName("kinds"); + private static final FieldDescriptor CHILD = RULES.findFieldByName("child"); // A native rule can read the wrong type before any CEL rule does, so CEL can't wrap the error. @ParameterizedTest(name = "nativeRules={0}") @@ -104,6 +105,53 @@ public void uniqueComparesEnumsByNumber(boolean nativeRules) throws Exception { .containsExactly("repeated.unique"); } + // repeated.unique reads the whole list, so elements are checked without wrapping each one. + @ParameterizedTest(name = "nativeRules={0}") + @ValueSource(booleans = {true, false}) + public void listLevelRulesCheckElementTypes(boolean nativeRules) { + ValidateMessage wrongType = + new MapValidateMessage(RULES, Collections.singletonMap(KINDS, Arrays.asList("a", "b"))); + ValidateMessage nullElement = + new MapValidateMessage(RULES, Collections.singletonMap(KINDS, Arrays.asList(1, null))); + + assertThatThrownBy(() -> validator(nativeRules).validate(wrongType)) + .isInstanceOf(ValidationException.class) + .hasMessageContaining("field \"test.v1.Rules.kinds\" must be of type Integer"); + assertThatThrownBy(() -> validator(nativeRules).validate(nullElement)) + .isInstanceOf(ValidationException.class) + .hasMessageContaining("field \"test.v1.Rules.kinds\" must not contain null values"); + } + + // Rules for the declared type would read another type's fields as unset and skip them. + @ParameterizedTest(name = "nativeRules={0}") + @ValueSource(booleans = {true, false}) + public void nestedMessagesAndEnumsMustHaveTheDeclaredType(boolean nativeRules) { + ValidateMessage wrongMessage = + new MapValidateMessage( + RULES, + Collections.singletonMap( + CHILD, + new MapValidateMessage(DescriptorProto.getDescriptor(), Collections.emptyMap()))); + ValidateMessage wrongEnum = + new MapValidateMessage( + RULES, + Collections.singletonMap( + KINDS, + Collections.singletonList( + FieldDescriptorProto.Type.TYPE_INT32.getValueDescriptor()))); + + assertThatThrownBy(() -> validator(nativeRules).validate(wrongMessage)) + .isInstanceOf(ValidationException.class) + .hasMessageContaining( + "field \"test.v1.Rules.child\" must be of type test.v1.Rules, but got" + + " google.protobuf.DescriptorProto"); + assertThatThrownBy(() -> validator(nativeRules).validate(wrongEnum)) + .isInstanceOf(ValidationException.class) + .hasMessageContaining( + "field \"test.v1.Rules.kinds\" must be of type test.v1.Kind, but got" + + " google.protobuf.FieldDescriptorProto.Type"); + } + private static List violatedKeys(ValidationResult result) { return result.getViolations().stream() .map(violation -> violation.toProto().getField().getElements(0).getStringKey()) @@ -160,6 +208,9 @@ private static Descriptor buildRulesDescriptor() { rules( FieldRules.newBuilder() .setRepeated(RepeatedRules.newBuilder().setUnique(true))))) + .addField( + field("child", 4, FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".test.v1.Rules")) .build(); try { return FileDescriptor.buildFrom( diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageWellKnownTypesTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageWellKnownTypesTest.java index 73a1fa355..8640a0cb7 100644 --- a/src/test/java/build/buf/protovalidate/ValidateMessageWellKnownTypesTest.java +++ b/src/test/java/build/buf/protovalidate/ValidateMessageWellKnownTypesTest.java @@ -43,6 +43,7 @@ import com.google.protobuf.Value; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -114,6 +115,38 @@ public void celMatchesProtobufJava(String expression) { assertThat(plain).as("ValidateMessage").isEqualTo(protobuf); } + // protobuf-java has no depth limit for a message built in memory, so a deep Struct must not + // hit the wire format's recursion limit when it's copied for CEL. + @Test + public void deepStructMatchesProtobufJava() { + Value value = string("leaf"); + for (int i = 0; i < 150; i++) { + value = Value.newBuilder().setStructValue(Struct.newBuilder().putFields("a", value)).build(); + } + Rule rule = + Rule.newBuilder() + .setId("rule") + .setMessage("rule") + .setExpression("size(this.s) == 1") + .build(); + Descriptor outer = + buildOuter( + MessageOptions.newBuilder() + .setExtension(ValidateProto.message, MessageRules.newBuilder().addCel(rule).build()) + .build(), + FieldRules.getDefaultInstance(), + FieldRules.getDefaultInstance()); + DynamicMessage.Builder builder = DynamicMessage.newBuilder(outer); + set(builder, "s", value.getStructValue()); + Message message = builder.build(); + Validator validator = ValidatorFactory.newBuilder().build(); + + assertThat(outcome(validator, message)).as("protobuf-java").isEqualTo("[]"); + assertThat(outcome(validator, MapValidateMessage.copyOf(message))) + .as("ValidateMessage") + .isEqualTo("[]"); + } + private static Stream standardRules() { String duration = ANY.getTypeUrl(); String other = "type.googleapis.com/google.protobuf.Timestamp"; From 9cc7a2a6de474c59b7386a34d6bc7c3fe97233e7 Mon Sep 17 00:00:00 2001 From: Jon Bodner Date: Thu, 3 Dec 2026 15:55:08 -0500 Subject: [PATCH 17/23] Require nested descriptors and compare time fields by value 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. --- .../build/buf/protovalidate/PlainValue.java | 17 ++++- .../protovalidate/ValidateMessageStruct.java | 19 +++--- .../protovalidate/ValidateMessageValue.java | 5 +- .../buf/protovalidate/ValidateMessages.java | 22 +++++-- .../ValidateMessageCelCollectionTest.java | 65 ++++++++++++++++++- .../ValidateMessageRulesTest.java | 21 ++++++ .../protovalidate/ValidateMessageTest.java | 3 +- 7 files changed, 129 insertions(+), 23 deletions(-) diff --git a/src/main/java/build/buf/protovalidate/PlainValue.java b/src/main/java/build/buf/protovalidate/PlainValue.java index fb2524998..cd068f4e0 100644 --- a/src/main/java/build/buf/protovalidate/PlainValue.java +++ b/src/main/java/build/buf/protovalidate/PlainValue.java @@ -15,6 +15,7 @@ package build.buf.protovalidate; import com.google.protobuf.ByteString; +import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.EnumValueDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor.JavaType; @@ -80,10 +81,20 @@ private void requireElement(FieldDescriptor typeField, @Nullable Object item) { } requireType(field, scalarType(typeField), item); if (typeField.getJavaType() == JavaType.MESSAGE) { + Descriptor expected = typeField.getMessageType(); + Descriptor actual = ((ValidateMessage) item).getDescriptorForType(); // Rules for the declared type would read another type's fields as unset. - requireTypeName( - typeField.getMessageType().getFullName(), - ((ValidateMessage) item).getDescriptorForType().getFullName()); + requireTypeName(expected.getFullName(), actual.getFullName()); + // Evaluators read nested messages with the parent schema's field descriptors. + if (actual != expected) { + throw new IllegalArgumentException( + "field \"" + + field.getFullName() + + "\" holds a " + + actual.getFullName() + + " whose descriptor isn't the field's message type; use" + + " FieldDescriptor.getMessageType() for nested messages"); + } } } diff --git a/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java b/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java index 9f1975bfb..5eea0b49c 100644 --- a/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java +++ b/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java @@ -140,16 +140,19 @@ public int hashCode() { return null; } - // A ValidateMessage's wrapper fields read as their scalar, but a protobuf-java message's read - // as the wrapper message, so compare wrappers by the value they hold. + // A ValidateMessage's wrapper, Timestamp and Duration fields read as CEL values, but a + // protobuf-java message's read as messages unless they use the generated classes. private static Object unwrap(Object value) { - if (value instanceof Message - && ValidateMessages.isWrapper(((Message) value).getDescriptorForType())) { - Message wrapper = (Message) value; - FieldDescriptor field = wrapper.getDescriptorForType().findFieldByName("value"); - return ProtoAdapter.scalarToCel(field.getType(), wrapper.getField(field)); + if (!(value instanceof Message)) { + return value; } - return value; + Message message = (Message) value; + if (ValidateMessages.isWrapper(message.getDescriptorForType())) { + FieldDescriptor field = message.getDescriptorForType().findFieldByName("value"); + return ProtoAdapter.scalarToCel(field.getType(), message.getField(field)); + } + Object time = ValidateMessages.time(new ProtobufValidateMessage(message)); + return time != null ? time : value; } private static boolean celEquals(Object left, Object right) { diff --git a/src/main/java/build/buf/protovalidate/ValidateMessageValue.java b/src/main/java/build/buf/protovalidate/ValidateMessageValue.java index 036bc507d..bf2e8330e 100644 --- a/src/main/java/build/buf/protovalidate/ValidateMessageValue.java +++ b/src/main/java/build/buf/protovalidate/ValidateMessageValue.java @@ -52,9 +52,8 @@ public Object celValue() { @Override public T jvmValue(Class clazz) { throw new UnsupportedOperationException( - "jvmValue returns a raw scalar for native rule evaluation and is not supported on a message" - + " value; a ValidateMessage.getField() implementation returned a message value for a" - + " field evaluated as a scalar"); + "jvmValue returns a raw scalar for native rule evaluation and is not supported on the" + + " message being validated"); } @Override diff --git a/src/main/java/build/buf/protovalidate/ValidateMessages.java b/src/main/java/build/buf/protovalidate/ValidateMessages.java index c5ca973f5..e60104b1f 100644 --- a/src/main/java/build/buf/protovalidate/ValidateMessages.java +++ b/src/main/java/build/buf/protovalidate/ValidateMessages.java @@ -22,6 +22,7 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Set; +import org.jspecify.annotations.Nullable; /** Reads {@link ValidateMessage} fields as validator {@link Value}s and CEL values. */ final class ValidateMessages { @@ -52,8 +53,21 @@ static Object cel(ValidateMessage message) { if (message instanceof ProtobufValidateMessage) { return ((ProtobufValidateMessage) message).getMessage(); } + Object time = time(message); + if (time != null) { + return time; + } Descriptor descriptor = message.getDescriptorForType(); - String name = descriptor.getFullName(); + if (isWrapper(descriptor)) { + return field(message, requiredField(descriptor, "value")).celValue(); + } + Object copy = ProtobufCopies.copyIfSpecial(message); + return copy != null ? copy : new ValidateMessageStruct(message); + } + + /** Returns a Timestamp as an {@link Instant} and a Duration as a {@link Duration}, or null. */ + static @Nullable Object time(ValidateMessage message) { + String name = message.getDescriptorForType().getFullName(); try { if (name.equals("google.protobuf.Timestamp")) { return Instant.ofEpochSecond(longField(message, "seconds"), longField(message, "nanos")); @@ -66,11 +80,7 @@ static Object cel(ValidateMessage message) { // ExecutionExceptions. throw new IllegalArgumentException(name + " value is out of range: " + e.getMessage(), e); } - if (isWrapper(descriptor)) { - return field(message, requiredField(descriptor, "value")).celValue(); - } - Object copy = ProtobufCopies.copyIfSpecial(message); - return copy != null ? copy : new ValidateMessageStruct(message); + return null; } static boolean isWrapper(Descriptor descriptor) { diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java index db6e37170..72595eb4c 100644 --- a/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java +++ b/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java @@ -29,9 +29,13 @@ import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.FileDescriptor; +import com.google.protobuf.Duration; +import com.google.protobuf.DurationProto; import com.google.protobuf.DynamicMessage; import com.google.protobuf.Int64Value; import com.google.protobuf.Message; +import com.google.protobuf.Timestamp; +import com.google.protobuf.TimestampProto; import com.google.protobuf.WrappersProto; import java.util.ArrayList; import java.util.Collections; @@ -167,6 +171,52 @@ public void structEqualsMessageWithWrapperFields() { protobuf.toBuilder().setField(inner.findFieldByName("w"), Int64Value.of(7)).build()); } + // A CEL message literal for a runtime-built descriptor holds its Timestamp and Duration as + // DynamicMessages, which CEL doesn't convert to time values. + @Test + public void structEqualsMessageWithTimeFields() { + Descriptor outer = + buildOuterDescriptor( + "this.target == test.v1.Inner{ts: timestamp('1970-01-01T00:00:05Z'), d: duration('6s')}" + + " && this.items[0] == this.target"); + Descriptor inner = outer.getFile().findMessageTypeByName("Inner"); + DynamicMessage protobuf = + DynamicMessage.newBuilder(inner) + .setField(inner.findFieldByName("ts"), timeMessage(Timestamp.getDescriptor(), 5)) + .setField(inner.findFieldByName("d"), timeMessage(Duration.getDescriptor(), 6)) + .build(); + Map fields = new HashMap<>(); + fields.put(outer.findFieldByName("target"), MapValidateMessage.copyOf(protobuf)); + fields.put( + outer.findFieldByName("items"), + Collections.singletonList(MapValidateMessage.copyOf(protobuf))); + ValidateMessageStruct struct = new ValidateMessageStruct(MapValidateMessage.copyOf(protobuf)); + + assertThat(struct).isEqualTo(protobuf); + assertThat(struct) + .isNotEqualTo( + protobuf.toBuilder() + .setField(inner.findFieldByName("d"), timeMessage(Duration.getDescriptor(), 7)) + .build()); + assertThat(outcome(new MapValidateMessage(outer, fields))).isEqualTo("[]"); + } + + // cel-java compares a message literal on the left of == with its own equals, which can't see + // into a ValidateMessage. This pins that known difference, so a cel-java change shows up here. + @Test + public void messageLiteralOnLeftDiffersFromProtobufJava() { + Descriptor outer = buildOuterDescriptor("test.v1.Inner{name: 'alice'} == this.target"); + + assertThat(outcome(dynamicOuter(outer))).isEqualTo("[]"); + assertThat(outcome(plainOuter(outer))).isNotEqualTo("[]"); + } + + private static DynamicMessage timeMessage(Descriptor type, long seconds) { + return DynamicMessage.newBuilder(type) + .setField(type.findFieldByName("seconds"), seconds) + .build(); + } + // Each call builds new descriptor instances, as a runtime with its own descriptors has. @Test public void structEqualsMessageWithAnotherDescriptorInstance() { @@ -355,6 +405,12 @@ private static Descriptor buildOuterDescriptor(String expression) { field("ws", 4, FieldDescriptorProto.Type.TYPE_MESSAGE) .setLabel(FieldDescriptorProto.Label.LABEL_REPEATED) .setTypeName(".google.protobuf.Int64Value")) + .addField( + field("ts", 5, FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".google.protobuf.Timestamp")) + .addField( + field("d", 6, FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".google.protobuf.Duration")) .build(); try { return FileDescriptor.buildFrom( @@ -364,12 +420,19 @@ private static Descriptor buildOuterDescriptor(String expression) { .setSyntax("proto3") .addDependency(ValidateProto.getDescriptor().getName()) .addDependency(WrappersProto.getDescriptor().getName()) + .addDependency(TimestampProto.getDescriptor().getName()) + .addDependency(DurationProto.getDescriptor().getName()) .addEnumType(enumType) .addMessageType(inner) .addMessageType(scalars) .addMessageType(outer) .build(), - new FileDescriptor[] {ValidateProto.getDescriptor(), WrappersProto.getDescriptor()}) + new FileDescriptor[] { + ValidateProto.getDescriptor(), + WrappersProto.getDescriptor(), + TimestampProto.getDescriptor(), + DurationProto.getDescriptor() + }) .findMessageTypeByName("Outer"); } catch (Exception e) { throw new IllegalStateException(e); diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageRulesTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageRulesTest.java index 2caf6cc8d..14cfb85d6 100644 --- a/src/test/java/build/buf/protovalidate/ValidateMessageRulesTest.java +++ b/src/test/java/build/buf/protovalidate/ValidateMessageRulesTest.java @@ -152,6 +152,27 @@ public void nestedMessagesAndEnumsMustHaveTheDeclaredType(boolean nativeRules) { + " google.protobuf.FieldDescriptorProto.Type"); } + // A runtime that builds descriptors again for nested messages would have its fields read with + // the parent schema's descriptors, which it doesn't recognize, so they'd read as unset. + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void nestedMessagesMustUseTheFieldsDescriptor(boolean nativeRules) { + Descriptor copy = buildRulesDescriptor(); + ValidateMessage message = + new MapValidateMessage( + RULES, + Collections.singletonMap( + CHILD, + new MapValidateMessage( + copy, Collections.singletonMap(copy.findFieldByName("number"), -1)))); + + assertThatThrownBy(() -> validator(nativeRules).validate(message)) + .isInstanceOf(ValidationException.class) + .hasMessageContaining( + "field \"test.v1.Rules.child\" holds a test.v1.Rules whose descriptor isn't the" + + " field's message type"); + } + private static List violatedKeys(ValidationResult result) { return result.getViolations().stream() .map(violation -> violation.toProto().getField().getElements(0).getStringKey()) diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java index 2dc942185..12297b569 100644 --- a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java +++ b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java @@ -340,8 +340,7 @@ public void messageValueJvmValueUnsupported() throws Exception { assertThatThrownBy(() -> messageValue.jvmValue(Object.class)) .isInstanceOf(UnsupportedOperationException.class) .hasMessageContaining("jvmValue returns a raw scalar for native rule evaluation") - .hasMessageContaining("not supported on a message value") - .hasMessageContaining("ValidateMessage.getField() implementation returned a message value"); + .hasMessageContaining("not supported on the message being validated"); Value protobufMessageValue = new MessageValue(Timestamp.getDefaultInstance()); assertThatThrownBy(() -> protobufMessageValue.jvmValue(Object.class)) From 5819c2e470c07289113211435074a5aaa92de9e2 Mon Sep 17 00:00:00 2001 From: Jon Bodner Date: Thu, 3 Dec 2026 16:26:35 -0500 Subject: [PATCH 18/23] Run conformance through ValidateMessage 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. --- Makefile | 4 +- .../buf/protovalidate/conformance/Main.java | 19 ++-- .../conformance/PlainValidateMessage.java | 89 +++++++++++++++++++ 3 files changed, 106 insertions(+), 6 deletions(-) create mode 100644 conformance/src/main/java/build/buf/protovalidate/conformance/PlainValidateMessage.java diff --git a/Makefile b/Makefile index 2aa35c07d..aa3ec84a8 100644 --- a/Makefile +++ b/Makefile @@ -29,9 +29,11 @@ clean: ## Delete intermediate build artifacts $(GRADLE) clean .PHONY: conformance -conformance: ## Execute conformance tests with native rule evaluators enabled and disabled. +conformance: ## Execute conformance tests with native rules on and off, for Message and ValidateMessage. ENABLE_NATIVE_RULES=true $(GRADLE) conformance:conformance ENABLE_NATIVE_RULES=false $(GRADLE) conformance:conformance + ENABLE_NATIVE_RULES=true VALIDATE_MESSAGE=true $(GRADLE) conformance:conformance + ENABLE_NATIVE_RULES=false VALIDATE_MESSAGE=true $(GRADLE) conformance:conformance .PHONY: help help: ## Describe useful make targets diff --git a/conformance/src/main/java/build/buf/protovalidate/conformance/Main.java b/conformance/src/main/java/build/buf/protovalidate/conformance/Main.java index 902de0a63..089029a33 100644 --- a/conformance/src/main/java/build/buf/protovalidate/conformance/Main.java +++ b/conformance/src/main/java/build/buf/protovalidate/conformance/Main.java @@ -69,11 +69,13 @@ static TestConformanceResponse testConformance(TestConformanceRequest request) { } Config cfg = cfgBuilder.build(); Validator validator = ValidatorFactory.newBuilder().withConfig(cfg).build(); + boolean validateMessage = Boolean.parseBoolean(System.getenv("VALIDATE_MESSAGE")); TestConformanceResponse.Builder responseBuilder = TestConformanceResponse.newBuilder(); Map resultsMap = new HashMap<>(); for (Map.Entry entry : request.getCasesMap().entrySet()) { - TestResult testResult = testCase(validator, descriptorMap, entry.getValue()); + TestResult testResult = + testCase(validator, descriptorMap, entry.getValue(), validateMessage); resultsMap.put(entry.getKey(), testResult); } responseBuilder.putAllResults(resultsMap); @@ -84,7 +86,10 @@ static TestConformanceResponse testConformance(TestConformanceRequest request) { } static TestResult testCase( - Validator validator, Map fileDescriptors, Any testCase) + Validator validator, + Map fileDescriptors, + Any testCase, + boolean validateMessage) throws InvalidProtocolBufferException { String fullName = testCase.getTypeUrl(); int slash = fullName.indexOf('/'); @@ -98,12 +103,16 @@ static TestResult testCase( ByteString testCaseValue = testCase.getValue(); DynamicMessage dynamicMessage = DynamicMessage.newBuilder(descriptor).mergeFrom(testCaseValue).build(); - return validate(validator, dynamicMessage); + return validate(validator, dynamicMessage, validateMessage); } - private static TestResult validate(Validator validator, DynamicMessage dynamicMessage) { + private static TestResult validate( + Validator validator, DynamicMessage dynamicMessage, boolean validateMessage) { try { - ValidationResult result = validator.validate(dynamicMessage); + ValidationResult result = + validateMessage + ? validator.validate(new PlainValidateMessage(dynamicMessage)) + : validator.validate(dynamicMessage); if (result.isSuccess()) { return TestResult.newBuilder().setSuccess(true).build(); } diff --git a/conformance/src/main/java/build/buf/protovalidate/conformance/PlainValidateMessage.java b/conformance/src/main/java/build/buf/protovalidate/conformance/PlainValidateMessage.java new file mode 100644 index 000000000..be12675a2 --- /dev/null +++ b/conformance/src/main/java/build/buf/protovalidate/conformance/PlainValidateMessage.java @@ -0,0 +1,89 @@ +// Copyright 2023-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package build.buf.protovalidate.conformance; + +import build.buf.protovalidate.ValidateMessage; +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.EnumValueDescriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Message; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.jspecify.annotations.Nullable; + +/** + * PlainValidateMessage presents a protobuf-java message as another runtime would, through + * ValidateMessage's plain values, so conformance can run the validator's path for other runtimes. + */ +final class PlainValidateMessage implements ValidateMessage { + private final Message message; + + PlainValidateMessage(Message message) { + this.message = message; + } + + @Override + public Descriptor getDescriptorForType() { + return message.getDescriptorForType(); + } + + @Override + public boolean hasField(FieldDescriptor field) { + return field.isRepeated() ? message.getRepeatedFieldCount(field) > 0 : message.hasField(field); + } + + @Override + public boolean isEmpty() { + return message.getAllFields().isEmpty() && message.getUnknownFields().asMap().isEmpty(); + } + + @Override + public @Nullable Object getField(FieldDescriptor field) { + if (!field.isRepeated() && field.hasPresence() && !message.hasField(field)) { + return null; + } + Object value = message.getField(field); + if (field.isMapField()) { + FieldDescriptor keyField = field.getMessageType().findFieldByNumber(1); + FieldDescriptor valueField = field.getMessageType().findFieldByNumber(2); + Map out = new LinkedHashMap<>(); + for (Object entry : (List) value) { + Message entryMessage = (Message) entry; + out.put(plain(entryMessage.getField(keyField)), plain(entryMessage.getField(valueField))); + } + return out; + } + if (field.isRepeated()) { + List out = new ArrayList<>(); + for (Object element : (List) value) { + out.add(plain(element)); + } + return out; + } + return plain(value); + } + + private static Object plain(Object value) { + if (value instanceof EnumValueDescriptor) { + return ((EnumValueDescriptor) value).getNumber(); + } + if (value instanceof Message) { + return new PlainValidateMessage((Message) value); + } + return value; + } +} From 6df1cbc68c3060bc2b4a69699b38406598664597 Mon Sep 17 00:00:00 2001 From: Jon Bodner Date: Thu, 3 Dec 2026 16:26:35 -0500 Subject: [PATCH 19/23] Compare ValidateMessages by plain values 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. --- .../buf/protovalidate/EvaluatorBuilder.java | 2 +- .../build/buf/protovalidate/MessageValue.java | 74 --------------- .../build/buf/protovalidate/PlainValue.java | 16 +--- .../protovalidate/ValidateMessageStruct.java | 95 ++++++++++--------- .../protovalidate/ValidateMessageValue.java | 6 +- .../protovalidate/ValidateMessageTest.java | 6 -- 6 files changed, 58 insertions(+), 141 deletions(-) delete mode 100644 src/main/java/build/buf/protovalidate/MessageValue.java diff --git a/src/main/java/build/buf/protovalidate/EvaluatorBuilder.java b/src/main/java/build/buf/protovalidate/EvaluatorBuilder.java index 9ef0c48d8..fbd1dd59d 100644 --- a/src/main/java/build/buf/protovalidate/EvaluatorBuilder.java +++ b/src/main/java/build/buf/protovalidate/EvaluatorBuilder.java @@ -650,7 +650,7 @@ private static List compileRules( cel.createProgram(astExpression.ast), astExpression.source, rulePath, - new MessageValue(rules.get(i)), + new ValidateMessageValue(new ProtobufValidateMessage(rules.get(i))), null)); } catch (CelEvaluationException e) { throw new CompilationException("failed to evaluate rule " + rules.get(i).getId(), e); diff --git a/src/main/java/build/buf/protovalidate/MessageValue.java b/src/main/java/build/buf/protovalidate/MessageValue.java deleted file mode 100644 index 08012a36a..000000000 --- a/src/main/java/build/buf/protovalidate/MessageValue.java +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2023-2026 Buf Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package build.buf.protovalidate; - -import com.google.protobuf.Descriptors; -import com.google.protobuf.Message; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import org.jspecify.annotations.Nullable; - -/** The {@link Value} type that contains a {@link com.google.protobuf.Message}. */ -final class MessageValue implements Value { - - private final ProtobufValidateMessage value; - - /** - * Constructs a {@link MessageValue} with the provided message value. - * - * @param value The message value. - */ - MessageValue(Message value) { - this.value = new ProtobufValidateMessage(value); - } - - @Override - public Descriptors.@Nullable FieldDescriptor fieldDescriptor() { - return null; - } - - @Override - public ValidateMessage messageValue() { - return value; - } - - @Override - public Object celValue() { - return value.getMessage(); - } - - @Override - public T jvmValue(Class clazz) { - throw new UnsupportedOperationException( - "jvmValue returns a raw scalar for native rule evaluation and is not supported on a message" - + " value; use messageValue() or celValue() instead"); - } - - @Override - public Object rawValue() { - return value; - } - - @Override - public List repeatedValue() { - return Collections.emptyList(); - } - - @Override - public Map mapValue() { - return Collections.emptyMap(); - } -} diff --git a/src/main/java/build/buf/protovalidate/PlainValue.java b/src/main/java/build/buf/protovalidate/PlainValue.java index cd068f4e0..e406c7532 100644 --- a/src/main/java/build/buf/protovalidate/PlainValue.java +++ b/src/main/java/build/buf/protovalidate/PlainValue.java @@ -229,10 +229,7 @@ public T jvmValue(Class clazz) { List out = new ArrayList<>(); for (Value item : repeatedValue()) { ValidateMessage itemMessage = item.messageValue(); - out.add( - itemMessage != null && isTimeType() - ? ValidateMessages.cel(itemMessage) - : item.jvmValue(Object.class)); + out.add(itemMessage != null ? timeOrMessage(itemMessage) : item.jvmValue(Object.class)); } return clazz.cast(out); } @@ -244,17 +241,14 @@ public T jvmValue(Class clazz) { return clazz.cast(out); } if (isMessage()) { - return clazz.cast(!element && isTimeType() ? ValidateMessages.cel(message()) : message()); + return clazz.cast(element ? message() : timeOrMessage(message())); } return clazz.cast(scalarCel()); } - private boolean isTimeType() { - if (field.getJavaType() != JavaType.MESSAGE) { - return false; - } - String type = field.getMessageType().getFullName(); - return type.equals("google.protobuf.Timestamp") || type.equals("google.protobuf.Duration"); + private static Object timeOrMessage(ValidateMessage message) { + Object time = ValidateMessages.time(message); + return time != null ? time : message; } private boolean isList() { diff --git a/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java b/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java index 5eea0b49c..c42566ebb 100644 --- a/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java +++ b/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java @@ -15,6 +15,7 @@ package build.buf.protovalidate; import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.EnumValueDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Message; import dev.cel.common.types.CelType; @@ -93,28 +94,8 @@ public Optional find(String fieldName) { @Override public boolean equals(@Nullable Object other) { - ValidateMessageStruct that = asStruct(other); - if (that == null - || !descriptor.getFullName().equals(that.descriptor.getFullName()) - || descriptor.getFields().size() != that.descriptor.getFields().size()) { - return false; - } - for (FieldDescriptor field : descriptor.getFields()) { - // The other message may use a different descriptor instance for the same type, and - // protobuf-java rejects a FieldDescriptor from another instance. - FieldDescriptor thatField = that.descriptor.findFieldByNumber(field.getNumber()); - if (thatField == null) { - return false; - } - boolean present = message.hasField(field); - if (present != that.message.hasField(thatField)) { - return false; - } - if (present && !celEquals(select(field.getName()), that.select(thatField.getName()))) { - return false; - } - } - return true; + ValidateMessage that = asMessage(other); + return that != null && contentEquals(message, that); } @Override @@ -128,39 +109,57 @@ public int hashCode() { return hash; } - // A protobuf-java message is compared field by field, so CEL message literals and nested - // protobuf-java values compare equal to structs with the same contents. - private static @Nullable ValidateMessageStruct asStruct(@Nullable Object value) { + // CEL message literals and nested protobuf-java values compare equal to structs with the same + // contents. + private static @Nullable ValidateMessage asMessage(@Nullable Object value) { if (value instanceof ValidateMessageStruct) { - return (ValidateMessageStruct) value; + return ((ValidateMessageStruct) value).message; } if (value instanceof Message) { - return new ValidateMessageStruct(new ProtobufValidateMessage((Message) value)); + return new ProtobufValidateMessage((Message) value); } return null; } - // A ValidateMessage's wrapper, Timestamp and Duration fields read as CEL values, but a - // protobuf-java message's read as messages unless they use the generated classes. - private static Object unwrap(Object value) { - if (!(value instanceof Message)) { - return value; + // Compares getField's plain values rather than CEL values, so types that CEL converts, such as + // wrappers and Timestamps, need no special cases. + private static boolean contentEquals(ValidateMessage left, ValidateMessage right) { + Descriptor leftType = left.getDescriptorForType(); + Descriptor rightType = right.getDescriptorForType(); + if (!leftType.getFullName().equals(rightType.getFullName()) + || leftType.getFields().size() != rightType.getFields().size()) { + return false; } - Message message = (Message) value; - if (ValidateMessages.isWrapper(message.getDescriptorForType())) { - FieldDescriptor field = message.getDescriptorForType().findFieldByName("value"); - return ProtoAdapter.scalarToCel(field.getType(), message.getField(field)); + for (FieldDescriptor leftField : leftType.getFields()) { + // The messages may use different descriptor instances for the same type, and protobuf-java + // rejects a FieldDescriptor from another instance. + FieldDescriptor rightField = rightType.findFieldByNumber(leftField.getNumber()); + if (rightField == null) { + return false; + } + boolean present = left.hasField(leftField); + if (present != right.hasField(rightField)) { + return false; + } + if (present && !plainEquals(plainField(left, leftField), plainField(right, rightField))) { + return false; + } } - Object time = ValidateMessages.time(new ProtobufValidateMessage(message)); - return time != null ? time : value; + return true; + } + + // Other runtimes' values are type-checked, as they are when a rule reads the field. + private static @Nullable Object plainField(ValidateMessage message, FieldDescriptor field) { + return message instanceof ProtobufValidateMessage + ? message.getField(field) + : ValidateMessages.field(message, field).rawValue(); } - private static boolean celEquals(Object left, Object right) { - left = unwrap(left); - right = unwrap(right); - ValidateMessageStruct struct = asStruct(left); - if (struct != null) { - return struct.equals(right); + private static boolean plainEquals(@Nullable Object left, @Nullable Object right) { + left = enumNumber(left); + right = enumNumber(right); + if (left instanceof ValidateMessage && right instanceof ValidateMessage) { + return contentEquals((ValidateMessage) left, (ValidateMessage) right); } if (left instanceof List && right instanceof List) { List leftList = (List) left; @@ -169,7 +168,7 @@ private static boolean celEquals(Object left, Object right) { return false; } for (int i = 0; i < leftList.size(); i++) { - if (!celEquals(leftList.get(i), rightList.get(i))) { + if (!plainEquals(leftList.get(i), rightList.get(i))) { return false; } } @@ -183,7 +182,7 @@ private static boolean celEquals(Object left, Object right) { } for (Map.Entry entry : leftMap.entrySet()) { if (!rightMap.containsKey(entry.getKey()) - || !celEquals(entry.getValue(), rightMap.get(entry.getKey()))) { + || !plainEquals(entry.getValue(), rightMap.get(entry.getKey()))) { return false; } } @@ -191,4 +190,8 @@ private static boolean celEquals(Object left, Object right) { } return Objects.equals(left, right); } + + private static @Nullable Object enumNumber(@Nullable Object value) { + return value instanceof EnumValueDescriptor ? ((EnumValueDescriptor) value).getNumber() : value; + } } diff --git a/src/main/java/build/buf/protovalidate/ValidateMessageValue.java b/src/main/java/build/buf/protovalidate/ValidateMessageValue.java index bf2e8330e..4f63bd7e3 100644 --- a/src/main/java/build/buf/protovalidate/ValidateMessageValue.java +++ b/src/main/java/build/buf/protovalidate/ValidateMessageValue.java @@ -20,7 +20,7 @@ import java.util.Map; import org.jspecify.annotations.Nullable; -/** Top-level {@link Value} backed by a user-supplied {@link ValidateMessage}. */ +/** A {@link Value} for a whole message, such as the one being validated or a rule. */ final class ValidateMessageValue implements Value { private final ValidateMessage message; @@ -52,8 +52,8 @@ public Object celValue() { @Override public T jvmValue(Class clazz) { throw new UnsupportedOperationException( - "jvmValue returns a raw scalar for native rule evaluation and is not supported on the" - + " message being validated"); + "jvmValue returns a raw scalar for native rule evaluation and is not supported on a message" + + " value; use messageValue() or celValue() instead"); } @Override diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java index 12297b569..1e1b52afa 100644 --- a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java +++ b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java @@ -338,12 +338,6 @@ public void messageValueJvmValueUnsupported() throws Exception { Value messageValue = new ValidateMessageValue(address(addressDescriptor, "Main Street")); assertThatThrownBy(() -> messageValue.jvmValue(Object.class)) - .isInstanceOf(UnsupportedOperationException.class) - .hasMessageContaining("jvmValue returns a raw scalar for native rule evaluation") - .hasMessageContaining("not supported on the message being validated"); - - Value protobufMessageValue = new MessageValue(Timestamp.getDefaultInstance()); - assertThatThrownBy(() -> protobufMessageValue.jvmValue(Object.class)) .isInstanceOf(UnsupportedOperationException.class) .hasMessageContaining("jvmValue returns a raw scalar for native rule evaluation") .hasMessageContaining("not supported on a message value") From b75e3d22ec30ae25cd8356d8148af8ddb2a70d93 Mon Sep 17 00:00:00 2001 From: Jon Bodner Date: Fri, 4 Dec 2026 11:46:42 -0500 Subject: [PATCH 20/23] Drop the unused rule value and restore Value.value Custom CEL rules passed a ValidateMessageValue over the rule message to CompiledProgram, which only reads a rule value that has a field descriptor, so it was never used. A constructor without the rule value and rule variable now says that at the call site. Value is package-private, so the jvmValue name bought no compatibility and only enlarged the diff from main. It also returns CEL's scalar forms, not plain JVM ones. --- .../java/build/buf/protovalidate/AnyEvaluator.java | 2 +- .../java/build/buf/protovalidate/CompiledProgram.java | 5 +++++ .../java/build/buf/protovalidate/EnumEvaluator.java | 2 +- .../java/build/buf/protovalidate/EvaluatorBuilder.java | 6 +----- .../java/build/buf/protovalidate/ListElementValue.java | 2 +- .../java/build/buf/protovalidate/MapEvaluator.java | 8 ++++---- src/main/java/build/buf/protovalidate/ObjectValue.java | 2 +- src/main/java/build/buf/protovalidate/PlainValue.java | 6 +++--- .../java/build/buf/protovalidate/RuleViolation.java | 2 +- .../build/buf/protovalidate/ValidateMessageValue.java | 6 +++--- src/main/java/build/buf/protovalidate/Value.java | 6 +++--- .../java/build/buf/protovalidate/ValueEvaluator.java | 2 +- .../build/buf/protovalidate/ValidateMessageTest.java | 10 +++++----- 13 files changed, 30 insertions(+), 29 deletions(-) diff --git a/src/main/java/build/buf/protovalidate/AnyEvaluator.java b/src/main/java/build/buf/protovalidate/AnyEvaluator.java index 8498fb082..6f4425197 100644 --- a/src/main/java/build/buf/protovalidate/AnyEvaluator.java +++ b/src/main/java/build/buf/protovalidate/AnyEvaluator.java @@ -82,7 +82,7 @@ public List evaluate(Value val, boolean failFast) return RuleViolation.NO_VIOLATIONS; } List violationList = new ArrayList<>(); - String typeURL = ValidateMessages.field(anyValue, typeURLDescriptor).jvmValue(String.class); + String typeURL = ValidateMessages.field(anyValue, typeURLDescriptor).value(String.class); if (!in.isEmpty() && !in.contains(typeURL)) { RuleViolation.Builder violation = RuleViolation.newBuilder() diff --git a/src/main/java/build/buf/protovalidate/CompiledProgram.java b/src/main/java/build/buf/protovalidate/CompiledProgram.java index 779b0bd7a..a8d29991e 100644 --- a/src/main/java/build/buf/protovalidate/CompiledProgram.java +++ b/src/main/java/build/buf/protovalidate/CompiledProgram.java @@ -65,6 +65,11 @@ final class CompiledProgram { this.globals = globals; } + // Custom CEL rules have no rule value to report and no rule variable to bind. + CompiledProgram(Program program, Expression source, @Nullable FieldPath rulePath) { + this(program, source, rulePath, null, null); + } + /** * Evaluate the compiled program with a given set of {@link Variable} variables. * diff --git a/src/main/java/build/buf/protovalidate/EnumEvaluator.java b/src/main/java/build/buf/protovalidate/EnumEvaluator.java index a77613cba..d8dfd6b6c 100644 --- a/src/main/java/build/buf/protovalidate/EnumEvaluator.java +++ b/src/main/java/build/buf/protovalidate/EnumEvaluator.java @@ -77,7 +77,7 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - Number enumValue = val.jvmValue(Number.class); + Number enumValue = val.value(Number.class); if (enumValue == null) { return RuleViolation.NO_VIOLATIONS; } diff --git a/src/main/java/build/buf/protovalidate/EvaluatorBuilder.java b/src/main/java/build/buf/protovalidate/EvaluatorBuilder.java index fbd1dd59d..e0e0a2ba6 100644 --- a/src/main/java/build/buf/protovalidate/EvaluatorBuilder.java +++ b/src/main/java/build/buf/protovalidate/EvaluatorBuilder.java @@ -647,11 +647,7 @@ private static List compileRules( try { compiledPrograms.add( new CompiledProgram( - cel.createProgram(astExpression.ast), - astExpression.source, - rulePath, - new ValidateMessageValue(new ProtobufValidateMessage(rules.get(i))), - null)); + cel.createProgram(astExpression.ast), astExpression.source, rulePath)); } catch (CelEvaluationException e) { throw new CompilationException("failed to evaluate rule " + rules.get(i).getId(), e); } diff --git a/src/main/java/build/buf/protovalidate/ListElementValue.java b/src/main/java/build/buf/protovalidate/ListElementValue.java index 86cbfb397..a35b4f755 100644 --- a/src/main/java/build/buf/protovalidate/ListElementValue.java +++ b/src/main/java/build/buf/protovalidate/ListElementValue.java @@ -62,7 +62,7 @@ public Object celValue() { } @Override - public T jvmValue(Class clazz) { + public T value(Class clazz) { Descriptors.FieldDescriptor.Type type = fieldDescriptor.getType(); if (type == Descriptors.FieldDescriptor.Type.MESSAGE) { return clazz.cast(value); diff --git a/src/main/java/build/buf/protovalidate/MapEvaluator.java b/src/main/java/build/buf/protovalidate/MapEvaluator.java index 0dfcecbfb..bc418e977 100644 --- a/src/main/java/build/buf/protovalidate/MapEvaluator.java +++ b/src/main/java/build/buf/protovalidate/MapEvaluator.java @@ -155,19 +155,19 @@ private List evalPairs(Value key, Value value, boolean fa case TYPE_SINT64: case TYPE_SFIXED32: case TYPE_SFIXED64: - fieldPathElementBuilder.setIntKey(key.jvmValue(Number.class).longValue()); + fieldPathElementBuilder.setIntKey(key.value(Number.class).longValue()); break; case TYPE_UINT32: case TYPE_UINT64: case TYPE_FIXED32: case TYPE_FIXED64: - fieldPathElementBuilder.setUintKey(key.jvmValue(Number.class).longValue()); + fieldPathElementBuilder.setUintKey(key.value(Number.class).longValue()); break; case TYPE_BOOL: - fieldPathElementBuilder.setBoolKey(key.jvmValue(Boolean.class)); + fieldPathElementBuilder.setBoolKey(key.value(Boolean.class)); break; case TYPE_STRING: - fieldPathElementBuilder.setStringKey(key.jvmValue(String.class)); + fieldPathElementBuilder.setStringKey(key.value(String.class)); break; default: throw new ExecutionException("Unexpected map key type"); diff --git a/src/main/java/build/buf/protovalidate/ObjectValue.java b/src/main/java/build/buf/protovalidate/ObjectValue.java index e187bd32e..fd4449434 100644 --- a/src/main/java/build/buf/protovalidate/ObjectValue.java +++ b/src/main/java/build/buf/protovalidate/ObjectValue.java @@ -71,7 +71,7 @@ public Object celValue() { } @Override - public T jvmValue(Class clazz) { + public T value(Class clazz) { if (value instanceof Descriptors.EnumValueDescriptor) { return clazz.cast((long) ((Descriptors.EnumValueDescriptor) value).getNumber()); } diff --git a/src/main/java/build/buf/protovalidate/PlainValue.java b/src/main/java/build/buf/protovalidate/PlainValue.java index e406c7532..c03be4c7a 100644 --- a/src/main/java/build/buf/protovalidate/PlainValue.java +++ b/src/main/java/build/buf/protovalidate/PlainValue.java @@ -222,21 +222,21 @@ public Object celValue() { } @Override - public T jvmValue(Class clazz) { + public T value(Class clazz) { // ObjectValue reports protobuf-java Timestamp and Duration values as java.time values, // including inside a whole list, but ListElementValue reports a single element as a message. if (isList()) { List out = new ArrayList<>(); for (Value item : repeatedValue()) { ValidateMessage itemMessage = item.messageValue(); - out.add(itemMessage != null ? timeOrMessage(itemMessage) : item.jvmValue(Object.class)); + out.add(itemMessage != null ? timeOrMessage(itemMessage) : item.value(Object.class)); } return clazz.cast(out); } if (isMap()) { Map out = new HashMap<>(); for (Map.Entry entry : mapValue().entrySet()) { - out.put(entry.getKey().jvmValue(Object.class), entry.getValue().jvmValue(Object.class)); + out.put(entry.getKey().value(Object.class), entry.getValue().value(Object.class)); } return clazz.cast(out); } diff --git a/src/main/java/build/buf/protovalidate/RuleViolation.java b/src/main/java/build/buf/protovalidate/RuleViolation.java index 39d18930d..454d2f782 100644 --- a/src/main/java/build/buf/protovalidate/RuleViolation.java +++ b/src/main/java/build/buf/protovalidate/RuleViolation.java @@ -55,7 +55,7 @@ static class FieldValue implements Violation.FieldValue { * @param value A {@link Value} to create this {@link FieldValue} from. */ FieldValue(Value value) { - this.value = value.jvmValue(Object.class); + this.value = value.value(Object.class); this.descriptor = Objects.requireNonNull(value.fieldDescriptor()); } diff --git a/src/main/java/build/buf/protovalidate/ValidateMessageValue.java b/src/main/java/build/buf/protovalidate/ValidateMessageValue.java index 4f63bd7e3..d73ec0690 100644 --- a/src/main/java/build/buf/protovalidate/ValidateMessageValue.java +++ b/src/main/java/build/buf/protovalidate/ValidateMessageValue.java @@ -20,7 +20,7 @@ import java.util.Map; import org.jspecify.annotations.Nullable; -/** A {@link Value} for a whole message, such as the one being validated or a rule. */ +/** A {@link Value} for the message being validated. */ final class ValidateMessageValue implements Value { private final ValidateMessage message; @@ -50,9 +50,9 @@ public Object celValue() { } @Override - public T jvmValue(Class clazz) { + public T value(Class clazz) { throw new UnsupportedOperationException( - "jvmValue returns a raw scalar for native rule evaluation and is not supported on a message" + "value(Class) returns a scalar for native rule evaluation and is not supported on a message" + " value; use messageValue() or celValue() instead"); } diff --git a/src/main/java/build/buf/protovalidate/Value.java b/src/main/java/build/buf/protovalidate/Value.java index 3acb4bed7..705d53c06 100644 --- a/src/main/java/build/buf/protovalidate/Value.java +++ b/src/main/java/build/buf/protovalidate/Value.java @@ -72,8 +72,8 @@ interface Value { Object celValue(); /** - * Returns the JVM representation specified in the {@link Value} type table, cast to {@code - * clazz}. + * Get the underlying value and cast it to the class type. Native rules, map keys, ignore checks + * and violation values read this, while CEL reads {@link #celValue}. * *

    Values returned by {@link ValidateMessage#getField}, {@link #repeatedValue}, or {@link * #mapValue} must support {@code Object.class} for violation details, including message-valued @@ -85,5 +85,5 @@ interface Value { * @return The value cast to the inferred class type. * @param The class type. */ - T jvmValue(Class clazz); + T value(Class clazz); } diff --git a/src/main/java/build/buf/protovalidate/ValueEvaluator.java b/src/main/java/build/buf/protovalidate/ValueEvaluator.java index 51f50c1ef..bcb61d255 100644 --- a/src/main/java/build/buf/protovalidate/ValueEvaluator.java +++ b/src/main/java/build/buf/protovalidate/ValueEvaluator.java @@ -110,7 +110,7 @@ private boolean isZeroValue(Value val) { ValidateMessage message = val.messageValue(); return message != null && message.isEmpty(); } - Object value = val.jvmValue(Object.class); + Object value = val.value(Object.class); if (zero instanceof Long && value instanceof Number) { return ((Number) value).longValue() == (Long) zero; } diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java index 1e1b52afa..a351c4be0 100644 --- a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java +++ b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java @@ -67,7 +67,7 @@ private static Stream customRuleCases() { @ParameterizedTest(name = "nativeRules={0}, stringResult={1}, valid={2}") @MethodSource("customRuleCases") - public void customRulesDoNotReadMessageJvmValues( + public void customRulesDoNotReadMessagesAsScalars( boolean nativeRules, boolean stringResult, boolean valid) throws Exception { String result = stringResult ? " ? '' : 'invalid name'" : ""; Rule messageRule = @@ -330,16 +330,16 @@ public void scalarFieldRequiresDocumentedType(boolean nativeRules) throws Except } @Test - public void messageValueJvmValueUnsupported() throws Exception { - // A message has no raw scalar form, so jvmValue is unsupported on a message-backed Value. + public void valueUnsupportedOnMessageValue() throws Exception { + // A message has no scalar form, so value(Class) is unsupported on a message-backed Value. Descriptors.Descriptor descriptor = buildPersonDescriptor(); Descriptors.Descriptor addressDescriptor = descriptor.findFieldByName("address").getMessageType(); Value messageValue = new ValidateMessageValue(address(addressDescriptor, "Main Street")); - assertThatThrownBy(() -> messageValue.jvmValue(Object.class)) + assertThatThrownBy(() -> messageValue.value(Object.class)) .isInstanceOf(UnsupportedOperationException.class) - .hasMessageContaining("jvmValue returns a raw scalar for native rule evaluation") + .hasMessageContaining("value(Class) returns a scalar for native rule evaluation") .hasMessageContaining("not supported on a message value") .hasMessageContaining("use messageValue() or celValue() instead"); } From 792773b539f25f12892ab55d720a95b6f5d4d9f4 Mon Sep 17 00:00:00 2001 From: Jon Bodner Date: Fri, 4 Dec 2026 11:50:59 -0500 Subject: [PATCH 21/23] Restore the MessageValue name The class is package-private, so the ValidateMessageValue name bought nothing and turned a small change to main's MessageValue into a rename. --- ...ateMessageValue.java => MessageValue.java} | 29 +++++++++++-------- .../buf/protovalidate/ValidatorImpl.java | 2 +- .../protovalidate/ValidateMessageTest.java | 2 +- 3 files changed, 19 insertions(+), 14 deletions(-) rename src/main/java/build/buf/protovalidate/{ValidateMessageValue.java => MessageValue.java} (78%) diff --git a/src/main/java/build/buf/protovalidate/ValidateMessageValue.java b/src/main/java/build/buf/protovalidate/MessageValue.java similarity index 78% rename from src/main/java/build/buf/protovalidate/ValidateMessageValue.java rename to src/main/java/build/buf/protovalidate/MessageValue.java index d73ec0690..78ae8ffe2 100644 --- a/src/main/java/build/buf/protovalidate/ValidateMessageValue.java +++ b/src/main/java/build/buf/protovalidate/MessageValue.java @@ -20,13 +20,18 @@ import java.util.Map; import org.jspecify.annotations.Nullable; -/** A {@link Value} for the message being validated. */ -final class ValidateMessageValue implements Value { +/** The {@link Value} type that contains a {@link ValidateMessage}. */ +final class MessageValue implements Value { - private final ValidateMessage message; + private final ValidateMessage value; - ValidateMessageValue(ValidateMessage message) { - this.message = message; + /** + * Constructs a {@link MessageValue} with the provided message value. + * + * @param value The message value. + */ + MessageValue(ValidateMessage value) { + this.value = value; } @Override @@ -36,17 +41,12 @@ final class ValidateMessageValue implements Value { @Override public ValidateMessage messageValue() { - return message; - } - - @Override - public Object rawValue() { - return message; + return value; } @Override public Object celValue() { - return ValidateMessages.cel(message); + return ValidateMessages.cel(value); } @Override @@ -56,6 +56,11 @@ public T value(Class clazz) { + " value; use messageValue() or celValue() instead"); } + @Override + public Object rawValue() { + return value; + } + @Override public List repeatedValue() { return Collections.emptyList(); diff --git a/src/main/java/build/buf/protovalidate/ValidatorImpl.java b/src/main/java/build/buf/protovalidate/ValidatorImpl.java index 4bc4f521b..d85282505 100644 --- a/src/main/java/build/buf/protovalidate/ValidatorImpl.java +++ b/src/main/java/build/buf/protovalidate/ValidatorImpl.java @@ -60,7 +60,7 @@ public ValidationResult validate(ValidateMessage message) throws ValidationExcep Evaluator evaluator = evaluatorBuilder.load(message.getDescriptorForType()); List result; try { - result = evaluator.evaluate(new ValidateMessageValue(message), this.failFast); + result = evaluator.evaluate(new MessageValue(message), this.failFast); } catch (IllegalArgumentException e) { // A CEL rule that reads a field of the wrong type already reports it as an // ExecutionException, so a native rule that reads it first does the same. diff --git a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java index a351c4be0..0e657aba4 100644 --- a/src/test/java/build/buf/protovalidate/ValidateMessageTest.java +++ b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java @@ -336,7 +336,7 @@ public void valueUnsupportedOnMessageValue() throws Exception { Descriptors.Descriptor addressDescriptor = descriptor.findFieldByName("address").getMessageType(); - Value messageValue = new ValidateMessageValue(address(addressDescriptor, "Main Street")); + Value messageValue = new MessageValue(address(addressDescriptor, "Main Street")); assertThatThrownBy(() -> messageValue.value(Object.class)) .isInstanceOf(UnsupportedOperationException.class) .hasMessageContaining("value(Class) returns a scalar for native rule evaluation") From 531dae20f5e884d2f3f416df48901a28c52efdc8 Mon Sep 17 00:00:00 2001 From: Jon Bodner Date: Fri, 4 Dec 2026 12:10:19 -0500 Subject: [PATCH 22/23] Restore main's code where the change wasn't needed ProtoAdapter already returns enums as long, so ObjectValue and EnumEvaluator need no enum handling of their own. ObjectValue creates its message wrapper lazily, so it no longer needs to skip repeated fields, and OneofEvaluator and WrappedValueEvaluator only needed the type change. --- src/main/java/build/buf/protovalidate/EnumEvaluator.java | 4 ++-- src/main/java/build/buf/protovalidate/ObjectValue.java | 4 ---- src/main/java/build/buf/protovalidate/OneofEvaluator.java | 6 +----- .../java/build/buf/protovalidate/WrappedValueEvaluator.java | 5 +++-- 4 files changed, 6 insertions(+), 13 deletions(-) diff --git a/src/main/java/build/buf/protovalidate/EnumEvaluator.java b/src/main/java/build/buf/protovalidate/EnumEvaluator.java index d8dfd6b6c..d2fa00df4 100644 --- a/src/main/java/build/buf/protovalidate/EnumEvaluator.java +++ b/src/main/java/build/buf/protovalidate/EnumEvaluator.java @@ -77,11 +77,11 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - Number enumValue = val.value(Number.class); + Object enumValue = val.value(Object.class); if (enumValue == null) { return RuleViolation.NO_VIOLATIONS; } - if (!values.contains(enumValue.longValue())) { + if (!values.contains(enumValue)) { return Collections.singletonList( RuleViolation.newBuilder() .addAllRulePathElements(helper.getRulePrefixElements()) diff --git a/src/main/java/build/buf/protovalidate/ObjectValue.java b/src/main/java/build/buf/protovalidate/ObjectValue.java index fd4449434..27e5cbc30 100644 --- a/src/main/java/build/buf/protovalidate/ObjectValue.java +++ b/src/main/java/build/buf/protovalidate/ObjectValue.java @@ -58,7 +58,6 @@ public Descriptors.FieldDescriptor fieldDescriptor() { @Override public ValidateMessage messageValue() { if (message == null - && !fieldDescriptor.isRepeated() && fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { message = new ProtobufValidateMessage((Message) value); } @@ -72,9 +71,6 @@ public Object celValue() { @Override public T value(Class clazz) { - if (value instanceof Descriptors.EnumValueDescriptor) { - return clazz.cast((long) ((Descriptors.EnumValueDescriptor) value).getNumber()); - } return clazz.cast(ProtoAdapter.toCel(fieldDescriptor, value)); } diff --git a/src/main/java/build/buf/protovalidate/OneofEvaluator.java b/src/main/java/build/buf/protovalidate/OneofEvaluator.java index 8a16323ab..b42085cfa 100644 --- a/src/main/java/build/buf/protovalidate/OneofEvaluator.java +++ b/src/main/java/build/buf/protovalidate/OneofEvaluator.java @@ -48,11 +48,7 @@ public boolean tautology() { public List evaluate(Value val, boolean failFast) throws ExecutionException { ValidateMessage message = val.messageValue(); - if (message == null) { - return RuleViolation.NO_VIOLATIONS; - } - boolean hasField = message.getOneofFieldDescriptor(descriptor) != null; - if (!required || hasField) { + if (message == null || !required || (message.getOneofFieldDescriptor(descriptor) != null)) { return RuleViolation.NO_VIOLATIONS; } return Collections.singletonList( diff --git a/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java b/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java index b767c1318..3afdb59f5 100644 --- a/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java +++ b/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java @@ -16,6 +16,7 @@ import build.buf.protovalidate.exceptions.ExecutionException; import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Message; import java.util.List; /** @@ -25,8 +26,8 @@ * *

    CEL's runtime auto-unwraps wrappers to their inner primitive type, so the CEL path doesn't * need this adapter. Native evaluators expect the underlying scalar (e.g. {@code Long} for {@code - * Int64Value.value}); without unwrapping they'd see the wrapper message and misbehave. Mirrors - * {@code wrappedValueEval} in protovalidate-go's {@code builder.go}. + * Int64Value.value}); without unwrapping they'd see the wrapper {@link Message} and misbehave. + * Mirrors {@code wrappedValueEval} in protovalidate-go's {@code builder.go}. * *

    The wrapped evaluator's {@link RuleBase} is constructed against the OUTER wrapper field's * {@code ValueEvaluator}, so violation field paths point at the user's wrapper-typed field rather From 1451931efa584d6028150ea0b9e78a09a73cd372 Mon Sep 17 00:00:00 2001 From: Jon Bodner Date: Fri, 4 Dec 2026 12:30:58 -0500 Subject: [PATCH 23/23] Return null from ObjectValue.messageValue for collections Value.messageValue promises null for repeated and map fields, as PlainValue returns, but ObjectValue cast the list to Message and threw ClassCastException. Also describe what rawValue returns, in place of a reference to a type table that doesn't exist. --- .../build/buf/protovalidate/ObjectValue.java | 1 + .../java/build/buf/protovalidate/Value.java | 4 +++- .../buf/protovalidate/PlainValueTest.java | 22 +++++++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/main/java/build/buf/protovalidate/ObjectValue.java b/src/main/java/build/buf/protovalidate/ObjectValue.java index 27e5cbc30..5ba7ab491 100644 --- a/src/main/java/build/buf/protovalidate/ObjectValue.java +++ b/src/main/java/build/buf/protovalidate/ObjectValue.java @@ -58,6 +58,7 @@ public Descriptors.FieldDescriptor fieldDescriptor() { @Override public ValidateMessage messageValue() { if (message == null + && !fieldDescriptor.isRepeated() && fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { message = new ProtobufValidateMessage((Message) value); } diff --git a/src/main/java/build/buf/protovalidate/Value.java b/src/main/java/build/buf/protovalidate/Value.java index 705d53c06..9dd4dd1ec 100644 --- a/src/main/java/build/buf/protovalidate/Value.java +++ b/src/main/java/build/buf/protovalidate/Value.java @@ -42,7 +42,9 @@ interface Value { @Nullable ValidateMessage messageValue(); /** - * Returns the raw representation specified in the {@link Value} type table for native rules. + * Get the underlying value without CEL conversion. For protobuf-java messages, this is the value + * as protobuf-java provides it. For other runtimes, it is the plain value from {@link + * ValidateMessage#getField}, or the protobuf default when the field is unset. * * @return The non-null raw value. */ diff --git a/src/test/java/build/buf/protovalidate/PlainValueTest.java b/src/test/java/build/buf/protovalidate/PlainValueTest.java index 01da58bf8..66b5c601d 100644 --- a/src/test/java/build/buf/protovalidate/PlainValueTest.java +++ b/src/test/java/build/buf/protovalidate/PlainValueTest.java @@ -71,6 +71,28 @@ public void rejectsWrongType(FieldDescriptor field, Object value, String expecte .hasMessageContaining(value.getClass().getName()); } + // Value.messageValue() promises null for collections, and the two implementations must agree. + @Test + public void messageValueIsNullForCollections() { + FieldDescriptor repeated = field(DescriptorProto.getDescriptor(), "field"); + FieldDescriptor map = field(Struct.getDescriptor(), "fields"); + DescriptorProto withField = + DescriptorProto.newBuilder().addField(FieldDescriptorProto.getDefaultInstance()).build(); + Struct withEntry = + Struct.newBuilder().putFields("k", com.google.protobuf.Value.getDefaultInstance()).build(); + + assertThat(new ObjectValue(repeated, withField.getField(repeated)).messageValue()).isNull(); + assertThat(new ObjectValue(map, withEntry.getField(map)).messageValue()).isNull(); + assertThat(new PlainValue(repeated, Collections.emptyList(), false).messageValue()).isNull(); + assertThat(new PlainValue(map, Collections.emptyMap(), false).messageValue()).isNull(); + assertThat( + new ObjectValue( + field(FieldDescriptorProto.getDescriptor(), "options"), + FieldOptions.getDefaultInstance()) + .messageValue()) + .isNotNull(); + } + @Test public void rejectsWrongElementType() { FieldDescriptor field = field(DescriptorProto.getDescriptor(), "reserved_name");