Debian Codegraph @

debian/missing-sources/github.com/google/cel-go/tools/compiler/compiler.go

raw symbols SCIP
1 // Copyright 2025 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package compiler exposes a standard way to set up a compiler which can be used for CEL
16 // expressions and policies.
17 package compiler
18
19 import (
20 "fmt"
21 "os"
22 "path/filepath"
23 "sync"
24
25 "go.yaml.in/yaml/v3"
26
27 "github.com/google/cel-go/cel"
28 "github.com/google/cel-go/common"
29 "github.com/google/cel-go/common/env"
30 "github.com/google/cel-go/common/types"
31 "github.com/google/cel-go/ext"
32 "github.com/google/cel-go/policy"
33 "google.golang.org/protobuf/encoding/prototext"
34 "google.golang.org/protobuf/proto"
35 "google.golang.org/protobuf/reflect/protoreflect"
36
37 celpb "cel.dev/expr"
38 configpb "cel.dev/expr/conformance"
39 exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
40 descpb "google.golang.org/protobuf/types/descriptorpb"
41 )
42
43 // FileFormat represents the format of the file being loaded.
44 type FileFormat int
45
46 const (
47 // Unspecified is used when the file format is not determined.
48 Unspecified FileFormat = iota + 1
49 // BinaryProto is used for a binary proto file.
50 BinaryProto
51 // TextProto is used for a text proto file.
52 TextProto
53 // TextYAML is used for a YAML file.
54 TextYAML
55 // CELString is used for a CEL string expression defined in a file with .cel extension.
56 CELString
57 // CELPolicy is used for a CEL policy file with .celpolicy extension.
58 CELPolicy
59 )
60
61 // ExpressionType is an enum for the type of input expression.
62 type ExpressionType int
63
64 const (
65 // ExpressionTypeUnspecified is used when the expression type is not specified.
66 ExpressionTypeUnspecified ExpressionType = iota
67 // CompiledExpressionFile is file containing a checked expression.
68 CompiledExpressionFile
69 // PolicyFile is a file containing a CEL policy.
70 PolicyFile
71 // ExpressionFile is a file containing a CEL expression.
72 ExpressionFile
73 // RawExpressionString is a raw CEL expression string.
74 RawExpressionString
75 )
76
77 // PolicyMetadataEnvOption represents a function which accepts a policy metadata map and returns an
78 // environment option used to extend the CEL environment.
79 //
80 // The policy metadata map is generally produced as a byproduct of parsing the policy and it can
81 // be optionally customised by providing a custom policy parser.
82 type PolicyMetadataEnvOption func(map[string]any) cel.EnvOption
83
84 // Compiler interface is used to set up a compiler with the following capabilities:
85 // - create a CEL environment
86 // - create a policy parser
87 // - fetch policy compiler options
88 // - fetch policy environment options
89 //
90 // Note: This compiler is not the same as the CEL expression compiler, rather it provides an
91 // abstraction layer which can create the different components needed for parsing and compiling CEL
92 // expressions and policies.
93 type Compiler interface {
94 // CreateEnv creates a singleton CEL environment with the configured environment options.
95 CreateEnv() (*cel.Env, error)
96 // CreatePolicyParser creates a policy parser using the optionally configured parser options.
97 CreatePolicyParser() (*policy.Parser, error)
98 // PolicyCompilerOptions returns the policy compiler options.
99 PolicyCompilerOptions() []policy.CompilerOption
100 // PolicyMetadataEnvOptions returns the policy metadata environment options.
101 PolicyMetadataEnvOptions() []PolicyMetadataEnvOption
102 }
103
104 type compiler struct {
105 envOptions []cel.EnvOption
106 policyParserOptions []policy.ParserOption
107 policyCompilerOptions []policy.CompilerOption
108 policyMetadataEnvOptions []PolicyMetadataEnvOption
109 env *cel.Env
110 doOnce sync.Once
111 }
112
113 // NewCompiler creates a new compiler with a set of functional options.
114 func NewCompiler(opts ...any) (Compiler, error) {
115 c := &compiler{
116 envOptions: []cel.EnvOption{},
117 policyParserOptions: []policy.ParserOption{},
118 policyCompilerOptions: []policy.CompilerOption{},
119 policyMetadataEnvOptions: []PolicyMetadataEnvOption{},
120 }
121 for _, opt := range opts {
122 switch opt := opt.(type) {
123 case cel.EnvOption:
124 c.envOptions = append(c.envOptions, opt)
125 case policy.ParserOption:
126 c.policyParserOptions = append(c.policyParserOptions, opt)
127 case policy.CompilerOption:
128 c.policyCompilerOptions = append(c.policyCompilerOptions, opt)
129 case PolicyMetadataEnvOption:
130 c.policyMetadataEnvOptions = append(c.policyMetadataEnvOptions, opt)
131 default:
132 return nil, fmt.Errorf("unsupported compiler option: %v", opt)
133 }
134 }
135 c.envOptions = append(c.envOptions, extensionOpt())
136 return c, nil
137 }
138
139 func extensionOpt() cel.EnvOption {
140 return func(e *cel.Env) (*cel.Env, error) {
141 envConfig := &env.Config{
142 Extensions: []*env.Extension{
143 &env.Extension{Name: "optional", Version: "latest"},
144 &env.Extension{Name: "bindings", Version: "latest"},
145 },
146 }
147 return e.Extend(cel.FromConfig(envConfig, ext.ExtensionOptionFactory))
148 }
149 }
150
151 // CreateEnv creates a singleton CEL environment with the configured environment options.
152 func (c *compiler) CreateEnv() (*cel.Env, error) {
153 var err error
154 c.doOnce.Do(func() {
155 c.env, err = cel.NewCustomEnv(c.envOptions...)
156 })
157 return c.env, err
158 }
159
160 // CreatePolicyParser creates a policy parser using the optionally configured parser options.
161 func (c *compiler) CreatePolicyParser() (*policy.Parser, error) {
162 return policy.NewParser(c.policyParserOptions...)
163 }
164
165 // PolicyCompilerOptions returns the policy compiler options configured in the compiler.
166 func (c *compiler) PolicyCompilerOptions() []policy.CompilerOption {
167 return c.policyCompilerOptions
168 }
169
170 // PolicyMetadataEnvOptions returns the policy metadata environment options configured in the compiler.
171 func (c *compiler) PolicyMetadataEnvOptions() []PolicyMetadataEnvOption {
172 return c.policyMetadataEnvOptions
173 }
174
175 func loadFile(path string) ([]byte, error) {
176 data, err := os.ReadFile(path)
177 if err != nil {
178 return nil, fmt.Errorf("failed to read file %q: %v", path, err)
179 }
180 return data, err
181 }
182
183 func loadProtoFile(path string, format FileFormat, out protoreflect.ProtoMessage) error {
184 unmarshaller := proto.Unmarshal
185 if format == TextProto {
186 unmarshaller = prototext.Unmarshal
187 }
188 data, err := loadFile(path)
189 if err != nil {
190 return err
191 }
192 return unmarshaller(data, out)
193 }
194
195 // InferFileFormat infers the file format from the file path.
196 func InferFileFormat(path string) FileFormat {
197 extension := filepath.Ext(path)
198 switch extension {
199 case ".textproto":
200 return TextProto
201 case ".yaml":
202 return TextYAML
203 case ".binarypb", ".fds", ".pb":
204 return BinaryProto
205 case ".cel":
206 return CELString
207 case ".celpolicy":
208 return CELPolicy
209 default:
210 return Unspecified
211 }
212 }
213
214 // EnvironmentFile returns an EnvOption which loads a serialized CEL environment from a file.
215 // The file must be in one of the following formats:
216 // - Textproto
217 // - YAML
218 // - Binarypb
219 func EnvironmentFile(path string) cel.EnvOption {
220 return func(e *cel.Env) (*cel.Env, error) {
221 format := InferFileFormat(path)
222 if format != TextProto && format != TextYAML && format != BinaryProto {
223 return nil, fmt.Errorf("file extension must be one of .textproto, .yaml, .binarypb: found %v", format)
224 }
225 var envConfig *env.Config
226 var fileDescriptorSet *descpb.FileDescriptorSet
227 switch format {
228 case TextProto, BinaryProto:
229 pbEnv := &configpb.Environment{}
230 var err error
231 if err = loadProtoFile(path, format, pbEnv); err != nil {
232 return nil, err
233 }
234 envConfig, fileDescriptorSet, err = envProtoToConfig(pbEnv)
235 if err != nil {
236 return nil, err
237 }
238 case TextYAML:
239 envConfig = &env.Config{}
240 data, err := loadFile(path)
241 if err != nil {
242 return nil, err
243 }
244 err = yaml.Unmarshal(data, envConfig)
245 if err != nil {
246 return nil, fmt.Errorf("yaml.Unmarshal failed to map CEL environment: %w", err)
247 }
248 default:
249 return nil, fmt.Errorf("unsupported format: %v, file: %s", format, path)
250 }
251 var envOpts []cel.EnvOption
252 if fileDescriptorSet != nil {
253 envOpts = append(envOpts, cel.TypeDescs(fileDescriptorSet))
254 }
255 envOpts = append(envOpts, cel.FromConfig(envConfig, ext.ExtensionOptionFactory))
256 var err error
257 e, err = e.Extend(envOpts...)
258 if err != nil {
259 return nil, fmt.Errorf("e.Extend() with env options %v failed: %w", envOpts, err)
260 }
261 return e, nil
262 }
263 }
264
265 func envProtoToConfig(pbEnv *configpb.Environment) (*env.Config, *descpb.FileDescriptorSet, error) {
266 if pbEnv == nil {
267 return nil, nil, fmt.Errorf("proto environment is not set")
268 }
269 envConfig := env.NewConfig(pbEnv.GetName())
270 envConfig.Description = pbEnv.GetDescription()
271 envConfig.SetContainer(pbEnv.GetContainer())
272 for _, imp := range pbEnv.GetImports() {
273 envConfig.AddImports(env.NewImport(imp.GetName()))
274 }
275 stdLib, err := envToStdLib(pbEnv)
276 if err != nil {
277 return nil, nil, err
278 }
279 envConfig.SetStdLib(stdLib)
280 extensions := make([]*env.Extension, 0, len(pbEnv.GetExtensions()))
281 for _, extension := range pbEnv.GetExtensions() {
282 extensions = append(extensions, &env.Extension{Name: extension.GetName(), Version: extension.GetVersion()})
283 }
284 envConfig.AddExtensions(extensions...)
285 if contextVariable := pbEnv.GetContextVariable(); contextVariable != nil {
286 envConfig.SetContextVariable(env.NewContextVariable(contextVariable.GetTypeName()))
287 }
288 functions, variables, err := protoDeclToFunctionsAndVariables(pbEnv.GetDeclarations())
289 if err != nil {
290 return nil, nil, err
291 }
292 envConfig.AddFunctions(functions...)
293 envConfig.AddVariables(variables...)
294 validators, err := envToValidators(pbEnv)
295 if err != nil {
296 return nil, nil, err
297 }
298 envConfig.AddValidators(validators...)
299 features, err := envToFeatures(pbEnv)
300 if err != nil {
301 return nil, nil, err
302 }
303 envConfig.AddFeatures(features...)
304 fileDescriptorSet := pbEnv.GetMessageTypeExtension()
305 return envConfig, fileDescriptorSet, nil
306 }
307
308 func envToFeatures(pbEnv *configpb.Environment) ([]*env.Feature, error) {
309 features := make([]*env.Feature, 0, len(pbEnv.GetFeatures())+1)
310 for _, feature := range pbEnv.GetFeatures() {
311 features = append(features, env.NewFeature(feature.GetName(), feature.GetEnabled()))
312 }
313 if pbEnv.GetEnableMacroCallTracking() {
314 features = append(features, env.NewFeature("cel.feature.macro_call_tracking", true))
315 }
316 return features, nil
317 }
318
319 func envToValidators(pbEnv *configpb.Environment) ([]*env.Validator, error) {
320 validators := make([]*env.Validator, 0, len(pbEnv.GetValidators()))
321 for _, pbValidator := range pbEnv.GetValidators() {
322 validator := env.NewValidator(pbValidator.GetName())
323 config := map[string]any{}
324 for k, v := range pbValidator.GetConfig() {
325 val := types.DefaultTypeAdapter.NativeToValue(v)
326 config[k] = val.Value()
327 }
328 validator.SetConfig(config)
329 validators = append(validators, validator)
330 }
331 return validators, nil
332 }
333
334 func protoDeclToFunctionsAndVariables(declarations []*celpb.Decl) ([]*env.Function, []*env.Variable, error) {
335 functions := make([]*env.Function, 0, len(declarations))
336 variables := make([]*env.Variable, 0, len(declarations))
337 for _, decl := range declarations {
338 switch decl.GetDeclKind().(type) {
339 case *celpb.Decl_Function:
340 fn, err := protoDeclToFunction(decl)
341 if err != nil {
342 return nil, nil, fmt.Errorf("protoDeclToFunction(%s) failed to create function: %w", decl.GetName(), err)
343 }
344 functions = append(functions, fn)
345 case *celpb.Decl_Ident:
346 t, err := types.ProtoAsType(decl.GetIdent().GetType())
347 if err != nil {
348 return nil, nil, fmt.Errorf("types.ProtoAsType(%s) failed to create type: %w", decl.GetIdent().GetType(), err)
349 }
350 variables = append(variables, env.NewVariable(decl.GetName(), env.SerializeTypeDesc(t)))
351 }
352 }
353 return functions, variables, nil
354 }
355
356 func envToStdLib(pbEnv *configpb.Environment) (*env.LibrarySubset, error) {
357 stdLib := env.NewLibrarySubset()
358 pbEnvStdLib := pbEnv.GetStdlib()
359 if pbEnvStdLib == nil {
360 if pbEnv.GetDisableStandardCelDeclarations() {
361 stdLib.SetDisabled(true)
362 return stdLib, nil
363 }
364 return nil, nil
365 }
366 if !stdLib.Disabled {
367 stdLib.SetDisabled(pbEnvStdLib.GetDisabled())
368 }
369 stdLib.SetDisableMacros(pbEnvStdLib.GetDisableMacros())
370 stdLib.AddIncludedMacros(pbEnvStdLib.GetIncludeMacros()...)
371 stdLib.AddExcludedMacros(pbEnvStdLib.GetExcludeMacros()...)
372 if pbEnvStdLib.GetIncludeFunctions() != nil {
373 for _, includeFn := range pbEnvStdLib.GetIncludeFunctions() {
374 if includeFn.GetFunction() != nil {
375 fn, err := protoDeclToFunction(includeFn)
376 if err != nil {
377 return nil, err
378 }
379 stdLib.AddIncludedFunctions(fn)
380 } else {
381 return nil, fmt.Errorf("IncludeFunctions must specify a function decl")
382 }
383 }
384 }
385 if pbEnvStdLib.GetExcludeFunctions() != nil {
386 for _, excludeFn := range pbEnvStdLib.GetExcludeFunctions() {
387 if excludeFn.GetFunction() != nil {
388 fn, err := protoDeclToFunction(excludeFn)
389 if err != nil {
390 return nil, err
391 }
392 stdLib.AddExcludedFunctions(fn)
393 } else {
394 return nil, fmt.Errorf("ExcludeFunctions must specify a function decl")
395 }
396 }
397 }
398 return stdLib, nil
399 }
400
401 func protoDeclToFunction(decl *celpb.Decl) (*env.Function, error) {
402 declFn := decl.GetFunction()
403 if declFn == nil {
404 return nil, nil
405 }
406 overloads := make([]*env.Overload, 0, len(declFn.GetOverloads()))
407 for _, o := range declFn.GetOverloads() {
408 args := make([]*env.TypeDesc, 0, len(o.GetParams()))
409 for _, p := range o.GetParams() {
410 t, err := types.ProtoAsType(p)
411 if err != nil {
412 return nil, err
413 }
414 args = append(args, env.SerializeTypeDesc(t))
415 }
416 res, err := types.ProtoAsType(o.GetResultType())
417 if err != nil {
418 return nil, err
419 }
420 ret := env.SerializeTypeDesc(res)
421 if o.IsInstanceFunction {
422 overloads = append(overloads, env.NewMemberOverload(o.GetOverloadId(), args[0], args[1:], ret))
423 } else {
424 overloads = append(overloads, env.NewOverload(o.GetOverloadId(), args, ret))
425 }
426 }
427 return env.NewFunction(decl.GetName(), overloads...), nil
428 }
429
430 // TypeDescriptorSetFile returns an EnvOption which loads type descriptors from a file.
431 // The file must be in binary format.
432 func TypeDescriptorSetFile(path string) cel.EnvOption {
433 return func(e *cel.Env) (*cel.Env, error) {
434 format := InferFileFormat(path)
435 if format != BinaryProto {
436 return nil, fmt.Errorf("type descriptor must be in binary format")
437 }
438 fds := &descpb.FileDescriptorSet{}
439 if err := loadProtoFile(path, BinaryProto, fds); err != nil {
440 return nil, err
441 }
442 var err error
443 e, err = e.Extend(cel.TypeDescs(fds))
444 if err != nil {
445 return nil, fmt.Errorf("e.Extend() with type descriptor set %v failed: %w", fds, err)
446 }
447 return e, nil
448 }
449 }
450
451 // InputExpression is an interface for an expression which can be compiled into a CEL AST and return
452 // an optional policy metadata map.
453 type InputExpression interface {
454 // CreateAST creates a CEL AST from the input expression using the provided compiler.
455 CreateAST(Compiler) (*cel.Ast, map[string]any, error)
456 }
457
458 // CompiledExpression is an InputExpression which loads a CheckedExpr from a file.
459 type CompiledExpression struct {
460 Path string
461 }
462
463 // CreateAST creates a CEL AST from a checked expression file.
464 // The file must be in one of the following formats:
465 // - Binarypb
466 // - Textproto
467 func (c *CompiledExpression) CreateAST(_ Compiler) (*cel.Ast, map[string]any, error) {
468 var expr exprpb.CheckedExpr
469 format := InferFileFormat(c.Path)
470 if format != BinaryProto && format != TextProto {
471 return nil, nil, fmt.Errorf("invalid file extension wanted: .binarypb or .textproto found: %v", format)
472 }
473 if err := loadProtoFile(c.Path, format, &expr); err != nil {
474 return nil, nil, err
475 }
476 return cel.CheckedExprToAst(&expr), nil, nil
477 }
478
479 // FileExpression is an InputExpression which loads a CEL expression or policy from a file.
480 type FileExpression struct {
481 Path string
482 }
483
484 // CreateAST creates a CEL AST from a file using the provided compiler:
485 // - All policy metadata options are executed using the policy metadata map to extend the
486 // environment.
487 // - All policy compiler options are passed on to compile the parsed policy.
488 //
489 // The file must be in one of the following formats:
490 // - .cel: CEL string expression
491 // - .celpolicy: CEL policy
492 func (f *FileExpression) CreateAST(compiler Compiler) (*cel.Ast, map[string]any, error) {
493 e, err := compiler.CreateEnv()
494 if err != nil {
495 return nil, nil, err
496 }
497 format := InferFileFormat(f.Path)
498 switch format {
499 case CELString:
500 data, err := loadFile(f.Path)
501 if err != nil {
502 return nil, nil, err
503 }
504 src := common.NewStringSource(string(data), f.Path)
505 ast, iss := e.CompileSource(src)
506 if iss.Err() != nil {
507 return nil, nil, fmt.Errorf("e.CompileSource(%q) failed: %w", src.Content(), iss.Err())
508 }
509 return ast, nil, nil
510 case CELPolicy, TextYAML:
511 data, err := loadFile(f.Path)
512 if err != nil {
513 return nil, nil, err
514 }
515 src := policy.ByteSource(data, f.Path)
516 parser, err := compiler.CreatePolicyParser()
517 if err != nil {
518 return nil, nil, err
519 }
520 p, iss := parser.Parse(src)
521 if iss.Err() != nil {
522 return nil, nil, fmt.Errorf("parser.Parse(%q) failed: %w", src.Content(), iss.Err())
523 }
524 policyMetadata := clonePolicyMetadata(p)
525 for _, opt := range compiler.PolicyMetadataEnvOptions() {
526 if e, err = e.Extend(opt(policyMetadata)); err != nil {
527 return nil, nil, fmt.Errorf("e.Extend() with metadata option failed: %w", err)
528 }
529 }
530 ast, iss := policy.Compile(e, p, compiler.PolicyCompilerOptions()...)
531 if iss.Err() != nil {
532 return nil, nil, fmt.Errorf("policy.Compile(%q) failed: %w", src.Content(), iss.Err())
533 }
534 return ast, policyMetadata, nil
535 default:
536 return nil, nil, fmt.Errorf("invalid file extension wanted: .cel or .celpolicy or .yaml found: %v", format)
537 }
538 }
539
540 func clonePolicyMetadata(p *policy.Policy) map[string]any {
541 metadataKeys := p.MetadataKeys()
542 metadata := make(map[string]any, len(metadataKeys))
543 for _, key := range metadataKeys {
544 value, _ := p.Metadata(key)
545 metadata[key] = value
546 }
547 return metadata
548 }
549
550 // RawExpression is an InputExpression which loads a CEL expression from a string.
551 type RawExpression struct {
552 Value string
553 }
554
555 // CreateAST creates a CEL AST from a raw CEL expression using the provided compiler.
556 func (r *RawExpression) CreateAST(compiler Compiler) (*cel.Ast, map[string]any, error) {
557 e, err := compiler.CreateEnv()
558 if err != nil {
559 return nil, nil, err
560 }
561 format := InferFileFormat(r.Value)
562 if format != Unspecified {
563 return nil, nil, fmt.Errorf("invalid raw expression found file with extension: %v", format)
564 }
565 ast, iss := e.Compile(r.Value)
566 if iss.Err() != nil {
567 return nil, nil, fmt.Errorf("e.Compile(%q) failed: %w", r.Value, iss.Err())
568 }
569 return ast, nil, nil
570 }