Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
39 changes: 28 additions & 11 deletions verifier/src/main/java/dev/cel/verifier/tools/CelVerifierRepl.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<FileDescriptor> fileDescriptors) {
LineReader lineReader = null;
BufferedReader fallbackReader = null;
try {
Expand All @@ -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<FileDescriptor> 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<FileDescriptor> 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.");
Expand Down Expand Up @@ -140,7 +150,7 @@ private static int runReplInternal(
err.println(
"Usage: :var <name> <type> (e.g. :var role string, :var scores map<string,int>)");
} else {
handleVarCommand(arg, sessionVars, out, err);
handleVarCommand(arg, typeOptions, sessionVars, out, err);
}
continue;
}
Expand Down Expand Up @@ -209,6 +219,7 @@ private static int runReplInternal(
.setTimeout(Duration.ofSeconds(timeoutSeconds))
.setComprehensionUnrollLimit(unrollLimit)
.setUnknownIdentifiers(unknownIdentifiers)
.setFileDescriptors(fileDescriptors)
.build();

try {
Expand Down Expand Up @@ -275,15 +286,19 @@ private static int runReplInternal(
}

private static void handleVarCommand(
String arg, Map<String, CelType> sessionVars, PrintStream out, PrintStream err) {
String arg,
VerificationOptions typeOptions,
Map<String, CelType> sessionVars,
PrintStream out,
PrintStream err) {
String[] parts = arg.split("\\s+", 2);
if (parts.length != 2) {
err.println("Usage: :var <name> <type> (e.g. :var role string, :var scores map<string,int>)");
return;
}
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) {
Expand Down Expand Up @@ -324,7 +339,9 @@ private static void printHelp(String topic, PrintStream out) {
out.println(
" - Optional types: optional_type<T> (e.g., optional_type<string>,"
+ " optional_type<int>)");
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");
Expand Down
66 changes: 43 additions & 23 deletions verifier/src/main/java/dev/cel/verifier/tools/CelVerifierTool.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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<FileDescriptor> 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<Integer> {

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -321,9 +332,18 @@ private static int getPolicyExitCode(ImmutableMap<String, CelVerificationResult>
@Command(name = "repl", description = "Launch interactive CEL Formal Verification REPL shell")
static class ReplCommand implements Callable<Integer> {

@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;
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -34,22 +37,44 @@ 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<FileDescriptor> fileDescriptors, String... commands) throws Exception {
String input = String.join("\n", commands) + "\n";
BufferedReader reader = new BufferedReader(new StringReader(input));
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ByteArrayOutputStream errStream = new ByteArrayOutputStream();
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");
Expand Down Expand Up @@ -86,7 +111,7 @@ public void repl_helpCommands() throws Exception {
assertThat(output[0]).contains("Query: equiv <expression1> <=> <expression2>");
assertThat(output[0]).contains("Well-known types: timestamp, duration");
assertThat(output[0]).contains("Optional types: optional_type<T>");
assertThat(output[0]).contains("Protobuf types: coming soon");
assertThat(output[0]).contains("Protobuf types: message and enum names");
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions verifier/tools/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,9 @@ parameters for every query.
bazel run //verifier/tools:cel_verifier_tool -- repl
```

Pass `--file_descriptor_set <path>` to `repl` to declare protobuf message and
enum variables with `:var`.

### REPL Commands

| Command | Description | Example |
Expand Down
Loading