Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
5624a94
Introduce MessageReflector to enable alternative protobuf runtimes
andrewparmet Jun 14, 2026
7ae533c
Merge branch 'main' into pv-message-reflector-pure
andrewparmet Jun 15, 2026
3788308
Apply spotless formatting
andrewparmet Jun 17, 2026
8ceebfd
Merge branch 'main' into pv-message-reflector-pure
andrewparmet Jun 17, 2026
ce25bd7
Rename MessageReflector to ValidateMessage
andrewparmet Jun 18, 2026
2d39522
Add ValidateMessage coverage tests
andrewparmet Jun 18, 2026
d703b9c
Merge remote-tracking branch 'upstream/main' into verify-validatemess…
andrewparmet Nov 30, 2026
e93bc74
Cover message-backed values during custom rule validation
andrewparmet Nov 30, 2026
7aa1222
Fix external runtime value contracts and validation overhead
andrewparmet Dec 1, 2026
df08d32
Keep cached message adapters immutable
andrewparmet Dec 1, 2026
90e5d3e
Use field descriptors to initialize message adapters
andrewparmet Dec 1, 2026
664b231
Return plain field values from ValidateMessage
jonbodner-buf Dec 2, 2026
4790d27
Validate other runtimes' messages by converting them to DynamicMessage
jonbodner-buf Dec 3, 2026
25b70c3
Revert "Validate other runtimes' messages by converting them to Dynam…
jonbodner-buf Dec 3, 2026
85720eb
Check plain field value types when wrapping them
jonbodner-buf Dec 3, 2026
ac4f2f7
Keep nested ValidateMessages readable and comparable in CEL
jonbodner-buf Dec 3, 2026
1608ecc
Give CEL protobuf-java copies of Any, Struct, Value and ListValue
jonbodner-buf Dec 3, 2026
1a36b3c
Match protobuf-java for defaults, violation values and errors
jonbodner-buf Dec 3, 2026
eecfd72
Check nested and element types and cache CEL field reads
jonbodner-buf Dec 3, 2026
9cc7a2a
Require nested descriptors and compare time fields by value
jonbodner-buf Dec 3, 2026
5819c2e
Run conformance through ValidateMessage
jonbodner-buf Dec 3, 2026
6df1cbc
Compare ValidateMessages by plain values
jonbodner-buf Dec 3, 2026
c5685a3
Merge branch 'main' into jonbodner-buf/validate-message-plain-values
jonbodner-buf Dec 4, 2026
b75e3d2
Drop the unused rule value and restore Value.value
jonbodner-buf Dec 4, 2026
792773b
Restore the MessageValue name
jonbodner-buf Dec 4, 2026
531dae2
Restore main's code where the change wasn't needed
jonbodner-buf Dec 4, 2026
1451931
Return null from ObjectValue.messageValue for collections
jonbodner-buf Dec 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, TestResult> resultsMap = new HashMap<>();
for (Map.Entry<String, Any> 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);
Expand All @@ -84,7 +86,10 @@ static TestConformanceResponse testConformance(TestConformanceRequest request) {
}

static TestResult testCase(
Validator validator, Map<String, Descriptors.Descriptor> fileDescriptors, Any testCase)
Validator validator,
Map<String, Descriptors.Descriptor> fileDescriptors,
Any testCase,
boolean validateMessage)
throws InvalidProtocolBufferException {
String fullName = testCase.getTypeUrl();
int slash = fullName.indexOf('/');
Expand All @@ -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();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Object, Object> 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<Object> 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;
}
}
5 changes: 2 additions & 3 deletions src/main/java/build/buf/protovalidate/AnyEvaluator.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -78,12 +77,12 @@ final class AnyEvaluator implements Evaluator {
@Override
public List<RuleViolation.Builder> evaluate(Value val, boolean failFast)
throws ExecutionException {
Message anyValue = val.messageValue();
ValidateMessage anyValue = val.messageValue();
if (anyValue == null) {
return RuleViolation.NO_VIOLATIONS;
}
List<RuleViolation.Builder> 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()
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/build/buf/protovalidate/CelPrograms.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public boolean tautology() {
@Override
public List<RuleViolation.Builder> evaluate(Value val, boolean failFast)
throws ExecutionException {
CelVariableResolver bindings = Variable.newThisVariable(val.value(Object.class));
CelVariableResolver bindings = Variable.newThisVariable(val.celValue());
List<RuleViolation.Builder> violations = new ArrayList<>();
for (CompiledProgram program : programs) {
RuleViolation.Builder violation = program.eval(val, bindings);
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/build/buf/protovalidate/CompiledProgram.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
43 changes: 43 additions & 0 deletions src/main/java/build/buf/protovalidate/EmptyValidateMessage.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
6 changes: 1 addition & 5 deletions src/main/java/build/buf/protovalidate/EvaluatorBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -647,11 +647,7 @@ private static List<CompiledProgram> 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);
}
Expand Down
19 changes: 3 additions & 16 deletions src/main/java/build/buf/protovalidate/FieldEvaluator.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -95,11 +94,11 @@ public List<RuleViolation.Builder> 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()
Expand All @@ -113,18 +112,6 @@ public List<RuleViolation.Builder> 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);
}
}
17 changes: 13 additions & 4 deletions src/main/java/build/buf/protovalidate/ListElementValue.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand All @@ -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
Expand Down
9 changes: 5 additions & 4 deletions src/main/java/build/buf/protovalidate/MapRulesEvaluator.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -96,10 +97,10 @@ public boolean tautology() {

@Override
public List<RuleViolation.Builder> 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<RuleViolation.Builder> violations = null;

if (minPairs != null && size < minPairs) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -45,13 +44,13 @@ public boolean tautology() {
@Override
public List<RuleViolation.Builder> 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++;
}
}
Expand Down
Loading
Loading