Debian Codegraph @

cel/env.go

raw symbols SCIP
1 // Copyright 2019 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 // http://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 cel
16
17 import (
18 "errors"
19 "fmt"
20 "math"
21 "sync"
22
23 "github.com/google/cel-go/checker"
24 chkdecls "github.com/google/cel-go/checker/decls"
25 "github.com/google/cel-go/common"
26 celast "github.com/google/cel-go/common/ast"
27 "github.com/google/cel-go/common/containers"
28 "github.com/google/cel-go/common/decls"
29 "github.com/google/cel-go/common/env"
30 "github.com/google/cel-go/common/functions"
31 "github.com/google/cel-go/common/stdlib"
32 "github.com/google/cel-go/common/types"
33 "github.com/google/cel-go/common/types/ref"
34 "github.com/google/cel-go/interpreter"
35 "github.com/google/cel-go/parser"
36
37 exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
38 "google.golang.org/protobuf/reflect/protoreflect"
39 )
40
41 // Source interface representing a user-provided expression.
42 type Source = common.Source
43
44 // Ast representing the checked or unchecked expression, its source, and related metadata such as
45 // source position information.
46 type Ast struct {
47 source Source
48 impl *celast.AST
49 }
50
51 // NativeRep converts the AST to a Go-native representation.
52 func (ast *Ast) NativeRep() *celast.AST {
53 if ast == nil {
54 return nil
55 }
56 return ast.impl
57 }
58
59 // Expr returns the proto serializable instance of the parsed/checked expression.
60 //
61 // Deprecated: prefer cel.AstToCheckedExpr() or cel.AstToParsedExpr() and call GetExpr()
62 // the result instead.
63 func (ast *Ast) Expr() *exprpb.Expr {
64 if ast == nil {
65 return nil
66 }
67 pbExpr, _ := celast.ExprToProto(ast.NativeRep().Expr())
68 return pbExpr
69 }
70
71 // IsChecked returns whether the Ast value has been successfully type-checked.
72 func (ast *Ast) IsChecked() bool {
73 return ast.NativeRep().IsChecked()
74 }
75
76 // SourceInfo returns character offset and newline position information about expression elements.
77 func (ast *Ast) SourceInfo() *exprpb.SourceInfo {
78 if ast == nil {
79 return nil
80 }
81 pbInfo, _ := celast.SourceInfoToProto(ast.NativeRep().SourceInfo())
82 return pbInfo
83 }
84
85 // ResultType returns the output type of the expression if the Ast has been type-checked, else
86 // returns chkdecls.Dyn as the parse step cannot infer the type.
87 //
88 // Deprecated: use OutputType
89 func (ast *Ast) ResultType() *exprpb.Type {
90 out := ast.OutputType()
91 t, err := TypeToExprType(out)
92 if err != nil {
93 return chkdecls.Dyn
94 }
95 return t
96 }
97
98 // OutputType returns the output type of the expression if the Ast has been type-checked, else
99 // returns cel.DynType as the parse step cannot infer types.
100 func (ast *Ast) OutputType() *Type {
101 if ast == nil {
102 return types.ErrorType
103 }
104 return ast.NativeRep().GetType(ast.NativeRep().Expr().ID())
105 }
106
107 // Source returns a view of the input used to create the Ast. This source may be complete or
108 // constructed from the SourceInfo.
109 func (ast *Ast) Source() Source {
110 if ast == nil {
111 return nil
112 }
113 return ast.source
114 }
115
116 // FormatType converts a type message into a string representation.
117 //
118 // Deprecated: prefer FormatCELType
119 func FormatType(t *exprpb.Type) string {
120 return checker.FormatCheckedType(t)
121 }
122
123 // FormatCELType formats a cel.Type value to a string representation.
124 //
125 // The type formatting is identical to FormatType.
126 func FormatCELType(t *Type) string {
127 return checker.FormatCELType(t)
128 }
129
130 // Env encapsulates the context necessary to perform parsing, type checking, or generation of
131 // evaluable programs for different expressions.
132 type Env struct {
133 Container *containers.Container
134 variables []*decls.VariableDecl
135 functions map[string]*decls.FunctionDecl
136 macros []Macro
137 contextProto protoreflect.MessageDescriptor
138 adapter types.Adapter
139 provider types.Provider
140 features map[int]bool
141 appliedFeatures map[int]bool
142 libraries map[string]SingletonLibrary
143 validators []ASTValidator
144 costOptions []checker.CostOption
145
146 funcBindOnce sync.Once
147 functionBindings []*functions.Overload
148
149 // Internal parser representation
150 prsr *parser.Parser
151 prsrOpts []parser.Option
152
153 // Internal checker representation
154 chkMutex sync.Mutex
155 chk *checker.Env
156 chkErr error
157 chkOnce sync.Once
158 chkOpts []checker.Option
159
160 // Program options tied to the environment
161 progOpts []ProgramOption
162 }
163
164 // ToConfig produces a YAML-serializable env.Config object from the given environment.
165 //
166 // The serialized configuration value is intended to represent a baseline set of config
167 // options which could be used as input to an EnvOption to configure the majority of the
168 // environment from a file.
169 //
170 // Note: validators, features, flags, and safe-guard settings are not yet supported by
171 // the serialize method. Since optimizers are a separate construct from the environment
172 // and the standard expression components (parse, check, evalute), they are also not
173 // supported by the serialize method.
174 func (e *Env) ToConfig(name string) (*env.Config, error) {
175 conf := env.NewConfig(name)
176 // Container settings
177 if e.Container != containers.DefaultContainer {
178 conf.SetContainer(e.Container.Name())
179 }
180 for _, typeName := range e.Container.AliasSet() {
181 conf.AddImports(env.NewImport(typeName))
182 }
183
184 libOverloads := map[string][]string{}
185 for libName, lib := range e.libraries {
186 // Track the options which have been configured by a library and
187 // then diff the library version against the configured function
188 // to detect incremental overloads or rewrites.
189 libEnv, _ := NewCustomEnv()
190 libEnv, _ = Lib(lib)(libEnv)
191 for fnName, fnDecl := range libEnv.Functions() {
192 if len(fnDecl.OverloadDecls()) == 0 {
193 continue
194 }
195 overloads, exist := libOverloads[fnName]
196 if !exist {
197 overloads = make([]string, 0, len(fnDecl.OverloadDecls()))
198 }
199 for _, o := range fnDecl.OverloadDecls() {
200 overloads = append(overloads, o.ID())
201 }
202 libOverloads[fnName] = overloads
203 }
204 subsetLib, canSubset := lib.(LibrarySubsetter)
205 alias := ""
206 if aliasLib, canAlias := lib.(LibraryAliaser); canAlias {
207 alias = aliasLib.LibraryAlias()
208 libName = alias
209 }
210 if libName == "stdlib" && canSubset {
211 conf.SetStdLib(subsetLib.LibrarySubset())
212 continue
213 }
214 version := uint32(math.MaxUint32)
215 if versionLib, isVersioned := lib.(LibraryVersioner); isVersioned {
216 version = versionLib.LibraryVersion()
217 }
218 conf.AddExtensions(env.NewExtension(libName, version))
219 }
220
221 // If this is a custom environment without the standard env, mark the stdlib as disabled.
222 if conf.StdLib == nil && !e.HasLibrary("cel.lib.std") {
223 conf.SetStdLib(env.NewLibrarySubset().SetDisabled(true))
224 }
225
226 // Serialize the variables
227 vars := make([]*decls.VariableDecl, 0, len(e.Variables()))
228 stdTypeVars := map[string]*decls.VariableDecl{}
229 for _, v := range stdlib.Types() {
230 stdTypeVars[v.Name()] = v
231 }
232 for _, v := range e.Variables() {
233 if _, isStdType := stdTypeVars[v.Name()]; isStdType {
234 continue
235 }
236 vars = append(vars, v)
237 }
238 if e.contextProto != nil {
239 conf.SetContextVariable(env.NewContextVariable(string(e.contextProto.FullName())))
240 skipVariables := map[string]bool{}
241 fields := e.contextProto.Fields()
242 for i := 0; i < fields.Len(); i++ {
243 field := fields.Get(i)
244 variable, err := fieldToVariable(field)
245 if err != nil {
246 return nil, fmt.Errorf("could not serialize context field variable %q, reason: %w", field.FullName(), err)
247 }
248 skipVariables[variable.Name()] = true
249 }
250 for _, v := range vars {
251 if _, found := skipVariables[v.Name()]; !found {
252 conf.AddVariableDecls(v)
253 }
254 }
255 } else {
256 conf.AddVariableDecls(vars...)
257 }
258
259 // Serialize functions which are distinct from the ones configured by libraries.
260 for fnName, fnDecl := range e.Functions() {
261 if excludedOverloads, found := libOverloads[fnName]; found {
262 if newDecl := fnDecl.Subset(decls.ExcludeOverloads(excludedOverloads...)); newDecl != nil {
263 conf.AddFunctionDecls(newDecl)
264 }
265 } else {
266 conf.AddFunctionDecls(fnDecl)
267 }
268 }
269
270 // Serialize validators
271 for _, val := range e.Validators() {
272 // Only add configurable validators to the env.Config as all others are
273 // expected to be implicitly enabled via extension libraries.
274 if confVal, ok := val.(ConfigurableASTValidator); ok {
275 conf.AddValidators(confVal.ToConfig())
276 }
277 }
278
279 // Serialize features
280 for featID, enabled := range e.features {
281 featName, found := featureNameByID(featID)
282 if !found {
283 // If the feature isn't named, it isn't intended to be publicly exposed
284 continue
285 }
286 conf.AddFeatures(env.NewFeature(featName, enabled))
287 }
288
289 return conf, nil
290 }
291
292 // NewEnv creates a program environment configured with the standard library of CEL functions and
293 // macros. The Env value returned can parse and check any CEL program which builds upon the core
294 // features documented in the CEL specification.
295 //
296 // See the EnvOption helper functions for the options that can be used to configure the
297 // environment.
298 func NewEnv(opts ...EnvOption) (*Env, error) {
299 // Extend the statically configured standard environment, disabling eager validation to ensure
300 // the cost of setup for the environment is still just as cheap as it is in v0.11.x and earlier
301 // releases. The user provided options can easily re-enable the eager validation as they are
302 // processed after this default option.
303 stdOpts := append([]EnvOption{EagerlyValidateDeclarations(false)}, opts...)
304 env, err := getStdEnv()
305 if err != nil {
306 return nil, err
307 }
308 return env.Extend(stdOpts...)
309 }
310
311 // NewCustomEnv creates a custom program environment which is not automatically configured with the
312 // standard library of functions and macros documented in the CEL spec.
313 //
314 // The purpose for using a custom environment might be for subsetting the standard library produced
315 // by the cel.StdLib() function. Subsetting CEL is a core aspect of its design that allows users to
316 // limit the compute and memory impact of a CEL program by controlling the functions and macros
317 // that may appear in a given expression.
318 //
319 // See the EnvOption helper functions for the options that can be used to configure the
320 // environment.
321 func NewCustomEnv(opts ...EnvOption) (*Env, error) {
322 registry, err := types.NewRegistry()
323 if err != nil {
324 return nil, err
325 }
326 return (&Env{
327 variables: []*decls.VariableDecl{},
328 functions: map[string]*decls.FunctionDecl{},
329 functionBindings: []*functions.Overload{},
330 macros: []parser.Macro{},
331 Container: containers.DefaultContainer,
332 adapter: registry,
333 provider: registry,
334 features: map[int]bool{},
335 appliedFeatures: map[int]bool{},
336 libraries: map[string]SingletonLibrary{},
337 validators: []ASTValidator{},
338 progOpts: []ProgramOption{},
339 costOptions: []checker.CostOption{},
340 }).configure(opts)
341 }
342
343 // Check performs type-checking on the input Ast and yields a checked Ast and/or set of Issues.
344 // If any `ASTValidators` are configured on the environment, they will be applied after a valid
345 // type-check result. If any issues are detected, the validators will provide them on the
346 // output Issues object.
347 //
348 // Either checking or validation has failed if the returned Issues value and its Issues.Err()
349 // value are non-nil. Issues should be inspected if they are non-nil, but may not represent a
350 // fatal error.
351 //
352 // It is possible to have both non-nil Ast and Issues values returned from this call: however,
353 // the mere presence of an Ast does not imply that it is valid for use.
354 func (e *Env) Check(ast *Ast) (*Ast, *Issues) {
355 // Construct the internal checker env, erroring if there is an issue adding the declarations.
356 chk, err := e.initChecker()
357 if err != nil {
358 errs := common.NewErrors(ast.Source())
359 errs.ReportErrorString(common.NoLocation, err.Error())
360 return nil, NewIssuesWithSourceInfo(errs, ast.NativeRep().SourceInfo())
361 }
362
363 checked, errs := checker.Check(ast.NativeRep(), ast.Source(), chk)
364 if len(errs.GetErrors()) > 0 {
365 return nil, NewIssuesWithSourceInfo(errs, ast.NativeRep().SourceInfo())
366 }
367 // Manually create the Ast to ensure that the Ast source information (which may be more
368 // detailed than the information provided by Check), is returned to the caller.
369 ast = &Ast{
370 source: ast.Source(),
371 impl: checked}
372
373 // Avoid creating a validator config if it's not needed.
374 if len(e.validators) == 0 {
375 return ast, nil
376 }
377
378 // Generate a validator configuration from the set of configured validators.
379 vConfig := newValidatorConfig()
380 for _, v := range e.validators {
381 if cv, ok := v.(ASTValidatorConfigurer); ok {
382 cv.Configure(vConfig)
383 }
384 }
385 // Apply additional validators on the type-checked result.
386 iss := NewIssuesWithSourceInfo(errs, ast.NativeRep().SourceInfo())
387 for _, v := range e.validators {
388 v.Validate(e, vConfig, checked, iss)
389 }
390 if iss.Err() != nil {
391 return nil, iss
392 }
393 return ast, nil
394 }
395
396 // Compile combines the Parse and Check phases CEL program compilation to produce an Ast and
397 // associated issues.
398 //
399 // If an error is encountered during parsing the Compile step will not continue with the Check
400 // phase. If non-error issues are encountered during Parse, they may be combined with any issues
401 // discovered during Check.
402 //
403 // Note, for parse-only uses of CEL use Parse.
404 func (e *Env) Compile(txt string) (*Ast, *Issues) {
405 return e.CompileSource(common.NewTextSource(txt))
406 }
407
408 // CompileSource combines the Parse and Check phases CEL program compilation to produce an Ast and
409 // associated issues.
410 //
411 // If an error is encountered during parsing the CompileSource step will not continue with the
412 // Check phase. If non-error issues are encountered during Parse, they may be combined with any
413 // issues discovered during Check.
414 //
415 // Note, for parse-only uses of CEL use Parse.
416 func (e *Env) CompileSource(src Source) (*Ast, *Issues) {
417 ast, iss := e.ParseSource(src)
418 if iss.Err() != nil {
419 return nil, iss
420 }
421 checked, iss2 := e.Check(ast)
422 if iss2.Err() != nil {
423 return nil, iss2
424 }
425 return checked, iss2
426 }
427
428 // Extend the current environment with additional options to produce a new Env.
429 //
430 // Note, the extended Env value should not share memory with the original. It is possible, however,
431 // that a CustomTypeAdapter or CustomTypeProvider options could provide values which are mutable.
432 // To ensure separation of state between extended environments either make sure the TypeAdapter and
433 // TypeProvider are immutable, or that their underlying implementations are based on the
434 // ref.TypeRegistry which provides a Copy method which will be invoked by this method.
435 func (e *Env) Extend(opts ...EnvOption) (*Env, error) {
436 chk, chkErr := e.getCheckerOrError()
437 if chkErr != nil {
438 return nil, chkErr
439 }
440
441 prsrOptsCopy := make([]parser.Option, len(e.prsrOpts))
442 copy(prsrOptsCopy, e.prsrOpts)
443
444 // The type-checker is configured with Declarations. The declarations may either be provided
445 // as options which have not yet been validated, or may come from a previous checker instance
446 // whose types have already been validated.
447 chkOptsCopy := make([]checker.Option, len(e.chkOpts))
448 copy(chkOptsCopy, e.chkOpts)
449
450 // Copy the declarations if needed.
451 if chk != nil {
452 // If the type-checker has already been instantiated, then the e.declarations have been
453 // validated within the chk instance.
454 chkOptsCopy = append(chkOptsCopy, checker.ValidatedDeclarations(chk))
455 }
456 varsCopy := make([]*decls.VariableDecl, len(e.variables))
457 copy(varsCopy, e.variables)
458
459 // Copy macros and program options
460 macsCopy := make([]parser.Macro, len(e.macros))
461 progOptsCopy := make([]ProgramOption, len(e.progOpts))
462 copy(macsCopy, e.macros)
463 copy(progOptsCopy, e.progOpts)
464
465 // Copy the adapter / provider if they appear to be mutable.
466 adapter := e.adapter
467 provider := e.provider
468 adapterReg, isAdapterReg := e.adapter.(*types.Registry)
469 providerReg, isProviderReg := e.provider.(*types.Registry)
470 // In most cases the provider and adapter will be a ref.TypeRegistry;
471 // however, in the rare cases where they are not, they are assumed to
472 // be immutable. Since it is possible to set the TypeProvider separately
473 // from the TypeAdapter, the possible configurations which could use a
474 // TypeRegistry as the base implementation are captured below.
475 if isAdapterReg && isProviderReg {
476 reg := providerReg.Copy()
477 provider = reg
478 // If the adapter and provider are the same object, set the adapter
479 // to the same ref.TypeRegistry as the provider.
480 if adapterReg == providerReg {
481 adapter = reg
482 } else {
483 // Otherwise, make a copy of the adapter.
484 adapter = adapterReg.Copy()
485 }
486 } else if isProviderReg {
487 provider = providerReg.Copy()
488 } else if isAdapterReg {
489 adapter = adapterReg.Copy()
490 }
491
492 featuresCopy := make(map[int]bool, len(e.features))
493 for k, v := range e.features {
494 featuresCopy[k] = v
495 }
496 appliedFeaturesCopy := make(map[int]bool, len(e.appliedFeatures))
497 for k, v := range e.appliedFeatures {
498 appliedFeaturesCopy[k] = v
499 }
500 funcsCopy := make(map[string]*decls.FunctionDecl, len(e.functions))
501 for k, v := range e.functions {
502 funcsCopy[k] = v
503 }
504 libsCopy := make(map[string]SingletonLibrary, len(e.libraries))
505 for k, v := range e.libraries {
506 libsCopy[k] = v
507 }
508 validatorsCopy := make([]ASTValidator, len(e.validators))
509 copy(validatorsCopy, e.validators)
510 costOptsCopy := make([]checker.CostOption, len(e.costOptions))
511 copy(costOptsCopy, e.costOptions)
512
513 ext := &Env{
514 Container: e.Container,
515 variables: varsCopy,
516 functions: funcsCopy,
517 macros: macsCopy,
518 contextProto: e.contextProto,
519 progOpts: progOptsCopy,
520 adapter: adapter,
521 features: featuresCopy,
522 appliedFeatures: appliedFeaturesCopy,
523 libraries: libsCopy,
524 validators: validatorsCopy,
525 provider: provider,
526 chkOpts: chkOptsCopy,
527 prsrOpts: prsrOptsCopy,
528 costOptions: costOptsCopy,
529 }
530 return ext.configure(opts)
531 }
532
533 // HasFeature checks whether the environment enables the given feature
534 // flag, as enumerated in options.go.
535 func (e *Env) HasFeature(flag int) bool {
536 enabled, has := e.features[flag]
537 return has && enabled
538 }
539
540 // HasLibrary returns whether a specific SingletonLibrary has been configured in the environment.
541 func (e *Env) HasLibrary(libName string) bool {
542 _, exists := e.libraries[libName]
543 return exists
544 }
545
546 // Libraries returns a list of SingletonLibrary that have been configured in the environment.
547 func (e *Env) Libraries() []string {
548 libraries := make([]string, 0, len(e.libraries))
549 for libName := range e.libraries {
550 libraries = append(libraries, libName)
551 }
552 return libraries
553 }
554
555 // HasFunction returns whether a specific function has been configured in the environment
556 func (e *Env) HasFunction(functionName string) bool {
557 _, ok := e.functions[functionName]
558 return ok
559 }
560
561 // Functions returns a shallow copy of the Functions, keyed by function name, that have been configured in the environment.
562 func (e *Env) Functions() map[string]*decls.FunctionDecl {
563 shallowCopy := make(map[string]*decls.FunctionDecl, len(e.functions))
564 for nm, fn := range e.functions {
565 shallowCopy[nm] = fn
566 }
567 return shallowCopy
568 }
569
570 // Variables returns a shallow copy of the variables associated with the environment.
571 func (e *Env) Variables() []*decls.VariableDecl {
572 shallowCopy := make([]*decls.VariableDecl, len(e.variables))
573 copy(shallowCopy, e.variables)
574 return shallowCopy
575 }
576
577 // Macros returns a shallow copy of macros associated with the environment.
578 func (e *Env) Macros() []Macro {
579 shallowCopy := make([]Macro, len(e.macros))
580 copy(shallowCopy, e.macros)
581 return shallowCopy
582 }
583
584 // HasValidator returns whether a specific ASTValidator has been configured in the environment.
585 func (e *Env) HasValidator(name string) bool {
586 for _, v := range e.validators {
587 if v.Name() == name {
588 return true
589 }
590 }
591 return false
592 }
593
594 // Validators returns the set of ASTValidators configured on the environment.
595 func (e *Env) Validators() []ASTValidator {
596 return e.validators[:]
597 }
598
599 // Parse parses the input expression value `txt` to a Ast and/or a set of Issues.
600 //
601 // This form of Parse creates a Source value for the input `txt` and forwards to the
602 // ParseSource method.
603 func (e *Env) Parse(txt string) (*Ast, *Issues) {
604 src := common.NewTextSource(txt)
605 return e.ParseSource(src)
606 }
607
608 // ParseSource parses the input source to an Ast and/or set of Issues.
609 //
610 // Parsing has failed if the returned Issues value and its Issues.Err() value is non-nil.
611 // Issues should be inspected if they are non-nil, but may not represent a fatal error.
612 //
613 // It is possible to have both non-nil Ast and Issues values returned from this call; however,
614 // the mere presence of an Ast does not imply that it is valid for use.
615 func (e *Env) ParseSource(src Source) (*Ast, *Issues) {
616 parsed, errs := e.prsr.Parse(src)
617 if len(errs.GetErrors()) > 0 {
618 return nil, &Issues{errs: errs}
619 }
620 return &Ast{source: src, impl: parsed}, nil
621 }
622
623 // Program generates an evaluable instance of the Ast within the environment (Env).
624 func (e *Env) Program(ast *Ast, opts ...ProgramOption) (Program, error) {
625 return e.PlanProgram(ast.NativeRep(), opts...)
626 }
627
628 // PlanProgram generates an evaluable instance of the AST in the go-native representation within
629 // the environment (Env).
630 func (e *Env) PlanProgram(a *celast.AST, opts ...ProgramOption) (Program, error) {
631 optSet := e.progOpts
632 if len(opts) != 0 {
633 mergedOpts := []ProgramOption{}
634 mergedOpts = append(mergedOpts, e.progOpts...)
635 mergedOpts = append(mergedOpts, opts...)
636 optSet = mergedOpts
637 }
638 return newProgram(e, a, optSet)
639 }
640
641 // CELTypeAdapter returns the `types.Adapter` configured for the environment.
642 func (e *Env) CELTypeAdapter() types.Adapter {
643 return e.adapter
644 }
645
646 // CELTypeProvider returns the `types.Provider` configured for the environment.
647 func (e *Env) CELTypeProvider() types.Provider {
648 return e.provider
649 }
650
651 // TypeAdapter returns the `ref.TypeAdapter` configured for the environment.
652 //
653 // Deprecated: use CELTypeAdapter()
654 func (e *Env) TypeAdapter() ref.TypeAdapter {
655 return e.adapter
656 }
657
658 // TypeProvider returns the `ref.TypeProvider` configured for the environment.
659 //
660 // Deprecated: use CELTypeProvider()
661 func (e *Env) TypeProvider() ref.TypeProvider {
662 if legacyProvider, ok := e.provider.(ref.TypeProvider); ok {
663 return legacyProvider
664 }
665 return &interopLegacyTypeProvider{Provider: e.provider}
666 }
667
668 // UnknownVars returns a PartialActivation which marks all variables declared in the Env as
669 // unknown AttributePattern values.
670 //
671 // Note, the UnknownVars will behave the same as an cel.NoVars() unless the PartialAttributes
672 // option is provided as a ProgramOption.
673 func (e *Env) UnknownVars() PartialActivation {
674 act := interpreter.EmptyActivation()
675 part, _ := PartialVars(act, e.computeUnknownVars(act)...)
676 return part
677 }
678
679 // PartialVars returns a PartialActivation where all variables not in the input variable
680 // set, but which have been configured in the environment, are marked as unknown.
681 //
682 // The `vars` value may either be an Activation or any valid input to the cel.NewActivation call.
683 //
684 // Note, this is equivalent to calling cel.PartialVars and manually configuring the set of unknown
685 // variables. For more advanced use cases of partial state where portions of an object graph, rather
686 // than top-level variables, are missing the PartialVars() method may be a more suitable choice.
687 //
688 // Note, the PartialVars will behave the same as cel.NoVars() unless the PartialAttributes
689 // option is provided as a ProgramOption.
690 func (e *Env) PartialVars(vars any) (PartialActivation, error) {
691 act, err := NewActivation(vars)
692 if err != nil {
693 return nil, err
694 }
695 return PartialVars(act, e.computeUnknownVars(act)...)
696 }
697
698 // ResidualAst takes an Ast and its EvalDetails to produce a new Ast which only contains the
699 // attribute references which are unknown.
700 //
701 // Residual expressions are beneficial in a few scenarios:
702 //
703 // - Optimizing constant expression evaluations away.
704 // - Indexing and pruning expressions based on known input arguments.
705 // - Surfacing additional requirements that are needed in order to complete an evaluation.
706 // - Sharing the evaluation of an expression across multiple machines/nodes.
707 //
708 // For example, if an expression targets a 'resource' and 'request' attribute and the possible
709 // values for the resource are known, a PartialActivation could mark the 'request' as an unknown
710 // interpreter.AttributePattern and the resulting ResidualAst would be reduced to only the parts
711 // of the expression that reference the 'request'.
712 //
713 // Note, the expression ids within the residual AST generated through this method have no
714 // correlation to the expression ids of the original AST.
715 //
716 // See the PartialVars helper for how to construct a PartialActivation.
717 //
718 // TODO: Consider adding an option to generate a Program.Residual to avoid round-tripping to an
719 // Ast format and then Program again.
720 func (e *Env) ResidualAst(a *Ast, details *EvalDetails) (*Ast, error) {
721 ast := a.NativeRep()
722 pruned := interpreter.PruneAst(ast.Expr(), ast.SourceInfo().MacroCalls(), details.State())
723 newAST := &Ast{source: a.Source(), impl: pruned}
724 expr, err := AstToString(newAST)
725 if err != nil {
726 return nil, err
727 }
728 parsed, iss := e.Parse(expr)
729 if iss != nil && iss.Err() != nil {
730 return nil, iss.Err()
731 }
732 if !a.IsChecked() {
733 return parsed, nil
734 }
735 checked, iss := e.Check(parsed)
736 if iss != nil && iss.Err() != nil {
737 return nil, iss.Err()
738 }
739 return checked, nil
740 }
741
742 // EstimateCost estimates the cost of a type checked CEL expression using the length estimates of input data and
743 // extension functions provided by estimator.
744 func (e *Env) EstimateCost(ast *Ast, estimator checker.CostEstimator, opts ...checker.CostOption) (checker.CostEstimate, error) {
745 extendedOpts := make([]checker.CostOption, 0, len(e.costOptions))
746 extendedOpts = append(extendedOpts, opts...)
747 extendedOpts = append(extendedOpts, e.costOptions...)
748 return checker.Cost(ast.NativeRep(), estimator, extendedOpts...)
749 }
750
751 // configure applies a series of EnvOptions to the current environment.
752 func (e *Env) configure(opts []EnvOption) (*Env, error) {
753 // Customized the environment using the provided EnvOption values. If an error is
754 // generated at any step this, will be returned as a nil Env with a non-nil error.
755 var err error
756 for _, opt := range opts {
757 e, err = opt(e)
758 if err != nil {
759 return nil, err
760 }
761 }
762
763 // If the default UTC timezone has been disabled, configure the legacy overloads
764 if utcTime, isSet := e.features[featureDefaultUTCTimeZone]; isSet && !utcTime {
765 if !e.appliedFeatures[featureDefaultUTCTimeZone] {
766 e.appliedFeatures[featureDefaultUTCTimeZone] = true
767 e, err = Lib(timeLegacyLibrary{})(e)
768 if err != nil {
769 return nil, err
770 }
771 }
772 }
773
774 // Configure the parser.
775 prsrOpts := []parser.Option{}
776 prsrOpts = append(prsrOpts, e.prsrOpts...)
777 prsrOpts = append(prsrOpts, parser.Macros(e.macros...))
778
779 if e.HasFeature(featureEnableMacroCallTracking) {
780 prsrOpts = append(prsrOpts, parser.PopulateMacroCalls(true))
781 }
782 if e.HasFeature(featureVariadicLogicalASTs) {
783 prsrOpts = append(prsrOpts, parser.EnableVariadicOperatorASTs(true))
784 }
785 if e.HasFeature(featureIdentEscapeSyntax) {
786 prsrOpts = append(prsrOpts, parser.EnableIdentEscapeSyntax(true))
787 }
788 e.prsr, err = parser.NewParser(prsrOpts...)
789 if err != nil {
790 return nil, err
791 }
792
793 // Ensure that the checker init happens eagerly rather than lazily.
794 if e.HasFeature(featureEagerlyValidateDeclarations) {
795 _, err := e.initChecker()
796 if err != nil {
797 return nil, err
798 }
799 }
800
801 return e, nil
802 }
803
804 func (e *Env) initChecker() (*checker.Env, error) {
805 e.chkOnce.Do(func() {
806 chkOpts := []checker.Option{}
807 chkOpts = append(chkOpts, e.chkOpts...)
808 chkOpts = append(chkOpts,
809 checker.CrossTypeNumericComparisons(
810 e.HasFeature(featureCrossTypeNumericComparisons)))
811
812 ce, err := checker.NewEnv(e.Container, e.provider, chkOpts...)
813 if err != nil {
814 e.setCheckerOrError(nil, err)
815 return
816 }
817 // Add the statically configured declarations.
818 err = ce.AddIdents(e.variables...)
819 if err != nil {
820 e.setCheckerOrError(nil, err)
821 return
822 }
823 // Add the function declarations which are derived from the FunctionDecl instances.
824 for _, fn := range e.functions {
825 if fn.IsDeclarationDisabled() {
826 continue
827 }
828 err = ce.AddFunctions(fn)
829 if err != nil {
830 e.setCheckerOrError(nil, err)
831 return
832 }
833 }
834 // Add function declarations here separately.
835 e.setCheckerOrError(ce, nil)
836 })
837 return e.getCheckerOrError()
838 }
839
840 // setCheckerOrError sets the checker.Env or error state in a concurrency-safe manner
841 func (e *Env) setCheckerOrError(chk *checker.Env, chkErr error) {
842 e.chkMutex.Lock()
843 e.chk = chk
844 e.chkErr = chkErr
845 e.chkMutex.Unlock()
846 }
847
848 // getCheckerOrError gets the checker.Env or error state in a concurrency-safe manner
849 func (e *Env) getCheckerOrError() (*checker.Env, error) {
850 e.chkMutex.Lock()
851 defer e.chkMutex.Unlock()
852 return e.chk, e.chkErr
853 }
854
855 // computeUnknownVars determines a set of missing variables based on the input activation and the
856 // environment's configured declaration set.
857 func (e *Env) computeUnknownVars(vars Activation) []*interpreter.AttributePattern {
858 var unknownPatterns []*interpreter.AttributePattern
859 for _, v := range e.variables {
860 varName := v.Name()
861 if _, found := vars.ResolveName(varName); found {
862 continue
863 }
864 unknownPatterns = append(unknownPatterns, interpreter.NewAttributePattern(varName))
865 }
866 return unknownPatterns
867 }
868
869 // Error type which references an expression id, a location within source, and a message.
870 type Error = common.Error
871
872 // Issues defines methods for inspecting the error details of parse and check calls.
873 //
874 // Note: in the future, non-fatal warnings and notices may be inspectable via the Issues struct.
875 type Issues struct {
876 errs *common.Errors
877 info *celast.SourceInfo
878 }
879
880 // NewIssues returns an Issues struct from a common.Errors object.
881 func NewIssues(errs *common.Errors) *Issues {
882 return NewIssuesWithSourceInfo(errs, nil)
883 }
884
885 // NewIssuesWithSourceInfo returns an Issues struct from a common.Errors object with SourceInfo metatata
886 // which can be used with the `ReportErrorAtID` method for additional error reports within the context
887 // information that's inferred from an expression id.
888 func NewIssuesWithSourceInfo(errs *common.Errors, info *celast.SourceInfo) *Issues {
889 return &Issues{
890 errs: errs,
891 info: info,
892 }
893 }
894
895 // Err returns an error value if the issues list contains one or more errors.
896 func (i *Issues) Err() error {
897 if i == nil {
898 return nil
899 }
900 if len(i.Errors()) > 0 {
901 return errors.New(i.String())
902 }
903 return nil
904 }
905
906 // Errors returns the collection of errors encountered in more granular detail.
907 func (i *Issues) Errors() []*Error {
908 if i == nil {
909 return []*Error{}
910 }
911 return i.errs.GetErrors()
912 }
913
914 // Append collects the issues from another Issues struct into a new Issues object.
915 func (i *Issues) Append(other *Issues) *Issues {
916 if i == nil {
917 return other
918 }
919 if other == nil || i == other {
920 return i
921 }
922 return NewIssuesWithSourceInfo(i.errs.Append(other.errs.GetErrors()), i.info)
923 }
924
925 // String converts the issues to a suitable display string.
926 func (i *Issues) String() string {
927 if i == nil {
928 return ""
929 }
930 return i.errs.ToDisplayString()
931 }
932
933 // ReportErrorAtID reports an error message with an optional set of formatting arguments.
934 //
935 // The source metadata for the expression at `id`, if present, is attached to the error report.
936 // To ensure that source metadata is attached to error reports, use NewIssuesWithSourceInfo.
937 func (i *Issues) ReportErrorAtID(id int64, message string, args ...any) {
938 i.errs.ReportErrorAtID(id, i.info.GetStartLocation(id), message, args...)
939 }
940
941 // getStdEnv lazy initializes the CEL standard environment.
942 func getStdEnv() (*Env, error) {
943 stdEnvInit.Do(func() {
944 stdEnv, stdEnvErr = NewCustomEnv(StdLib(), EagerlyValidateDeclarations(true))
945 })
946 return stdEnv, stdEnvErr
947 }
948
949 // interopCELTypeProvider layers support for the types.Provider interface on top of a ref.TypeProvider.
950 type interopCELTypeProvider struct {
951 ref.TypeProvider
952 }
953
954 // FindStructType returns a types.Type instance for the given fully-qualified typeName if one exists.
955 //
956 // This method proxies to the underlying ref.TypeProvider's FindType method and converts protobuf type
957 // into a native type representation. If the conversion fails, the type is listed as not found.
958 func (p *interopCELTypeProvider) FindStructType(typeName string) (*types.Type, bool) {
959 if et, found := p.FindType(typeName); found {
960 t, err := types.ExprTypeToType(et)
961 if err != nil {
962 return nil, false
963 }
964 return t, true
965 }
966 return nil, false
967 }
968
969 // FindStructFieldNames returns an empty set of field for the interop provider.
970 //
971 // To inspect the field names, migrate to a `types.Provider` implementation.
972 func (p *interopCELTypeProvider) FindStructFieldNames(typeName string) ([]string, bool) {
973 return []string{}, false
974 }
975
976 // FindStructFieldType returns a types.FieldType instance for the given fully-qualified typeName and field
977 // name, if one exists.
978 //
979 // This method proxies to the underlying ref.TypeProvider's FindFieldType method and converts protobuf type
980 // into a native type representation. If the conversion fails, the type is listed as not found.
981 func (p *interopCELTypeProvider) FindStructFieldType(structType, fieldName string) (*types.FieldType, bool) {
982 if ft, found := p.FindFieldType(structType, fieldName); found {
983 t, err := types.ExprTypeToType(ft.Type)
984 if err != nil {
985 return nil, false
986 }
987 return &types.FieldType{
988 Type: t,
989 IsSet: ft.IsSet,
990 GetFrom: ft.GetFrom,
991 }, true
992 }
993 return nil, false
994 }
995
996 // interopLegacyTypeProvider layers support for the ref.TypeProvider interface on top of a types.Provider.
997 type interopLegacyTypeProvider struct {
998 types.Provider
999 }
1000
1001 // FindType retruns the protobuf Type representation for the input type name if one exists.
1002 //
1003 // This method proxies to the underlying types.Provider FindStructType method and converts the types.Type
1004 // value to a protobuf Type representation.
1005 //
1006 // Failure to convert the type will result in the type not being found.
1007 func (p *interopLegacyTypeProvider) FindType(typeName string) (*exprpb.Type, bool) {
1008 if t, found := p.FindStructType(typeName); found {
1009 et, err := types.TypeToExprType(t)
1010 if err != nil {
1011 return nil, false
1012 }
1013 return et, true
1014 }
1015 return nil, false
1016 }
1017
1018 // FindFieldType returns the protobuf-based FieldType representation for the input type name and field,
1019 // if one exists.
1020 //
1021 // This call proxies to the types.Provider FindStructFieldType method and converts the types.FIeldType
1022 // value to a protobuf-based ref.FieldType representation if found.
1023 //
1024 // Failure to convert the FieldType will result in the field not being found.
1025 func (p *interopLegacyTypeProvider) FindFieldType(structType, fieldName string) (*ref.FieldType, bool) {
1026 if cft, found := p.FindStructFieldType(structType, fieldName); found {
1027 et, err := types.TypeToExprType(cft.Type)
1028 if err != nil {
1029 return nil, false
1030 }
1031 return &ref.FieldType{
1032 Type: et,
1033 IsSet: cft.IsSet,
1034 GetFrom: cft.GetFrom,
1035 }, true
1036 }
1037 return nil, false
1038 }
1039
1040 var (
1041 stdEnvInit sync.Once
1042 stdEnv *Env
1043 stdEnvErr error
1044 )