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/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/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; + } +} diff --git a/src/main/java/build/buf/protovalidate/AnyEvaluator.java b/src/main/java/build/buf/protovalidate/AnyEvaluator.java index d7d18356d..6f4425197 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).value(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/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/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/EvaluatorBuilder.java b/src/main/java/build/buf/protovalidate/EvaluatorBuilder.java index 9ef0c48d8..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 MessageValue(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/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..a35b4f755 100644 --- a/src/main/java/build/buf/protovalidate/ListElementValue.java +++ b/src/main/java/build/buf/protovalidate/ListElementValue.java @@ -29,6 +29,9 @@ final class ListElementValue implements Value { /** Object type since the object type is inferred from the field descriptor. */ private final Object value; + // 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. */ @@ -45,11 +48,17 @@ final class ListElementValue implements Value { } @Override - public @Nullable Message messageValue() { - if (fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { - return (Message) value; + public @Nullable ValidateMessage messageValue() { + if (message == null + && fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { + message = new ProtobufValidateMessage((Message) value); } - return null; + return message; + } + + @Override + public Object celValue() { + return ProtoAdapter.scalarToCel(fieldDescriptor.getType(), value); } @Override diff --git a/src/main/java/build/buf/protovalidate/MapRulesEvaluator.java b/src/main/java/build/buf/protovalidate/MapRulesEvaluator.java index 39455b9e8..2e7bc64da 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; /** @@ -96,10 +97,10 @@ 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. - List entries = (List) val.rawValue(); - long size = entries.size(); + // 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; 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..78ae8ffe2 100644 --- a/src/main/java/build/buf/protovalidate/MessageValue.java +++ b/src/main/java/build/buf/protovalidate/MessageValue.java @@ -15,24 +15,22 @@ 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}. */ +/** The {@link Value} type that contains a {@link ValidateMessage}. */ final class MessageValue implements Value { - /** Object type since the object type is inferred from the field descriptor. */ - private final Object value; + private final ValidateMessage value; /** * Constructs a {@link MessageValue} with the provided message value. * * @param value The message value. */ - MessageValue(Message value) { + MessageValue(ValidateMessage value) { this.value = value; } @@ -42,13 +40,20 @@ final class MessageValue implements Value { } @Override - public Message messageValue() { - return (Message) value; + public ValidateMessage messageValue() { + return value; + } + + @Override + public Object celValue() { + return ValidateMessages.cel(value); } @Override public T value(Class clazz) { - return clazz.cast(value); + throw new UnsupportedOperationException( + "value(Class) returns a 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..5ba7ab491 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; @@ -35,6 +35,9 @@ final class ObjectValue implements Value { /** Object type since the object type is inferred from the field descriptor. */ private final Object value; + // Created on first use, because most evaluators never ask for the message wrapper. + private @Nullable ProtobufValidateMessage message; + /** * Constructs a new {@link ObjectValue}. * @@ -53,11 +56,18 @@ public Descriptors.FieldDescriptor fieldDescriptor() { @Nullable @Override - public Message messageValue() { - if (fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { - return (Message) value; + public ValidateMessage messageValue() { + if (message == null + && !fieldDescriptor.isRepeated() + && fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE) { + message = new ProtobufValidateMessage((Message) value); } - return null; + return message; + } + + @Override + public Object celValue() { + return ProtoAdapter.toCel(fieldDescriptor, value); } @Override @@ -91,7 +101,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/OneofEvaluator.java b/src/main/java/build/buf/protovalidate/OneofEvaluator.java index 5ddccd6d6..b42085cfa 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,7 +47,7 @@ public boolean tautology() { @Override public List evaluate(Value val, boolean failFast) throws ExecutionException { - Message message = val.messageValue(); + ValidateMessage message = val.messageValue(); if (message == null || !required || (message.getOneofFieldDescriptor(descriptor) != null)) { return RuleViolation.NO_VIOLATIONS; } 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..c03be4c7a --- /dev/null +++ b/src/main/java/build/buf/protovalidate/PlainValue.java @@ -0,0 +1,308 @@ +// 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.Descriptors.FieldDescriptor.JavaType; +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; + +/** + * {@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; + checkType(); + } + + // 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; + } + 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; + } + 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(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"); + } + } + } + + 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); + } + } + + 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: + 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 + public FieldDescriptor fieldDescriptor() { + return field; + } + + @Override + public @Nullable ValidateMessage messageValue() { + return isMessage() ? message() : null; + } + + @Override + public Object rawValue() { + if (isList()) { + return field.getJavaType() == JavaType.ENUM ? enumNumbers() : 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); + // 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), + 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 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.value(Object.class)); + } + return clazz.cast(out); + } + if (isMap()) { + Map out = new HashMap<>(); + for (Map.Entry entry : mapValue().entrySet()) { + out.put(entry.getKey().value(Object.class), entry.getValue().value(Object.class)); + } + return clazz.cast(out); + } + if (isMessage()) { + return clazz.cast(element ? message() : timeOrMessage(message())); + } + return clazz.cast(scalarCel()); + } + + private static Object timeOrMessage(ValidateMessage message) { + Object time = ValidateMessages.time(message); + return time != null ? time : message; + } + + 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; + } + + // 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; + } + + private ValidateMessage message() { + if (value == null) { + return new EmptyValidateMessage(field.getMessageType()); + } + return (ValidateMessage) value; + } + + private Object scalar() { + if (field.getJavaType() == JavaType.ENUM) { + Object number = value == null ? field.getDefaultValue() : value; + return number instanceof EnumValueDescriptor + ? ((EnumValueDescriptor) number).getNumber() + : number; + } + return value != null ? value : 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/ProtobufCopies.java b/src/main/java/build/buf/protovalidate/ProtobufCopies.java new file mode 100644 index 000000000..3319d9b3b --- /dev/null +++ b/src/main/java/build/buf/protovalidate/ProtobufCopies.java @@ -0,0 +1,110 @@ +// 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.CodedInputStream; +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. + // 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(input); + } catch (InvalidProtocolBufferException e) { + throw new IllegalArgumentException( + "can't copy " + message.getDescriptorForType().getFullName() + ": " + e.getMessage(), 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/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/ValidateMessage.java b/src/main/java/build/buf/protovalidate/ValidateMessage.java new file mode 100644 index 000000000..143cb0d6d --- /dev/null +++ b/src/main/java/build/buf/protovalidate/ValidateMessage.java @@ -0,0 +1,100 @@ +// 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.Descriptors.OneofDescriptor; +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. + */ +public interface ValidateMessage { + /** + * The {@link Descriptor} of the wrapped message's type. + * + * @return The descriptor. + */ + Descriptor getDescriptorForType(); + + /** + * Whether the field is populated. Repeated and map fields are populated when non-empty. Fields + * with explicit presence are populated when set, including a set default value. Other scalar + * fields are populated when their value differs from the protobuf default. + * + * @param field The field descriptor to check for. + * @return Whether the field is present. + */ + boolean hasField(FieldDescriptor field); + + /** + * Returns the populated member of a oneof, or null when no member is set. + * + * @param oneof The oneof to inspect. + * @return The populated field descriptor, or null. + */ + default @Nullable FieldDescriptor getOneofFieldDescriptor(OneofDescriptor oneof) { + for (FieldDescriptor field : oneof.getFields()) { + if (hasField(field)) { + return field; + } + } + return null; + } + + /** + * Whether the message has no populated fields. Implementations retaining extensions or unknown + * fields must override this method to include them in the emptiness check. + * + * @return Whether the message is empty. + */ + default boolean isEmpty() { + for (FieldDescriptor field : getDescriptorForType().getFields()) { + if (hasField(field)) { + return false; + } + } + return true; + } + + /** + * Returns the plain Java value of a field, or null when the field is unset. The validator + * substitutes the protobuf default for unset fields and does all conversion for CEL itself. + * + *

Singular values use these types. Unsigned integers use the signed type with the same bits. + * + *

    + *
  • 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}. If a value has a different type, validation fails with an exception that names + * the field. + * + * @param field The field descriptor for which to retrieve a value. + * @return The field's value, or null when the field is unset. + */ + @Nullable Object getField(FieldDescriptor field); +} 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..c42566ebb --- /dev/null +++ b/src/main/java/build/buf/protovalidate/ValidateMessageStruct.java @@ -0,0 +1,197 @@ +// 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 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.HashMap; +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}, + * 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; + // 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; + 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 ValidateMessageStruct value() { + return this; + } + + @Override + public boolean isZeroValue() { + return message.isEmpty(); + } + + @Override + public CelType celType() { + return StructTypeReference.create(descriptor.getFullName()); + } + + @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() + && 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(); + } + + @Override + public boolean equals(@Nullable Object other) { + ValidateMessage that = asMessage(other); + return that != null && contentEquals(message, that); + } + + @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; + } + + // 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).message; + } + if (value instanceof Message) { + return new ProtobufValidateMessage((Message) value); + } + return null; + } + + // 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; + } + 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; + } + } + 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 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; + List rightList = (List) right; + if (leftList.size() != rightList.size()) { + return false; + } + for (int i = 0; i < leftList.size(); i++) { + if (!plainEquals(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()) + || !plainEquals(entry.getValue(), rightMap.get(entry.getKey()))) { + return false; + } + } + return true; + } + 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/ValidateMessages.java b/src/main/java/build/buf/protovalidate/ValidateMessages.java new file mode 100644 index 000000000..e60104b1f --- /dev/null +++ b/src/main/java/build/buf/protovalidate/ValidateMessages.java @@ -0,0 +1,103 @@ +// 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.DateTimeException; +import java.time.Duration; +import java.time.Instant; +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 { + 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(); + } + Object time = time(message); + if (time != null) { + return time; + } + Descriptor descriptor = message.getDescriptorForType(); + 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")); + } + 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); + } + return null; + } + + 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 449abef73..f9151a11d 100644 --- a/src/main/java/build/buf/protovalidate/Validator.java +++ b/src/main/java/build/buf/protovalidate/Validator.java @@ -35,4 +35,18 @@ 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 ValidateMessage}. Used by alternative protobuf + * runtimes that reflect over their own message types via this interface rather than going through + * a {@link Message}. The default implementation throws {@link ValidationException} when this + * overload is unsupported. + * + * @param message the {@link ValidateMessage} view of the message to validate. + * @return the {@link ValidationResult} from the evaluation. + * @throws ValidationException if there are any compilation or validation execution errors. + */ + default ValidationResult validate(ValidateMessage message) throws ValidationException { + throw new ValidationException("ValidateMessage validation is unsupported"); + } } diff --git a/src/main/java/build/buf/protovalidate/ValidatorImpl.java b/src/main/java/build/buf/protovalidate/ValidatorImpl.java index 39613c9f8..d85282505 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; @@ -48,9 +49,28 @@ 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; + try { + 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. + 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/main/java/build/buf/protovalidate/Value.java b/src/main/java/build/buf/protovalidate/Value.java index a2bb96b29..9dd4dd1ec 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,19 @@ 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. + * 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. * - * @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 +62,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(); + + /** + * 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 + * 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 value(Class clazz); } diff --git a/src/main/java/build/buf/protovalidate/ValueEvaluator.java b/src/main/java/build/buf/protovalidate/ValueEvaluator.java index 433da1c40..bcb61d255 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,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.value(Object.class); + if (zero instanceof Long && value instanceof Number) { + return ((Number) value).longValue() == (Long) 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..3afdb59f5 100644 --- a/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java +++ b/src/main/java/build/buf/protovalidate/WrappedValueEvaluator.java @@ -58,12 +58,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/MapValidateMessage.java b/src/test/java/build/buf/protovalidate/MapValidateMessage.java new file mode 100644 index 000000000..68312434a --- /dev/null +++ b/src/test/java/build/buf/protovalidate/MapValidateMessage.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.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; + +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 LinkedHashMap<>(); + 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/PlainValueTest.java b/src/test/java/build/buf/protovalidate/PlainValueTest.java new file mode 100644 index 000000000..66b5c601d --- /dev/null +++ b/src/test/java/build/buf/protovalidate/PlainValueTest.java @@ -0,0 +1,122 @@ +// 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()); + } + + // 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"); + assertThatThrownBy(() -> new PlainValue(field, Collections.singletonList(1), false)) + .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/ValidateMessageCelCollectionTest.java b/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java new file mode 100644 index 000000000..72595eb4c --- /dev/null +++ b/src/test/java/build/buf/protovalidate/ValidateMessageCelCollectionTest.java @@ -0,0 +1,465 @@ +// 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.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; +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; + +/** 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("[]"); + } + + // 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()); + } + + // 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() { + 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 = + 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)) + .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")) + .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( + FileDescriptorProto.newBuilder() + .setName("cel_collections.proto") + .setPackage("test.v1") + .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(), + TimestampProto.getDescriptor(), + DurationProto.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"); + } +} 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..032869a3d --- /dev/null +++ b/src/test/java/build/buf/protovalidate/ValidateMessageDefaultsTest.java @@ -0,0 +1,312 @@ +// 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.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; +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.time.Instant; +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; + +/** 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); + } + + // 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() + .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_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) + .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..14cfb85d6 --- /dev/null +++ b/src/test/java/build/buf/protovalidate/ValidateMessageRulesTest.java @@ -0,0 +1,261 @@ +// 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"); + 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}") + @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"); + } + + // 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"); + } + + // 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()) + .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))))) + .addField( + field("child", 4, FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".test.v1.Rules")) + .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 new file mode 100644 index 000000000..0e657aba4 --- /dev/null +++ b/src/test/java/build/buf/protovalidate/ValidateMessageTest.java @@ -0,0 +1,860 @@ +// 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.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.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 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; + +/** + * 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 { + 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 customRulesDoNotReadMessagesAsScalars( + 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 + // 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(ValidationException.class) + .hasMessageContaining("address") + .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 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 MessageValue(address(addressDescriptor, "Main Street")); + assertThatThrownBy(() -> messageValue.value(Object.class)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("value(Class) returns a 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) { + 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 + public @Nullable Object getField(Descriptors.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..8640a0cb7 --- /dev/null +++ b/src/test/java/build/buf/protovalidate/ValidateMessageWellKnownTypesTest.java @@ -0,0 +1,322 @@ +// 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.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; + +/** 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); + } + + // 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"; + 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(); + } +} 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..b9417c521 --- /dev/null +++ b/src/test/java/build/buf/protovalidate/external/ExternalRuntimeTest.java @@ -0,0 +1,511 @@ +// 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.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.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 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; + +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 @Nullable Object getField(FieldDescriptor field) { + return fields.get(field.getName()); + } + } +}