Skip to content

Commit fe24990

Browse files
l46kokcopybara-github
authored andcommitted
Support protobuf types in the cel-verifier REPL
PiperOrigin-RevId: 1029294329
1 parent e9a8fe0 commit fe24990

5 files changed

Lines changed: 128 additions & 38 deletions

File tree

‎verifier/src/main/java/dev/cel/verifier/tools/CelVerifierRepl.java‎

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818

1919
import com.google.common.base.Ascii;
2020
import com.google.common.collect.ImmutableList;
21+
import com.google.common.collect.ImmutableSet;
22+
import com.google.protobuf.Descriptors.FileDescriptor;
2123
import dev.cel.common.CelValidationException;
2224
import dev.cel.common.types.CelType;
2325
import dev.cel.common.types.CelTypes;
@@ -43,11 +45,9 @@
4345
/** Interactive REPL shell for CEL formal verification. */
4446
final class CelVerifierRepl {
4547

46-
private static final VerificationOptions DEFAULT_OPTIONS = VerificationOptions.builder().build();
47-
4848
private CelVerifierRepl() {}
4949

50-
static int runInteractiveRepl() {
50+
static int runInteractiveRepl(ImmutableSet<FileDescriptor> fileDescriptors) {
5151
LineReader lineReader = null;
5252
BufferedReader fallbackReader = null;
5353
try {
@@ -60,15 +60,25 @@ static int runInteractiveRepl() {
6060
} catch (Exception e) {
6161
fallbackReader = new BufferedReader(new InputStreamReader(System.in, UTF_8));
6262
}
63-
return runReplInternal(lineReader, fallbackReader, System.out, System.err);
63+
return runReplInternal(fileDescriptors, lineReader, fallbackReader, System.out, System.err);
6464
}
6565

66-
static int runRepl(BufferedReader reader, PrintStream out, PrintStream err) {
67-
return runReplInternal(null, reader, out, err);
66+
static int runRepl(
67+
ImmutableSet<FileDescriptor> fileDescriptors,
68+
BufferedReader reader,
69+
PrintStream out,
70+
PrintStream err) {
71+
return runReplInternal(fileDescriptors, null, reader, out, err);
6872
}
6973

7074
private static int runReplInternal(
71-
LineReader lineReader, BufferedReader fallbackReader, PrintStream out, PrintStream err) {
75+
ImmutableSet<FileDescriptor> fileDescriptors,
76+
LineReader lineReader,
77+
BufferedReader fallbackReader,
78+
PrintStream out,
79+
PrintStream err) {
80+
VerificationOptions typeOptions =
81+
VerificationOptions.builder().setFileDescriptors(fileDescriptors).build();
7282
out.println("============================================================");
7383
out.println(" CEL Verification REPL");
7484
out.println(" Type :help for commands, :quit to exit.");
@@ -140,7 +150,7 @@ private static int runReplInternal(
140150
err.println(
141151
"Usage: :var <name> <type> (e.g. :var role string, :var scores map<string,int>)");
142152
} else {
143-
handleVarCommand(arg, sessionVars, out, err);
153+
handleVarCommand(arg, typeOptions, sessionVars, out, err);
144154
}
145155
continue;
146156
}
@@ -209,6 +219,7 @@ private static int runReplInternal(
209219
.setTimeout(Duration.ofSeconds(timeoutSeconds))
210220
.setComprehensionUnrollLimit(unrollLimit)
211221
.setUnknownIdentifiers(unknownIdentifiers)
222+
.setFileDescriptors(fileDescriptors)
212223
.build();
213224

214225
try {
@@ -275,15 +286,19 @@ private static int runReplInternal(
275286
}
276287

277288
private static void handleVarCommand(
278-
String arg, Map<String, CelType> sessionVars, PrintStream out, PrintStream err) {
289+
String arg,
290+
VerificationOptions typeOptions,
291+
Map<String, CelType> sessionVars,
292+
PrintStream out,
293+
PrintStream err) {
279294
String[] parts = arg.split("\\s+", 2);
280295
if (parts.length != 2) {
281296
err.println("Usage: :var <name> <type> (e.g. :var role string, :var scores map<string,int>)");
282297
return;
283298
}
284299
String name = parts[0].trim();
285300
try {
286-
CelType type = DEFAULT_OPTIONS.parseCelType(parts[1]);
301+
CelType type = typeOptions.parseCelType(parts[1]);
287302
sessionVars.put(name, type);
288303
out.println("Variable declared: " + name + " : " + CelTypes.format(type));
289304
} catch (IllegalArgumentException | IllegalStateException e) {
@@ -324,7 +339,9 @@ private static void printHelp(String topic, PrintStream out) {
324339
out.println(
325340
" - Optional types: optional_type<T> (e.g., optional_type<string>,"
326341
+ " optional_type<int>)");
327-
out.println(" - Protobuf types: coming soon");
342+
out.println(
343+
" - Protobuf types: message and enum names from repl --file_descriptor_set"
344+
+ " (enums are int)");
328345
out.println();
329346
out.println("Examples:");
330347
out.println(" cel-verifier> :var role string");

‎verifier/src/main/java/dev/cel/verifier/tools/CelVerifierTool.java‎

Lines changed: 43 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@
1515
package dev.cel.verifier.tools;
1616

1717
import com.google.common.collect.ImmutableMap;
18+
import com.google.common.collect.ImmutableSet;
1819
import com.google.protobuf.DescriptorProtos.FileDescriptorSet;
20+
import com.google.protobuf.Descriptors.FileDescriptor;
1921
import com.google.protobuf.ExtensionRegistry;
2022
import dev.cel.common.CelDescriptorUtil;
2123
import dev.cel.common.CelValidationException;
@@ -38,6 +40,7 @@
3840
import picocli.CommandLine;
3941
import picocli.CommandLine.Command;
4042
import picocli.CommandLine.IVersionProvider;
43+
import picocli.CommandLine.Mixin;
4144
import picocli.CommandLine.Model.CommandSpec;
4245
import picocli.CommandLine.Option;
4346
import picocli.CommandLine.Spec;
@@ -76,6 +79,28 @@ public void run() {
7679
spec.commandLine().usage(spec.commandLine().getOut());
7780
}
7881

82+
/** The protobuf descriptor set option, shared by all commands. */
83+
static final class DescriptorSetOption {
84+
@Option(
85+
names = {"--file_descriptor_set", "--transitive_descriptor_set"},
86+
description = "Path to a FileDescriptorSet with the protobuf types used by variables")
87+
String path = "";
88+
89+
ImmutableSet<FileDescriptor> load() throws IOException {
90+
if (path.isEmpty()) {
91+
return ImmutableSet.of();
92+
}
93+
try {
94+
return CelDescriptorUtil.getFileDescriptorsFromFileDescriptorSet(
95+
FileDescriptorSet.parseFrom(
96+
Files.readAllBytes(new File(path).toPath()), ExtensionRegistry.getEmptyRegistry()));
97+
} catch (IOException | RuntimeException e) {
98+
throw new IOException(
99+
"Failed to read file descriptor set '" + path + "': " + e.getMessage(), e);
100+
}
101+
}
102+
}
103+
79104
/** Options shared across all verification commands. */
80105
abstract static class BaseVerificationCommand implements Callable<Integer> {
81106

@@ -120,10 +145,7 @@ PrintWriter err() {
120145
description = "Output format: TEXT or JSON (default: TEXT)")
121146
String outputFormatStr = VerificationOptions.DEFAULT_OUTPUT_FORMAT.name();
122147

123-
@Option(
124-
names = {"--file_descriptor_set", "--transitive_descriptor_set"},
125-
description = "Path to a FileDescriptorSet with the protobuf types used by variables")
126-
String fileDescriptorSetPath = "";
148+
@Mixin DescriptorSetOption descriptorSet = new DescriptorSetOption();
127149

128150
@FunctionalInterface
129151
protected interface CommandAction {
@@ -158,24 +180,13 @@ protected VerificationOptions getOptions() throws IOException {
158180
} catch (IllegalArgumentException e) {
159181
err().println("Invalid output format '" + outputFormatStr + "'. Defaulting to TEXT.");
160182
}
161-
VerificationOptions.Builder builder =
162-
VerificationOptions.builder()
163-
.setTimeout(Duration.ofSeconds(timeoutSeconds))
164-
.setComprehensionUnrollLimit(comprehensionUnrollLimit)
165-
.setUnknownIdentifiers(unknownIdentifiers)
166-
.setOutputFormat(format);
167-
if (!fileDescriptorSetPath.isEmpty()) {
168-
try {
169-
builder.setFileDescriptors(
170-
CelDescriptorUtil.getFileDescriptorsFromFileDescriptorSet(
171-
FileDescriptorSet.parseFrom(
172-
Files.readAllBytes(new File(fileDescriptorSetPath).toPath()),
173-
ExtensionRegistry.getEmptyRegistry())));
174-
} catch (IOException e) {
175-
throw new IOException("Failed to read file descriptor set: " + fileDescriptorSetPath, e);
176-
}
177-
}
178-
return builder.build();
183+
return VerificationOptions.builder()
184+
.setTimeout(Duration.ofSeconds(timeoutSeconds))
185+
.setComprehensionUnrollLimit(comprehensionUnrollLimit)
186+
.setUnknownIdentifiers(unknownIdentifiers)
187+
.setOutputFormat(format)
188+
.setFileDescriptors(descriptorSet.load())
189+
.build();
179190
}
180191

181192
protected int handleSingleResult(CelVerificationResult result, OutputFormat format) {
@@ -321,9 +332,18 @@ private static int getPolicyExitCode(ImmutableMap<String, CelVerificationResult>
321332
@Command(name = "repl", description = "Launch interactive CEL Formal Verification REPL shell")
322333
static class ReplCommand implements Callable<Integer> {
323334

335+
@Spec private CommandSpec spec;
336+
337+
@Mixin DescriptorSetOption descriptorSet = new DescriptorSetOption();
338+
324339
@Override
325340
public Integer call() {
326-
return CelVerifierRepl.runInteractiveRepl();
341+
try {
342+
return CelVerifierRepl.runInteractiveRepl(descriptorSet.load());
343+
} catch (IOException e) {
344+
spec.commandLine().getErr().println(e.getMessage());
345+
return EXIT_CODE_ERROR;
346+
}
327347
}
328348
}
329349

‎verifier/src/test/java/dev/cel/verifier/tools/CelVerifierReplTest.java‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@
1717
import static com.google.common.truth.Truth.assertThat;
1818
import static java.nio.charset.StandardCharsets.UTF_8;
1919

20+
import com.google.common.collect.ImmutableSet;
21+
import com.google.protobuf.Descriptors.FileDescriptor;
22+
import dev.cel.expr.conformance.proto3.TestAllTypes;
2023
import java.io.BufferedReader;
2124
import java.io.ByteArrayOutputStream;
2225
import java.io.PrintStream;
@@ -34,22 +37,44 @@ public void setUp() {
3437
System.setProperty("z3.skipLibraryLoad", "true");
3538
}
3639

37-
@SuppressWarnings({"PreferCharsetOverload", "JdkObsolete"})
3840
private String[] runReplWithCommands(String... commands) throws Exception {
41+
return runReplWithCommands(ImmutableSet.of(), commands);
42+
}
43+
44+
@SuppressWarnings({"PreferCharsetOverload", "JdkObsolete"})
45+
private String[] runReplWithCommands(
46+
ImmutableSet<FileDescriptor> fileDescriptors, String... commands) throws Exception {
3947
String input = String.join("\n", commands) + "\n";
4048
BufferedReader reader = new BufferedReader(new StringReader(input));
4149
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
4250
ByteArrayOutputStream errStream = new ByteArrayOutputStream();
4351
PrintStream out = new PrintStream(outStream, true, UTF_8.name());
4452
PrintStream err = new PrintStream(errStream, true, UTF_8.name());
4553

46-
CelVerifierRepl.runRepl(reader, out, err);
54+
CelVerifierRepl.runRepl(fileDescriptors, reader, out, err);
4755

4856
return new String[] {
4957
new String(outStream.toByteArray(), UTF_8), new String(errStream.toByteArray(), UTF_8)
5058
};
5159
}
5260

61+
@Test
62+
public void repl_protoTypesFromDescriptorSet() throws Exception {
63+
String[] output =
64+
runReplWithCommands(
65+
ImmutableSet.of(TestAllTypes.getDescriptor().getFile()),
66+
":var msg cel.expr.conformance.proto3.TestAllTypes",
67+
":var e cel.expr.conformance.proto3.TestAllTypes.NestedEnum",
68+
"valid has(msg.single_nested_message) || msg.single_nested_message.bb == 0",
69+
":quit");
70+
71+
assertThat(output[0])
72+
.contains("Variable declared: msg : cel.expr.conformance.proto3.TestAllTypes");
73+
assertThat(output[0]).contains("Variable declared: e : int");
74+
assertThat(output[0]).contains("[VERIFIED]");
75+
assertThat(output[1]).isEmpty();
76+
}
77+
5378
@Test
5479
public void repl_quitAndExit() throws Exception {
5580
String[] output1 = runReplWithCommands(":quit");
@@ -86,7 +111,7 @@ public void repl_helpCommands() throws Exception {
86111
assertThat(output[0]).contains("Query: equiv <expression1> <=> <expression2>");
87112
assertThat(output[0]).contains("Well-known types: timestamp, duration");
88113
assertThat(output[0]).contains("Optional types: optional_type<T>");
89-
assertThat(output[0]).contains("Protobuf types: coming soon");
114+
assertThat(output[0]).contains("Protobuf types: message and enum names");
90115
}
91116

92117
@Test

‎verifier/src/test/java/dev/cel/verifier/tools/CelVerifierToolTest.java‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
import com.google.common.collect.ImmutableList;
2121
import com.google.common.collect.ImmutableMap;
22+
import com.google.protobuf.DescriptorProtos.FileDescriptorProto;
2223
import com.google.protobuf.DescriptorProtos.FileDescriptorSet;
2324
import dev.cel.common.types.CelType;
2425
import dev.cel.common.types.ListType;
@@ -133,7 +134,31 @@ public void celVerifierTool_missingFileDescriptorSet_error() {
133134

134135
assertThat(output)
135136
.contains(
136-
"Verification error: Failed to read file descriptor set: missing_descriptor_set.pb");
137+
"Verification error: Failed to read file descriptor set 'missing_descriptor_set.pb'");
138+
}
139+
140+
@Test
141+
public void celVerifierTool_repl_withFileDescriptorSet_exitsAtEndOfInput() throws Exception {
142+
int exitCode =
143+
new CommandLine(new CelVerifierTool())
144+
.execute("repl", "--file_descriptor_set", writeTestAllTypesDescriptorSet());
145+
146+
assertThat(exitCode).isEqualTo(CelVerifierTool.EXIT_CODE_VERIFIED);
147+
}
148+
149+
@Test
150+
public void celVerifierTool_repl_unresolvedFileDescriptorSet_error() throws Exception {
151+
File file = tempFolder.newFile("unresolved.pb");
152+
Files.write(
153+
file.toPath(),
154+
FileDescriptorSet.newBuilder()
155+
.addFile(FileDescriptorProto.newBuilder().setName("a.proto").addDependency("b.proto"))
156+
.build()
157+
.toByteArray());
158+
159+
String output = executeToolWithOutput("repl", "--file_descriptor_set", file.getAbsolutePath());
160+
161+
assertThat(output).contains("unresolved proto file: b.proto");
137162
}
138163

139164
@Test

‎verifier/tools/README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,9 @@ parameters for every query.
159159
bazel run //verifier/tools:cel_verifier_tool -- repl
160160
```
161161

162+
Pass `--file_descriptor_set <path>` to `repl` to declare protobuf message and
163+
enum variables with `:var`.
164+
162165
### REPL Commands
163166

164167
| Command | Description | Example |

0 commit comments

Comments
 (0)