From fe2499041b1e58a1a4fffe385f8142468c23473d Mon Sep 17 00:00:00 2001 From: Sean Huh Date: Tue, 24 Nov 2026 13:19:46 -0800 Subject: [PATCH] Support protobuf types in the cel-verifier REPL PiperOrigin-RevId: 1029294329 --- .../cel/verifier/tools/CelVerifierRepl.java | 39 +++++++---- .../cel/verifier/tools/CelVerifierTool.java | 66 ++++++++++++------- .../verifier/tools/CelVerifierReplTest.java | 31 ++++++++- .../verifier/tools/CelVerifierToolTest.java | 27 +++++++- verifier/tools/README.md | 3 + 5 files changed, 128 insertions(+), 38 deletions(-) diff --git a/verifier/src/main/java/dev/cel/verifier/tools/CelVerifierRepl.java b/verifier/src/main/java/dev/cel/verifier/tools/CelVerifierRepl.java index 902903b89..ae7a1f89f 100644 --- a/verifier/src/main/java/dev/cel/verifier/tools/CelVerifierRepl.java +++ b/verifier/src/main/java/dev/cel/verifier/tools/CelVerifierRepl.java @@ -18,6 +18,8 @@ import com.google.common.base.Ascii; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; +import com.google.protobuf.Descriptors.FileDescriptor; import dev.cel.common.CelValidationException; import dev.cel.common.types.CelType; import dev.cel.common.types.CelTypes; @@ -43,11 +45,9 @@ /** Interactive REPL shell for CEL formal verification. */ final class CelVerifierRepl { - private static final VerificationOptions DEFAULT_OPTIONS = VerificationOptions.builder().build(); - private CelVerifierRepl() {} - static int runInteractiveRepl() { + static int runInteractiveRepl(ImmutableSet fileDescriptors) { LineReader lineReader = null; BufferedReader fallbackReader = null; try { @@ -60,15 +60,25 @@ static int runInteractiveRepl() { } catch (Exception e) { fallbackReader = new BufferedReader(new InputStreamReader(System.in, UTF_8)); } - return runReplInternal(lineReader, fallbackReader, System.out, System.err); + return runReplInternal(fileDescriptors, lineReader, fallbackReader, System.out, System.err); } - static int runRepl(BufferedReader reader, PrintStream out, PrintStream err) { - return runReplInternal(null, reader, out, err); + static int runRepl( + ImmutableSet fileDescriptors, + BufferedReader reader, + PrintStream out, + PrintStream err) { + return runReplInternal(fileDescriptors, null, reader, out, err); } private static int runReplInternal( - LineReader lineReader, BufferedReader fallbackReader, PrintStream out, PrintStream err) { + ImmutableSet fileDescriptors, + LineReader lineReader, + BufferedReader fallbackReader, + PrintStream out, + PrintStream err) { + VerificationOptions typeOptions = + VerificationOptions.builder().setFileDescriptors(fileDescriptors).build(); out.println("============================================================"); out.println(" CEL Verification REPL"); out.println(" Type :help for commands, :quit to exit."); @@ -140,7 +150,7 @@ private static int runReplInternal( err.println( "Usage: :var (e.g. :var role string, :var scores map)"); } else { - handleVarCommand(arg, sessionVars, out, err); + handleVarCommand(arg, typeOptions, sessionVars, out, err); } continue; } @@ -209,6 +219,7 @@ private static int runReplInternal( .setTimeout(Duration.ofSeconds(timeoutSeconds)) .setComprehensionUnrollLimit(unrollLimit) .setUnknownIdentifiers(unknownIdentifiers) + .setFileDescriptors(fileDescriptors) .build(); try { @@ -275,7 +286,11 @@ private static int runReplInternal( } private static void handleVarCommand( - String arg, Map sessionVars, PrintStream out, PrintStream err) { + String arg, + VerificationOptions typeOptions, + Map sessionVars, + PrintStream out, + PrintStream err) { String[] parts = arg.split("\\s+", 2); if (parts.length != 2) { err.println("Usage: :var (e.g. :var role string, :var scores map)"); @@ -283,7 +298,7 @@ private static void handleVarCommand( } String name = parts[0].trim(); try { - CelType type = DEFAULT_OPTIONS.parseCelType(parts[1]); + CelType type = typeOptions.parseCelType(parts[1]); sessionVars.put(name, type); out.println("Variable declared: " + name + " : " + CelTypes.format(type)); } catch (IllegalArgumentException | IllegalStateException e) { @@ -324,7 +339,9 @@ private static void printHelp(String topic, PrintStream out) { out.println( " - Optional types: optional_type (e.g., optional_type," + " optional_type)"); - out.println(" - Protobuf types: coming soon"); + out.println( + " - Protobuf types: message and enum names from repl --file_descriptor_set" + + " (enums are int)"); out.println(); out.println("Examples:"); out.println(" cel-verifier> :var role string"); diff --git a/verifier/src/main/java/dev/cel/verifier/tools/CelVerifierTool.java b/verifier/src/main/java/dev/cel/verifier/tools/CelVerifierTool.java index a4c8fe213..a6e075056 100644 --- a/verifier/src/main/java/dev/cel/verifier/tools/CelVerifierTool.java +++ b/verifier/src/main/java/dev/cel/verifier/tools/CelVerifierTool.java @@ -15,7 +15,9 @@ package dev.cel.verifier.tools; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; import com.google.protobuf.DescriptorProtos.FileDescriptorSet; +import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.ExtensionRegistry; import dev.cel.common.CelDescriptorUtil; import dev.cel.common.CelValidationException; @@ -38,6 +40,7 @@ import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.IVersionProvider; +import picocli.CommandLine.Mixin; import picocli.CommandLine.Model.CommandSpec; import picocli.CommandLine.Option; import picocli.CommandLine.Spec; @@ -76,6 +79,28 @@ public void run() { spec.commandLine().usage(spec.commandLine().getOut()); } + /** The protobuf descriptor set option, shared by all commands. */ + static final class DescriptorSetOption { + @Option( + names = {"--file_descriptor_set", "--transitive_descriptor_set"}, + description = "Path to a FileDescriptorSet with the protobuf types used by variables") + String path = ""; + + ImmutableSet load() throws IOException { + if (path.isEmpty()) { + return ImmutableSet.of(); + } + try { + return CelDescriptorUtil.getFileDescriptorsFromFileDescriptorSet( + FileDescriptorSet.parseFrom( + Files.readAllBytes(new File(path).toPath()), ExtensionRegistry.getEmptyRegistry())); + } catch (IOException | RuntimeException e) { + throw new IOException( + "Failed to read file descriptor set '" + path + "': " + e.getMessage(), e); + } + } + } + /** Options shared across all verification commands. */ abstract static class BaseVerificationCommand implements Callable { @@ -120,10 +145,7 @@ PrintWriter err() { description = "Output format: TEXT or JSON (default: TEXT)") String outputFormatStr = VerificationOptions.DEFAULT_OUTPUT_FORMAT.name(); - @Option( - names = {"--file_descriptor_set", "--transitive_descriptor_set"}, - description = "Path to a FileDescriptorSet with the protobuf types used by variables") - String fileDescriptorSetPath = ""; + @Mixin DescriptorSetOption descriptorSet = new DescriptorSetOption(); @FunctionalInterface protected interface CommandAction { @@ -158,24 +180,13 @@ protected VerificationOptions getOptions() throws IOException { } catch (IllegalArgumentException e) { err().println("Invalid output format '" + outputFormatStr + "'. Defaulting to TEXT."); } - VerificationOptions.Builder builder = - VerificationOptions.builder() - .setTimeout(Duration.ofSeconds(timeoutSeconds)) - .setComprehensionUnrollLimit(comprehensionUnrollLimit) - .setUnknownIdentifiers(unknownIdentifiers) - .setOutputFormat(format); - if (!fileDescriptorSetPath.isEmpty()) { - try { - builder.setFileDescriptors( - CelDescriptorUtil.getFileDescriptorsFromFileDescriptorSet( - FileDescriptorSet.parseFrom( - Files.readAllBytes(new File(fileDescriptorSetPath).toPath()), - ExtensionRegistry.getEmptyRegistry()))); - } catch (IOException e) { - throw new IOException("Failed to read file descriptor set: " + fileDescriptorSetPath, e); - } - } - return builder.build(); + return VerificationOptions.builder() + .setTimeout(Duration.ofSeconds(timeoutSeconds)) + .setComprehensionUnrollLimit(comprehensionUnrollLimit) + .setUnknownIdentifiers(unknownIdentifiers) + .setOutputFormat(format) + .setFileDescriptors(descriptorSet.load()) + .build(); } protected int handleSingleResult(CelVerificationResult result, OutputFormat format) { @@ -321,9 +332,18 @@ private static int getPolicyExitCode(ImmutableMap @Command(name = "repl", description = "Launch interactive CEL Formal Verification REPL shell") static class ReplCommand implements Callable { + @Spec private CommandSpec spec; + + @Mixin DescriptorSetOption descriptorSet = new DescriptorSetOption(); + @Override public Integer call() { - return CelVerifierRepl.runInteractiveRepl(); + try { + return CelVerifierRepl.runInteractiveRepl(descriptorSet.load()); + } catch (IOException e) { + spec.commandLine().getErr().println(e.getMessage()); + return EXIT_CODE_ERROR; + } } } diff --git a/verifier/src/test/java/dev/cel/verifier/tools/CelVerifierReplTest.java b/verifier/src/test/java/dev/cel/verifier/tools/CelVerifierReplTest.java index 3e7a9eccf..5462963f3 100644 --- a/verifier/src/test/java/dev/cel/verifier/tools/CelVerifierReplTest.java +++ b/verifier/src/test/java/dev/cel/verifier/tools/CelVerifierReplTest.java @@ -17,6 +17,9 @@ import static com.google.common.truth.Truth.assertThat; import static java.nio.charset.StandardCharsets.UTF_8; +import com.google.common.collect.ImmutableSet; +import com.google.protobuf.Descriptors.FileDescriptor; +import dev.cel.expr.conformance.proto3.TestAllTypes; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.PrintStream; @@ -34,8 +37,13 @@ public void setUp() { System.setProperty("z3.skipLibraryLoad", "true"); } - @SuppressWarnings({"PreferCharsetOverload", "JdkObsolete"}) private String[] runReplWithCommands(String... commands) throws Exception { + return runReplWithCommands(ImmutableSet.of(), commands); + } + + @SuppressWarnings({"PreferCharsetOverload", "JdkObsolete"}) + private String[] runReplWithCommands( + ImmutableSet fileDescriptors, String... commands) throws Exception { String input = String.join("\n", commands) + "\n"; BufferedReader reader = new BufferedReader(new StringReader(input)); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); @@ -43,13 +51,30 @@ private String[] runReplWithCommands(String... commands) throws Exception { PrintStream out = new PrintStream(outStream, true, UTF_8.name()); PrintStream err = new PrintStream(errStream, true, UTF_8.name()); - CelVerifierRepl.runRepl(reader, out, err); + CelVerifierRepl.runRepl(fileDescriptors, reader, out, err); return new String[] { new String(outStream.toByteArray(), UTF_8), new String(errStream.toByteArray(), UTF_8) }; } + @Test + public void repl_protoTypesFromDescriptorSet() throws Exception { + String[] output = + runReplWithCommands( + ImmutableSet.of(TestAllTypes.getDescriptor().getFile()), + ":var msg cel.expr.conformance.proto3.TestAllTypes", + ":var e cel.expr.conformance.proto3.TestAllTypes.NestedEnum", + "valid has(msg.single_nested_message) || msg.single_nested_message.bb == 0", + ":quit"); + + assertThat(output[0]) + .contains("Variable declared: msg : cel.expr.conformance.proto3.TestAllTypes"); + assertThat(output[0]).contains("Variable declared: e : int"); + assertThat(output[0]).contains("[VERIFIED]"); + assertThat(output[1]).isEmpty(); + } + @Test public void repl_quitAndExit() throws Exception { String[] output1 = runReplWithCommands(":quit"); @@ -86,7 +111,7 @@ public void repl_helpCommands() throws Exception { assertThat(output[0]).contains("Query: equiv <=> "); assertThat(output[0]).contains("Well-known types: timestamp, duration"); assertThat(output[0]).contains("Optional types: optional_type"); - assertThat(output[0]).contains("Protobuf types: coming soon"); + assertThat(output[0]).contains("Protobuf types: message and enum names"); } @Test diff --git a/verifier/src/test/java/dev/cel/verifier/tools/CelVerifierToolTest.java b/verifier/src/test/java/dev/cel/verifier/tools/CelVerifierToolTest.java index 79262233b..d56606ff5 100644 --- a/verifier/src/test/java/dev/cel/verifier/tools/CelVerifierToolTest.java +++ b/verifier/src/test/java/dev/cel/verifier/tools/CelVerifierToolTest.java @@ -19,6 +19,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import com.google.protobuf.DescriptorProtos.FileDescriptorProto; import com.google.protobuf.DescriptorProtos.FileDescriptorSet; import dev.cel.common.types.CelType; import dev.cel.common.types.ListType; @@ -133,7 +134,31 @@ public void celVerifierTool_missingFileDescriptorSet_error() { assertThat(output) .contains( - "Verification error: Failed to read file descriptor set: missing_descriptor_set.pb"); + "Verification error: Failed to read file descriptor set 'missing_descriptor_set.pb'"); + } + + @Test + public void celVerifierTool_repl_withFileDescriptorSet_exitsAtEndOfInput() throws Exception { + int exitCode = + new CommandLine(new CelVerifierTool()) + .execute("repl", "--file_descriptor_set", writeTestAllTypesDescriptorSet()); + + assertThat(exitCode).isEqualTo(CelVerifierTool.EXIT_CODE_VERIFIED); + } + + @Test + public void celVerifierTool_repl_unresolvedFileDescriptorSet_error() throws Exception { + File file = tempFolder.newFile("unresolved.pb"); + Files.write( + file.toPath(), + FileDescriptorSet.newBuilder() + .addFile(FileDescriptorProto.newBuilder().setName("a.proto").addDependency("b.proto")) + .build() + .toByteArray()); + + String output = executeToolWithOutput("repl", "--file_descriptor_set", file.getAbsolutePath()); + + assertThat(output).contains("unresolved proto file: b.proto"); } @Test diff --git a/verifier/tools/README.md b/verifier/tools/README.md index e37b02b16..18937d188 100644 --- a/verifier/tools/README.md +++ b/verifier/tools/README.md @@ -159,6 +159,9 @@ parameters for every query. bazel run //verifier/tools:cel_verifier_tool -- repl ``` +Pass `--file_descriptor_set ` to `repl` to declare protobuf message and +enum variables with `:var`. + ### REPL Commands | Command | Description | Example |