Skip to content
Open
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
2 changes: 2 additions & 0 deletions verifier/src/main/java/dev/cel/verifier/tools/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,12 @@ java_library(
"//bundle:cel",
"//bundle:environment",
"//common:cel_ast",
"//common:cel_descriptor_util",
"//common:compiler_common",
"//common:options",
"//common/internal:cel_descriptor_pools",
"//common/internal:well_known_proto",
"//common/types",
"//common/types:cel_types",
"//common/types:message_type_provider",
"//common/types:type_providers",
Expand Down
37 changes: 28 additions & 9 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 Down Expand Up @@ -45,7 +47,7 @@ final class CelVerifierRepl {

private CelVerifierRepl() {}

static int runInteractiveRepl() {
static int runInteractiveRepl(ImmutableSet<FileDescriptor> fileDescriptors) {
LineReader lineReader = null;
BufferedReader fallbackReader = null;
try {
Expand All @@ -58,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 @@ -138,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 @@ -207,6 +219,7 @@ private static int runReplInternal(
.setTimeout(Duration.ofSeconds(timeoutSeconds))
.setComprehensionUnrollLimit(unrollLimit)
.setUnknownIdentifiers(unknownIdentifiers)
.setFileDescriptors(fileDescriptors)
.build();

try {
Expand Down Expand Up @@ -273,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 = VerificationOptions.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 @@ -322,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
47 changes: 44 additions & 3 deletions verifier/src/main/java/dev/cel/verifier/tools/CelVerifierTool.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,19 @@
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;
import dev.cel.common.types.CelType;
import dev.cel.policy.CelPolicyValidationException;
import dev.cel.verifier.CelVerificationResult;
import dev.cel.verifier.CelVerificationResult.VerificationStatus;
import dev.cel.verifier.tools.VerificationOptions.OutputFormat;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
Expand All @@ -34,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 @@ -72,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 @@ -116,6 +145,8 @@ PrintWriter err() {
description = "Output format: TEXT or JSON (default: TEXT)")
String outputFormatStr = VerificationOptions.DEFAULT_OUTPUT_FORMAT.name();

@Mixin DescriptorSetOption descriptorSet = new DescriptorSetOption();

@FunctionalInterface
protected interface CommandAction {
int execute(VerificationOptions options, ImmutableMap<String, CelType> vars) throws Exception;
Expand All @@ -128,7 +159,7 @@ protected int executeCommand(CommandAction action) {
protected int executeCommand(String errorPrefix, CommandAction action) {
try {
VerificationOptions options = getOptions();
ImmutableMap<String, CelType> vars = VerificationOptions.parseVariables(variables);
ImmutableMap<String, CelType> vars = options.parseVariables(variables);
return action.execute(options, vars);
} catch (CelValidationException e) {
err().println("Compilation error:\n" + e.getMessage());
Expand All @@ -142,7 +173,7 @@ protected int executeCommand(String errorPrefix, CommandAction action) {
}
}

protected VerificationOptions getOptions() {
protected VerificationOptions getOptions() throws IOException {
OutputFormat format = OutputFormat.TEXT;
try {
format = OutputFormat.valueOf(outputFormatStr.toUpperCase(Locale.US));
Expand All @@ -154,6 +185,7 @@ protected VerificationOptions getOptions() {
.setComprehensionUnrollLimit(comprehensionUnrollLimit)
.setUnknownIdentifiers(unknownIdentifiers)
.setOutputFormat(format)
.setFileDescriptors(descriptorSet.load())
.build();
}

Expand Down Expand Up @@ -300,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 @@ -74,7 +74,7 @@ private CelVerifierToolCore() {}
static CelVerificationResult checkSatisfiable(
String expression, Map<String, CelType> variables, VerificationOptions options)
throws Exception {
CelCompiler compiler = buildCompiler(variables);
CelCompiler compiler = buildCompiler(variables, options);
CelAbstractSyntaxTree ast = compiler.compile(expression).getAst();
CelVerifier verifier = buildVerifier(variables, options);
return verifier.isSatisfiable(ast);
Expand All @@ -84,7 +84,7 @@ static CelVerificationResult checkSatisfiable(
static CelVerificationResult checkValid(
String expression, Map<String, CelType> variables, VerificationOptions options)
throws Exception {
CelCompiler compiler = buildCompiler(variables);
CelCompiler compiler = buildCompiler(variables, options);
CelAbstractSyntaxTree ast = compiler.compile(expression).getAst();
CelVerifier verifier = buildVerifier(variables, options);
return verifier.isAlwaysTrue(ast);
Expand All @@ -97,7 +97,7 @@ static CelVerificationResult verifyEquivalence(
Map<String, CelType> variables,
VerificationOptions options)
throws Exception {
CelCompiler compiler = buildCompiler(variables);
CelCompiler compiler = buildCompiler(variables, options);
CelAbstractSyntaxTree astA = compiler.compile(expressionA).getAst();
CelAbstractSyntaxTree astB = compiler.compile(expressionB).getAst();
CelVerifier verifier = buildVerifier(variables, options);
Expand Down Expand Up @@ -130,11 +130,12 @@ static CelVerificationResult verifyPolicyEquivalence(
return policyVerifier.verifyEquivalence(policyA, policyB);
}

static CelCompiler buildCompiler(Map<String, CelType> variables) {
static CelCompiler buildCompiler(Map<String, CelType> variables, VerificationOptions options) {
CelCompilerBuilder builder =
CelCompilerFactory.standardCelCompilerBuilder()
.setStandardMacros(CelStandardMacro.STANDARD_MACROS)
.addMessageTypes(WELL_KNOWN_DESCRIPTORS)
.addFileTypes(options.getFileDescriptors())
.addLibraries(
CelExtensions.bindings(),
CelExtensions.comprehensions(),
Expand All @@ -152,11 +153,12 @@ static CelCompiler buildCompiler(Map<String, CelType> variables) {
return builder.build();
}

static Cel buildCel(Map<String, CelType> variables) {
static Cel buildCel(Map<String, CelType> variables, VerificationOptions options) {
CelBuilder celBuilder =
CelFactory.plannerCelBuilder()
.setStandardMacros(CelStandardMacro.STANDARD_MACROS)
.addMessageTypes(WELL_KNOWN_DESCRIPTORS)
.addFileTypes(options.getFileDescriptors())
.addCompilerLibraries(
CelExtensions.optional(),
CelExtensions.bindings(),
Expand All @@ -171,7 +173,7 @@ static Cel buildCel(Map<String, CelType> variables) {

static CelVerifier buildVerifier(Map<String, CelType> variables, VerificationOptions options) {
CelVerifierBuilder builder =
CelVerifierFactory.newVerifier(buildCel(variables))
CelVerifierFactory.newVerifier(buildCel(variables, options))
.setTimeout(options.getTimeout())
.setComprehensionUnrollLimit(options.getComprehensionUnrollLimit());

Expand All @@ -183,7 +185,7 @@ static CelVerifier buildVerifier(Map<String, CelType> variables, VerificationOpt

private static CelPolicyVerifier buildPolicyVerifier(
Map<String, CelType> variables, VerificationOptions options) {
Cel celBundle = buildCel(variables);
Cel celBundle = buildCel(variables, options);
CelPolicyCompiler policyCompiler =
CelPolicyCompilerFactory.newPolicyCompiler(celBundle).build();
CelVerifier astVerifier = buildVerifier(variables, options);
Expand Down
Loading
Loading