diff --git a/verifier/src/main/java/dev/cel/verifier/tools/BUILD.bazel b/verifier/src/main/java/dev/cel/verifier/tools/BUILD.bazel index ebda2d80d..ea22ab405 100644 --- a/verifier/src/main/java/dev/cel/verifier/tools/BUILD.bazel +++ b/verifier/src/main/java/dev/cel/verifier/tools/BUILD.bazel @@ -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", 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 d7056f741..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; @@ -45,7 +47,7 @@ final class CelVerifierRepl { private CelVerifierRepl() {} - static int runInteractiveRepl() { + static int runInteractiveRepl(ImmutableSet fileDescriptors) { LineReader lineReader = null; BufferedReader fallbackReader = null; try { @@ -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 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."); @@ -138,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; } @@ -207,6 +219,7 @@ private static int runReplInternal( .setTimeout(Duration.ofSeconds(timeoutSeconds)) .setComprehensionUnrollLimit(unrollLimit) .setUnknownIdentifiers(unknownIdentifiers) + .setFileDescriptors(fileDescriptors) .build(); try { @@ -273,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)"); @@ -281,7 +298,7 @@ private static void handleVarCommand( } 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) { @@ -322,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 a4210d246..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,6 +15,11 @@ 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; @@ -22,6 +27,7 @@ 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; @@ -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; @@ -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 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 { @@ -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 vars) throws Exception; @@ -128,7 +159,7 @@ protected int executeCommand(CommandAction action) { protected int executeCommand(String errorPrefix, CommandAction action) { try { VerificationOptions options = getOptions(); - ImmutableMap vars = VerificationOptions.parseVariables(variables); + ImmutableMap vars = options.parseVariables(variables); return action.execute(options, vars); } catch (CelValidationException e) { err().println("Compilation error:\n" + e.getMessage()); @@ -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)); @@ -154,6 +185,7 @@ protected VerificationOptions getOptions() { .setComprehensionUnrollLimit(comprehensionUnrollLimit) .setUnknownIdentifiers(unknownIdentifiers) .setOutputFormat(format) + .setFileDescriptors(descriptorSet.load()) .build(); } @@ -300,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/main/java/dev/cel/verifier/tools/CelVerifierToolCore.java b/verifier/src/main/java/dev/cel/verifier/tools/CelVerifierToolCore.java index ddc217998..020e163a2 100644 --- a/verifier/src/main/java/dev/cel/verifier/tools/CelVerifierToolCore.java +++ b/verifier/src/main/java/dev/cel/verifier/tools/CelVerifierToolCore.java @@ -74,7 +74,7 @@ private CelVerifierToolCore() {} static CelVerificationResult checkSatisfiable( String expression, Map 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); @@ -84,7 +84,7 @@ static CelVerificationResult checkSatisfiable( static CelVerificationResult checkValid( String expression, Map 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); @@ -97,7 +97,7 @@ static CelVerificationResult verifyEquivalence( Map 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); @@ -130,11 +130,12 @@ static CelVerificationResult verifyPolicyEquivalence( return policyVerifier.verifyEquivalence(policyA, policyB); } - static CelCompiler buildCompiler(Map variables) { + static CelCompiler buildCompiler(Map variables, VerificationOptions options) { CelCompilerBuilder builder = CelCompilerFactory.standardCelCompilerBuilder() .setStandardMacros(CelStandardMacro.STANDARD_MACROS) .addMessageTypes(WELL_KNOWN_DESCRIPTORS) + .addFileTypes(options.getFileDescriptors()) .addLibraries( CelExtensions.bindings(), CelExtensions.comprehensions(), @@ -152,11 +153,12 @@ static CelCompiler buildCompiler(Map variables) { return builder.build(); } - static Cel buildCel(Map variables) { + static Cel buildCel(Map variables, VerificationOptions options) { CelBuilder celBuilder = CelFactory.plannerCelBuilder() .setStandardMacros(CelStandardMacro.STANDARD_MACROS) .addMessageTypes(WELL_KNOWN_DESCRIPTORS) + .addFileTypes(options.getFileDescriptors()) .addCompilerLibraries( CelExtensions.optional(), CelExtensions.bindings(), @@ -171,7 +173,7 @@ static Cel buildCel(Map variables) { static CelVerifier buildVerifier(Map variables, VerificationOptions options) { CelVerifierBuilder builder = - CelVerifierFactory.newVerifier(buildCel(variables)) + CelVerifierFactory.newVerifier(buildCel(variables, options)) .setTimeout(options.getTimeout()) .setComprehensionUnrollLimit(options.getComprehensionUnrollLimit()); @@ -183,7 +185,7 @@ static CelVerifier buildVerifier(Map variables, VerificationOpt private static CelPolicyVerifier buildPolicyVerifier( Map variables, VerificationOptions options) { - Cel celBundle = buildCel(variables); + Cel celBundle = buildCel(variables, options); CelPolicyCompiler policyCompiler = CelPolicyCompilerFactory.newPolicyCompiler(celBundle).build(); CelVerifier astVerifier = buildVerifier(variables, options); diff --git a/verifier/src/main/java/dev/cel/verifier/tools/VerificationOptions.java b/verifier/src/main/java/dev/cel/verifier/tools/VerificationOptions.java index 967a03fd9..a649338f8 100644 --- a/verifier/src/main/java/dev/cel/verifier/tools/VerificationOptions.java +++ b/verifier/src/main/java/dev/cel/verifier/tools/VerificationOptions.java @@ -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 { @@ -42,8 +47,6 @@ 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 UNDECLARABLE_KINDS = Sets.immutableEnumSet(CelKind.NULL_TYPE, CelKind.TYPE, CelKind.TYPE_PARAM); @@ -51,6 +54,8 @@ enum OutputFormat { private final int comprehensionUnrollLimit; private final ImmutableList unknownIdentifiers; private final OutputFormat outputFormat; + private final ImmutableSet fileDescriptors; + private final CelTypeProvider typeProvider; Duration getTimeout() { return timeout; @@ -68,6 +73,10 @@ OutputFormat getOutputFormat() { return outputFormat; } + ImmutableSet getFileDescriptors() { + return fileDescriptors; + } + static Builder builder() { return new Builder(); } @@ -78,6 +87,7 @@ static final class Builder { private int comprehensionUnrollLimit = DEFAULT_COMPREHENSION_UNROLL_LIMIT; private ImmutableList unknownIdentifiers = ImmutableList.of(); private OutputFormat outputFormat = DEFAULT_OUTPUT_FORMAT; + private ImmutableSet fileDescriptors = ImmutableSet.of(); @CanIgnoreReturnValue Builder setTimeout(Duration timeout) { @@ -104,9 +114,15 @@ Builder setOutputFormat(OutputFormat outputFormat) { return this; } + @CanIgnoreReturnValue + Builder setFileDescriptors(Iterable fileDescriptors) { + this.fileDescriptors = ImmutableSet.copyOf(fileDescriptors); + return this; + } + VerificationOptions build() { return new VerificationOptions( - timeout, comprehensionUnrollLimit, unknownIdentifiers, outputFormat); + timeout, comprehensionUnrollLimit, unknownIdentifiers, outputFormat, fileDescriptors); } } @@ -114,18 +130,38 @@ private VerificationOptions( Duration timeout, int comprehensionUnrollLimit, ImmutableList unknownIdentifiers, - OutputFormat outputFormat) { + OutputFormat outputFormat, + ImmutableSet 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 types() { + return provider.types(); + } + + @Override + public Optional 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 parseVariables(List varSpecs) { + ImmutableMap parseVariables(List varSpecs) { if (varSpecs == null || varSpecs.isEmpty()) { return ImmutableMap.of(); } @@ -149,8 +185,8 @@ static ImmutableMap parseVariables(List 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; } diff --git a/verifier/src/test/java/dev/cel/verifier/tools/BUILD.bazel b/verifier/src/test/java/dev/cel/verifier/tools/BUILD.bazel index 6077e4950..2f5c41732 100644 --- a/verifier/src/test/java/dev/cel/verifier/tools/BUILD.bazel +++ b/verifier/src/test/java/dev/cel/verifier/tools/BUILD.bazel @@ -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", ], 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 755c8ebe7..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,10 +19,14 @@ 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; import dev.cel.common.types.MapType; import dev.cel.common.types.SimpleType; +import dev.cel.expr.conformance.proto2.TestAllTypesProto; +import dev.cel.expr.conformance.proto3.TestAllTypes; import dev.cel.verifier.CelVerificationResult; import dev.cel.verifier.CelVerificationResult.VerificationStatus; import java.io.File; @@ -42,6 +46,7 @@ @RunWith(JUnit4.class) public final class CelVerifierToolTest { + private static final VerificationOptions OPTIONS = VerificationOptions.builder().build(); @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @@ -60,6 +65,102 @@ private String executeToolWithOutput(String... args) { return out.toString(); } + private String writeTestAllTypesDescriptorSet() throws Exception { + File file = tempFolder.newFile("test_all_types.pb"); + Files.write( + file.toPath(), + FileDescriptorSet.newBuilder() + .addFile(TestAllTypes.getDescriptor().getFile().toProto()) + .addFile(TestAllTypesProto.getDescriptor().toProto()) + .build() + .toByteArray()); + return file.getAbsolutePath(); + } + + @Test + public void celVerifierTool_checkValid_unsetMessageFieldReadsDefault() throws Exception { + String output = + executeToolWithOutput( + "check-valid", + "--expr", + "has(msg.single_nested_message) || msg.single_nested_message.bb == 0", + "--var", + "msg:cel.expr.conformance.proto3.TestAllTypes", + "--file_descriptor_set", + writeTestAllTypesDescriptorSet()); + + assertThat(output).contains("[VERIFIED]"); + } + + @Test + public void celVerifierTool_verifyEquiv_proto2ScalarPresence() throws Exception { + String output = + executeToolWithOutput( + "verify-equiv", + "--expr1", + "has(msg.single_int64)", + "--expr2", + "msg.single_int64 != 0", + "--var", + "msg:cel.expr.conformance.proto2.TestAllTypes", + "--transitive_descriptor_set", + writeTestAllTypesDescriptorSet()); + + assertThat(output).contains("[VIOLATED]"); + } + + @Test + public void celVerifierTool_verifyEquiv_protoEnumVariable() throws Exception { + String output = + executeToolWithOutput( + "verify-equiv", + "--expr1", + "e == cel.expr.conformance.proto3.TestAllTypes.NestedEnum.BAR", + "--expr2", + "e == 1", + "--var", + "e:cel.expr.conformance.proto3.TestAllTypes.NestedEnum", + "--file_descriptor_set", + writeTestAllTypesDescriptorSet()); + + assertThat(output).contains("[VERIFIED]"); + } + + @Test + public void celVerifierTool_missingFileDescriptorSet_error() { + String output = + executeToolWithOutput( + "check-sat", "--expr", "true", "--file_descriptor_set", "missing_descriptor_set.pb"); + + assertThat(output) + .contains( + "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 public void celVerifierTool_checkSat_jsonOutputFormat() { String output = @@ -153,27 +254,26 @@ public void celVerifierTool_verifyPolicy_fileNotFound() { @Test public void parseVariables_invalidFormat_throws() { assertThrows( - IllegalArgumentException.class, - () -> VerificationOptions.parseVariables(Arrays.asList("x_no_colon"))); + IllegalArgumentException.class, () -> OPTIONS.parseVariables(Arrays.asList("x_no_colon"))); } @Test public void parseVariables_invalidMapFormat_throws() { assertThrows( IllegalArgumentException.class, - () -> VerificationOptions.parseVariables(Arrays.asList("x:map"))); + () -> OPTIONS.parseVariables(Arrays.asList("x:map"))); } @Test public void parseVariables_emptyOrNull_returnsEmptyMap() { - assertThat(VerificationOptions.parseVariables(null)).isEmpty(); - assertThat(VerificationOptions.parseVariables(ImmutableList.of())).isEmpty(); + assertThat(OPTIONS.parseVariables(null)).isEmpty(); + assertThat(OPTIONS.parseVariables(ImmutableList.of())).isEmpty(); } @Test public void parseVariables_nestedTypes() { ImmutableMap vars = - VerificationOptions.parseVariables( + OPTIONS.parseVariables( Arrays.asList( "nested_map:map>", "nested_list_map:map>")); @@ -189,19 +289,15 @@ public void parseVariables_nestedTypes() { @Test public void parseVariables_emptyString_throws() { + assertThrows(IllegalArgumentException.class, () -> OPTIONS.parseVariables(Arrays.asList(""))); assertThrows( - IllegalArgumentException.class, - () -> VerificationOptions.parseVariables(Arrays.asList(""))); - assertThrows( - IllegalArgumentException.class, - () -> VerificationOptions.parseVariables(Arrays.asList(" "))); + IllegalArgumentException.class, () -> OPTIONS.parseVariables(Arrays.asList(" "))); } @Test public void parseVariables_nullElement_throws() { assertThrows( - NullPointerException.class, - () -> VerificationOptions.parseVariables(Arrays.asList((String) null))); + NullPointerException.class, () -> OPTIONS.parseVariables(Arrays.asList((String) null))); } @Test @@ -264,7 +360,7 @@ public void verifyEquivalence_wellKnownTypesSupportedByDefault() throws Exceptio VerificationOptions options = VerificationOptions.builder().setTimeout(Duration.ofSeconds(5)).build(); ImmutableMap vars = - VerificationOptions.parseVariables( + options.parseVariables( Arrays.asList("x:int", "w:google.protobuf.Int64Value", "s:google.protobuf.Struct")); assertThat( diff --git a/verifier/src/test/java/dev/cel/verifier/tools/VerificationOptionsTest.java b/verifier/src/test/java/dev/cel/verifier/tools/VerificationOptionsTest.java index 5a1bbbed7..a256af336 100644 --- a/verifier/src/test/java/dev/cel/verifier/tools/VerificationOptionsTest.java +++ b/verifier/src/test/java/dev/cel/verifier/tools/VerificationOptionsTest.java @@ -19,12 +19,14 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import dev.cel.common.types.CelKind; import dev.cel.common.types.CelType; import dev.cel.common.types.ListType; import dev.cel.common.types.MapType; import dev.cel.common.types.NullableType; import dev.cel.common.types.OptionalType; import dev.cel.common.types.SimpleType; +import dev.cel.expr.conformance.proto3.TestAllTypes; import dev.cel.verifier.tools.VerificationOptions.OutputFormat; import java.time.Duration; import org.junit.Test; @@ -33,6 +35,7 @@ @RunWith(JUnit4.class) public final class VerificationOptionsTest { + private static final VerificationOptions OPTIONS = VerificationOptions.builder().build(); @Test public void defaultOptions() { @@ -87,7 +90,7 @@ public void setOutputFormat_null_throwsException() { @Test public void parseVariables_validSpecs() { ImmutableMap vars = - VerificationOptions.parseVariables( + OPTIONS.parseVariables( ImmutableList.of( "x:int", "name:string", @@ -112,73 +115,79 @@ public void parseVariables_validSpecs() { @Test public void parseCelType_wellKnownTypes() { - assertThat(VerificationOptions.parseCelType("google.protobuf.Timestamp")) - .isEqualTo(SimpleType.TIMESTAMP); - assertThat(VerificationOptions.parseCelType("google.protobuf.Duration")) - .isEqualTo(SimpleType.DURATION); - assertThat(VerificationOptions.parseCelType("google.protobuf.Value")).isEqualTo(SimpleType.DYN); - assertThat(VerificationOptions.parseCelType("google.protobuf.Struct")) + assertThat(OPTIONS.parseCelType("google.protobuf.Timestamp")).isEqualTo(SimpleType.TIMESTAMP); + assertThat(OPTIONS.parseCelType("google.protobuf.Duration")).isEqualTo(SimpleType.DURATION); + assertThat(OPTIONS.parseCelType("google.protobuf.Value")).isEqualTo(SimpleType.DYN); + assertThat(OPTIONS.parseCelType("google.protobuf.Struct")) .isEqualTo(MapType.create(SimpleType.STRING, SimpleType.DYN)); - assertThat(VerificationOptions.parseCelType("google.protobuf.ListValue")) + assertThat(OPTIONS.parseCelType("google.protobuf.ListValue")) .isEqualTo(ListType.create(SimpleType.DYN)); - assertThat(VerificationOptions.parseCelType("google.protobuf.BoolValue")) + assertThat(OPTIONS.parseCelType("google.protobuf.BoolValue")) .isEqualTo(NullableType.create(SimpleType.BOOL)); - assertThat(VerificationOptions.parseCelType("google.protobuf.BytesValue")) + assertThat(OPTIONS.parseCelType("google.protobuf.BytesValue")) .isEqualTo(NullableType.create(SimpleType.BYTES)); - assertThat(VerificationOptions.parseCelType("google.protobuf.DoubleValue")) + assertThat(OPTIONS.parseCelType("google.protobuf.DoubleValue")) .isEqualTo(NullableType.create(SimpleType.DOUBLE)); - assertThat(VerificationOptions.parseCelType("google.protobuf.FloatValue")) + assertThat(OPTIONS.parseCelType("google.protobuf.FloatValue")) .isEqualTo(NullableType.create(SimpleType.DOUBLE)); - assertThat(VerificationOptions.parseCelType("google.protobuf.Int32Value")) + assertThat(OPTIONS.parseCelType("google.protobuf.Int32Value")) .isEqualTo(NullableType.create(SimpleType.INT)); - assertThat(VerificationOptions.parseCelType("google.protobuf.Int64Value")) + assertThat(OPTIONS.parseCelType("google.protobuf.Int64Value")) .isEqualTo(NullableType.create(SimpleType.INT)); - assertThat(VerificationOptions.parseCelType("google.protobuf.UInt32Value")) + assertThat(OPTIONS.parseCelType("google.protobuf.UInt32Value")) .isEqualTo(NullableType.create(SimpleType.UINT)); - assertThat(VerificationOptions.parseCelType("google.protobuf.UInt64Value")) + assertThat(OPTIONS.parseCelType("google.protobuf.UInt64Value")) .isEqualTo(NullableType.create(SimpleType.UINT)); - assertThat(VerificationOptions.parseCelType("google.protobuf.StringValue")) + assertThat(OPTIONS.parseCelType("google.protobuf.StringValue")) .isEqualTo(NullableType.create(SimpleType.STRING)); - assertThat(VerificationOptions.parseCelType("google.protobuf.Any")).isEqualTo(SimpleType.ANY); + assertThat(OPTIONS.parseCelType("google.protobuf.Any")).isEqualTo(SimpleType.ANY); + } + + @Test + public void parseCelType_protoTypes() { + VerificationOptions options = + VerificationOptions.builder() + .setFileDescriptors(ImmutableList.of(TestAllTypes.getDescriptor().getFile())) + .build(); + + CelType message = options.parseCelType("cel.expr.conformance.proto3.TestAllTypes"); + CelType optionalEnum = + options.parseCelType("optional_type"); + + assertThat(message.kind()).isEqualTo(CelKind.STRUCT); + assertThat(message.name()).isEqualTo("cel.expr.conformance.proto3.TestAllTypes"); + assertThat(optionalEnum).isEqualTo(OptionalType.create(SimpleType.INT)); } @Test public void parseCelType_undeclarableType_throwsException() { IllegalArgumentException e = - assertThrows( - IllegalArgumentException.class, - () -> VerificationOptions.parseCelType("map")); + assertThrows(IllegalArgumentException.class, () -> OPTIONS.parseCelType("map")); assertThat(e).hasMessageThat().isEqualTo("Unsupported variable type: T"); - assertThrows(IllegalArgumentException.class, () -> VerificationOptions.parseCelType("null")); - assertThrows( - IllegalArgumentException.class, () -> VerificationOptions.parseCelType("type")); + assertThrows(IllegalArgumentException.class, () -> OPTIONS.parseCelType("null")); + assertThrows(IllegalArgumentException.class, () -> OPTIONS.parseCelType("type")); } @Test public void parseCelType_parenthesesSyntax_throwsException() { - assertThrows( - IllegalArgumentException.class, () -> VerificationOptions.parseCelType("optional(int)")); - assertThrows( - IllegalArgumentException.class, - () -> VerificationOptions.parseCelType("optional_type(bool)")); - assertThrows( - IllegalArgumentException.class, () -> VerificationOptions.parseCelType("list(string)")); - assertThrows( - IllegalArgumentException.class, () -> VerificationOptions.parseCelType("map(string, int)")); + assertThrows(IllegalArgumentException.class, () -> OPTIONS.parseCelType("optional(int)")); + assertThrows(IllegalArgumentException.class, () -> OPTIONS.parseCelType("optional_type(bool)")); + assertThrows(IllegalArgumentException.class, () -> OPTIONS.parseCelType("list(string)")); + assertThrows(IllegalArgumentException.class, () -> OPTIONS.parseCelType("map(string, int)")); } @Test public void parseVariables_nullOrEmpty_returnsEmptyMap() { - assertThat(VerificationOptions.parseVariables(null)).isEmpty(); - assertThat(VerificationOptions.parseVariables(ImmutableList.of())).isEmpty(); + assertThat(OPTIONS.parseVariables(null)).isEmpty(); + assertThat(OPTIONS.parseVariables(ImmutableList.of())).isEmpty(); } @Test public void parseVariables_invalidSpec_throwsException() { ImmutableList specs = ImmutableList.of("invalid_spec_without_colon"); - assertThrows(IllegalArgumentException.class, () -> VerificationOptions.parseVariables(specs)); + assertThrows(IllegalArgumentException.class, () -> OPTIONS.parseVariables(specs)); } @Test @@ -186,8 +195,7 @@ public void parseVariables_unsupportedType_throwsException() { ImmutableList specs = ImmutableList.of("x:unknown_type"); IllegalArgumentException ex = - assertThrows( - IllegalArgumentException.class, () -> VerificationOptions.parseVariables(specs)); + assertThrows(IllegalArgumentException.class, () -> OPTIONS.parseVariables(specs)); assertThat(ex).hasMessageThat().contains("Undefined type name: unknown_type"); } } diff --git a/verifier/tools/BUILD.bazel b/verifier/tools/BUILD.bazel index c3fe3fc32..dd853044d 100644 --- a/verifier/tools/BUILD.bazel +++ b/verifier/tools/BUILD.bazel @@ -1,4 +1,5 @@ load("@bazel_skylib//:bzl_library.bzl", "bzl_library") +load("@rules_proto//proto:defs.bzl", "proto_descriptor_set") load(":cel_verifier.bzl", "cel_verifier_test") package( @@ -74,6 +75,20 @@ cel_verifier_test( variables = {"role": "string"}, ) +proto_descriptor_set( + name = "test_all_types_fds", + testonly = True, + deps = ["@cel_conformance//proto/cel/expr/conformance/proto3:test_all_types_proto"], +) + +cel_verifier_test( + name = "test_proto_message_test", + command = "check-valid", + expression = "has(msg.single_nested_message) || msg.single_nested_message.bb == 0", + file_descriptor_set = ":test_all_types_fds", + variables = {"msg": "cel.expr.conformance.proto3.TestAllTypes"}, +) + bzl_library( name = "cel_verifier_bzl", srcs = ["cel_verifier.bzl"], diff --git a/verifier/tools/README.md b/verifier/tools/README.md index d008c1d1e..18937d188 100644 --- a/verifier/tools/README.md +++ b/verifier/tools/README.md @@ -86,13 +86,26 @@ Supported types: * Map types: `map` (e.g., `--var "scores:map"`) * Optional types: `optional_type` (e.g., `--var "opt_flag:optional_type"`) -* Protobuf types: Coming soon +* Protobuf types: fully qualified message and enum names (e.g., + `--var "msg:my.pkg.MyMessage"`), declared by `--file_descriptor_set`. Enum + variables are `int`, as in CEL. Examples: ```bash --var "role:string" --var "port:int" --var "tags:list" --var "created_at:timestamp" --var "opt_flag:optional_type" ``` +### Protobuf Descriptors (`--file_descriptor_set`) + +Load protobuf message and enum types from a binary `FileDescriptorSet` that +includes all imports (alias: `--transitive_descriptor_set`). Build one with +`protoc --include_imports --descriptor_set_out=types.pb my/pkg/types.proto`, or +with a `proto_descriptor_set` rule in Bazel: + +```bash +--file_descriptor_set types.pb --var "msg:my.pkg.MyMessage" +``` + ### Unknown Identifiers (`--unknown`, `-u`) Permit specific identifiers or attributes (e.g., `request.headers`) to @@ -146,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 | diff --git a/verifier/tools/cel_verifier.bzl b/verifier/tools/cel_verifier.bzl index 1b6b9e6c6..b7cfa7d97 100644 --- a/verifier/tools/cel_verifier.bzl +++ b/verifier/tools/cel_verifier.bzl @@ -30,6 +30,7 @@ def _make_verifier_args( expression = None, expression_b = None, policy_file = None, + file_descriptor_set = None, variables = {}, unknowns = [], timeout = 10, @@ -61,6 +62,11 @@ def _make_verifier_args( args.append("$(rootpath %s)" % policy_file) srcs.append(policy_file) + if file_descriptor_set: + args.append("--file_descriptor_set") + args.append("$(rootpath %s)" % file_descriptor_set) + srcs.append(file_descriptor_set) + for var_name, var_type in variables.items(): args.append("--var") args.append("%s:%s" % (var_name, var_type)) @@ -86,6 +92,7 @@ def cel_verifier_test( expression = None, expression_b = None, policy_file = None, + file_descriptor_set = None, variables = {}, unknowns = [], timeout = 10, @@ -106,6 +113,8 @@ def cel_verifier_test( expression: str CEL expression to verify (required for check-sat, check-valid, verify-equiv) expression_b: str second CEL expression for equivalence check (required for verify-equiv) policy_file: label of a YAML policy file to verify (required for verify-policy) + file_descriptor_set: label of a transitive FileDescriptorSet (e.g., a proto_descriptor_set + target) declaring the protobuf types used by variables variables: dict of var_name -> type_string (e.g., {"port": "int"}) unknowns: list of str unknown identifiers timeout: int solver timeout in seconds (default 10) @@ -120,6 +129,7 @@ def cel_verifier_test( expression = expression, expression_b = expression_b, policy_file = policy_file, + file_descriptor_set = file_descriptor_set, variables = variables, unknowns = unknowns, timeout = timeout,