From 18b43e0b56e868b6e7cedbb7f38e4a99d96a5154 Mon Sep 17 00:00:00 2001 From: Sean Huh Date: Tue, 24 Nov 2026 13:03:30 -0800 Subject: [PATCH] Support protobuf message and enum variables in the cel-verifier CLI PiperOrigin-RevId: 1029281972 --- .../java/dev/cel/verifier/tools/BUILD.bazel | 2 + .../cel/verifier/tools/CelVerifierRepl.java | 4 +- .../cel/verifier/tools/CelVerifierTool.java | 37 +++++-- .../verifier/tools/CelVerifierToolCore.java | 16 +-- .../verifier/tools/VerificationOptions.java | 50 ++++++++-- .../java/dev/cel/verifier/tools/BUILD.bazel | 3 + .../verifier/tools/CelVerifierToolTest.java | 99 ++++++++++++++++--- .../tools/VerificationOptionsTest.java | 84 +++++++++------- verifier/tools/README.md | 15 ++- 9 files changed, 234 insertions(+), 76 deletions(-) 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..902903b89 100644 --- a/verifier/src/main/java/dev/cel/verifier/tools/CelVerifierRepl.java +++ b/verifier/src/main/java/dev/cel/verifier/tools/CelVerifierRepl.java @@ -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() { @@ -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) { 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..a4c8fe213 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,9 @@ 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; @@ -22,6 +25,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; @@ -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 vars) throws Exception; @@ -128,7 +137,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,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) { 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/CelVerifierToolTest.java b/verifier/src/test/java/dev/cel/verifier/tools/CelVerifierToolTest.java index 755c8ebe7..79262233b 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,13 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +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 +45,7 @@ @RunWith(JUnit4.class) public final class CelVerifierToolTest { + private static final VerificationOptions OPTIONS = VerificationOptions.builder().build(); @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @@ -60,6 +64,78 @@ 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_checkSat_jsonOutputFormat() { String output = @@ -153,27 +229,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 +264,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 +335,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/README.md b/verifier/tools/README.md index d008c1d1e..e37b02b16 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