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
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
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@
/** Interactive REPL shell for CEL formal verification. */
final class CelVerifierRepl {

private static final VerificationOptions DEFAULT_OPTIONS = VerificationOptions.builder().build();

private CelVerifierRepl() {}

static int runInteractiveRepl() {
Expand Down Expand Up @@ -281,7 +283,7 @@ private static void handleVarCommand(
}
String name = parts[0].trim();
try {
CelType type = VerificationOptions.parseCelType(parts[1]);
CelType type = DEFAULT_OPTIONS.parseCelType(parts[1]);
sessionVars.put(name, type);
out.println("Variable declared: " + name + " : " + CelTypes.format(type));
} catch (IllegalArgumentException | IllegalStateException e) {
Expand Down
37 changes: 29 additions & 8 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,17 @@
package dev.cel.verifier.tools;

import com.google.common.collect.ImmutableMap;
import com.google.protobuf.DescriptorProtos.FileDescriptorSet;
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 Down Expand Up @@ -116,6 +120,11 @@ 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 = "";

@FunctionalInterface
protected interface CommandAction {
int execute(VerificationOptions options, ImmutableMap<String, CelType> vars) throws Exception;
Expand All @@ -128,7 +137,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,19 +151,31 @@ 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));
} catch (IllegalArgumentException e) {
err().println("Invalid output format '" + outputFormatStr + "'. Defaulting to TEXT.");
}
return VerificationOptions.builder()
.setTimeout(Duration.ofSeconds(timeoutSeconds))
.setComprehensionUnrollLimit(comprehensionUnrollLimit)
.setUnknownIdentifiers(unknownIdentifiers)
.setOutputFormat(format)
.build();
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();
}

protected int handleSingleResult(CelVerificationResult result, OutputFormat format) {
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
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,25 @@
package dev.cel.verifier.tools;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.protobuf.Descriptors.FileDescriptor;
import dev.cel.bundle.CelEnvironment.TypeDecl;
import dev.cel.common.types.CelKind;
import dev.cel.common.types.CelType;
import dev.cel.common.types.CelTypeProvider;
import dev.cel.common.types.EnumType;
import dev.cel.common.types.ProtoMessageTypeProvider;
import dev.cel.common.types.SimpleType;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/** Configuration options for CEL verification CLI operations. */
final class VerificationOptions {
Expand All @@ -42,15 +47,15 @@ enum OutputFormat {
static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(10);
static final int DEFAULT_COMPREHENSION_UNROLL_LIMIT = 5;
static final OutputFormat DEFAULT_OUTPUT_FORMAT = OutputFormat.TEXT;
private static final CelTypeProvider EMPTY_TYPE_PROVIDER =
ProtoMessageTypeProvider.newBuilder().build();
private static final ImmutableSet<CelKind> UNDECLARABLE_KINDS =
Sets.immutableEnumSet(CelKind.NULL_TYPE, CelKind.TYPE, CelKind.TYPE_PARAM);

private final Duration timeout;
private final int comprehensionUnrollLimit;
private final ImmutableList<String> unknownIdentifiers;
private final OutputFormat outputFormat;
private final ImmutableSet<FileDescriptor> fileDescriptors;
private final CelTypeProvider typeProvider;

Duration getTimeout() {
return timeout;
Expand All @@ -68,6 +73,10 @@ OutputFormat getOutputFormat() {
return outputFormat;
}

ImmutableSet<FileDescriptor> getFileDescriptors() {
return fileDescriptors;
}

static Builder builder() {
return new Builder();
}
Expand All @@ -78,6 +87,7 @@ static final class Builder {
private int comprehensionUnrollLimit = DEFAULT_COMPREHENSION_UNROLL_LIMIT;
private ImmutableList<String> unknownIdentifiers = ImmutableList.of();
private OutputFormat outputFormat = DEFAULT_OUTPUT_FORMAT;
private ImmutableSet<FileDescriptor> fileDescriptors = ImmutableSet.of();

@CanIgnoreReturnValue
Builder setTimeout(Duration timeout) {
Expand All @@ -104,28 +114,54 @@ Builder setOutputFormat(OutputFormat outputFormat) {
return this;
}

@CanIgnoreReturnValue
Builder setFileDescriptors(Iterable<FileDescriptor> fileDescriptors) {
this.fileDescriptors = ImmutableSet.copyOf(fileDescriptors);
return this;
}

VerificationOptions build() {
return new VerificationOptions(
timeout, comprehensionUnrollLimit, unknownIdentifiers, outputFormat);
timeout, comprehensionUnrollLimit, unknownIdentifiers, outputFormat, fileDescriptors);
}
}

private VerificationOptions(
Duration timeout,
int comprehensionUnrollLimit,
ImmutableList<String> unknownIdentifiers,
OutputFormat outputFormat) {
OutputFormat outputFormat,
ImmutableSet<FileDescriptor> fileDescriptors) {
this.timeout = timeout;
this.comprehensionUnrollLimit = comprehensionUnrollLimit;
this.unknownIdentifiers = unknownIdentifiers;
this.outputFormat = outputFormat;
this.fileDescriptors = fileDescriptors;
this.typeProvider =
enumsAsInt(
ProtoMessageTypeProvider.newBuilder().addFileDescriptors(fileDescriptors).build());
}

// The type checker reads enum fields and constants as int, but leaves enum-typed variables as is.
private static CelTypeProvider enumsAsInt(CelTypeProvider provider) {
return new CelTypeProvider() {
@Override
public ImmutableCollection<CelType> types() {
return provider.types();
}

@Override
public Optional<CelType> findType(String typeName) {
return provider.findType(typeName).map(t -> t instanceof EnumType ? SimpleType.INT : t);
}
};
}

/**
* Helper utility to parse CLI variable definitions formatted as "name:type" (e.g. "x:int",
* "role:string", "is_admin:bool").
*/
static ImmutableMap<String, CelType> parseVariables(List<String> varSpecs) {
ImmutableMap<String, CelType> parseVariables(List<String> varSpecs) {
if (varSpecs == null || varSpecs.isEmpty()) {
return ImmutableMap.of();
}
Expand All @@ -149,8 +185,8 @@ static ImmutableMap<String, CelType> parseVariables(List<String> varSpecs) {
return ImmutableMap.copyOf(vars);
}

static CelType parseCelType(String typeStr) {
CelType type = TypeDecl.parse(typeStr).toCelType(EMPTY_TYPE_PROVIDER);
CelType parseCelType(String typeStr) {
CelType type = TypeDecl.parse(typeStr).toCelType(typeProvider);
checkDeclarable(type);
return type;
}
Expand Down
3 changes: 3 additions & 0 deletions verifier/src/test/java/dev/cel/verifier/tools/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ java_library(
"//common/types:type_providers",
"//verifier",
"//verifier/tools",
"@cel_conformance//proto/cel/expr/conformance/proto2:test_all_types_java_proto",
"@cel_conformance//proto/cel/expr/conformance/proto3:test_all_types_java_proto",
"@maven//:com_google_guava_guava",
"@maven//:com_google_protobuf_protobuf_java",
"@maven//:info_picocli_picocli",
"@maven//:junit_junit",
],
Expand Down
Loading
Loading