| 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 | "context" |
| 19 | "fmt" |
| 20 | "sync" |
| 21 | |
| 22 | "github.com/google/cel-go/common/ast" |
| 23 | "github.com/google/cel-go/common/functions" |
| 24 | "github.com/google/cel-go/common/types" |
| 25 | "github.com/google/cel-go/common/types/ref" |
| 26 | "github.com/google/cel-go/interpreter" |
| 27 | ) |
| 28 | |
| 29 | // Program is an evaluable view of an Ast. |
| 30 | type Program interface { |
| 31 | // Eval returns the result of an evaluation of the Ast and environment against the input vars. |
| 32 | // |
| 33 | // The vars value may either be an `Activation` or a `map[string]any`. |
| 34 | // |
| 35 | // If the `OptTrackState`, `OptTrackCost` or `OptExhaustiveEval` flags are used, the `details` response will |
| 36 | // be non-nil. Given this caveat on `details`, the return state from evaluation will be: |
| 37 | // |
| 38 | // * `val`, `details`, `nil` - Successful evaluation of a non-error result. |
| 39 | // * `val`, `details`, `err` - Successful evaluation to an error result. |
| 40 | // * `nil`, `details`, `err` - Unsuccessful evaluation. |
| 41 | // |
| 42 | // An unsuccessful evaluation is typically the result of a series of incompatible `EnvOption` |
| 43 | // or `ProgramOption` values used in the creation of the evaluation environment or executable |
| 44 | // program. |
| 45 | Eval(any) (ref.Val, *EvalDetails, error) |
| 46 | |
| 47 | // ContextEval evaluates the program with a set of input variables and a context object in order |
| 48 | // to support cancellation and timeouts. This method must be used in conjunction with the |
| 49 | // InterruptCheckFrequency() option for cancellation interrupts to be impact evaluation. |
| 50 | // |
| 51 | // The vars value may either be an `Activation` or `map[string]any`. |
| 52 | // |
| 53 | // The output contract for `ContextEval` is otherwise identical to the `Eval` method. |
| 54 | ContextEval(context.Context, any) (ref.Val, *EvalDetails, error) |
| 55 | } |
| 56 | |
| 57 | // Activation used to resolve identifiers by name and references by id. |
| 58 | // |
| 59 | // An Activation is the primary mechanism by which a caller supplies input into a CEL program. |
| 60 | type Activation = interpreter.Activation |
| 61 | |
| 62 | // NewActivation returns an activation based on a map-based binding where the map keys are |
| 63 | // expected to be qualified names used with ResolveName calls. |
| 64 | // |
| 65 | // The input `bindings` may either be of type `Activation` or `map[string]any`. |
| 66 | // |
| 67 | // Lazy bindings may be supplied within the map-based input in either of the following forms: |
| 68 | // - func() any |
| 69 | // - func() ref.Val |
| 70 | // |
| 71 | // The output of the lazy binding will overwrite the variable reference in the internal map. |
| 72 | // |
| 73 | // Values which are not represented as ref.Val types on input may be adapted to a ref.Val using |
| 74 | // the types.Adapter configured in the environment. |
| 75 | func NewActivation(bindings any) (Activation, error) { |
| 76 | return interpreter.NewActivation(bindings) |
| 77 | } |
| 78 | |
| 79 | // PartialActivation extends the Activation interface with a set of unknown AttributePatterns. |
| 80 | type PartialActivation = interpreter.PartialActivation |
| 81 | |
| 82 | // NoVars returns an empty Activation. |
| 83 | func NoVars() Activation { |
| 84 | return interpreter.EmptyActivation() |
| 85 | } |
| 86 | |
| 87 | // PartialVars returns a PartialActivation which contains variables and a set of AttributePattern |
| 88 | // values that indicate variables or parts of variables whose value are not yet known. |
| 89 | // |
| 90 | // This method relies on manually configured sets of missing attribute patterns. For a method which |
| 91 | // infers the missing variables from the input and the configured environment, use Env.PartialVars(). |
| 92 | // |
| 93 | // The `vars` value may either be an Activation or any valid input to the NewActivation call. |
| 94 | func PartialVars(vars any, |
| 95 | unknowns ...*AttributePatternType) (PartialActivation, error) { |
| 96 | return interpreter.NewPartialActivation(vars, unknowns...) |
| 97 | } |
| 98 | |
| 99 | // AttributePattern returns an AttributePattern that matches a top-level variable. The pattern is |
| 100 | // mutable, and its methods support the specification of one or more qualifier patterns. |
| 101 | // |
| 102 | // For example, the AttributePattern(`a`).QualString(`b`) represents a variable access `a` with a |
| 103 | // string field or index qualification `b`. This pattern will match Attributes `a`, and `a.b`, |
| 104 | // but not `a.c`. |
| 105 | // |
| 106 | // When using a CEL expression within a container, e.g. a package or namespace, the variable name |
| 107 | // in the pattern must match the qualified name produced during the variable namespace resolution. |
| 108 | // For example, when variable `a` is declared within an expression whose container is `ns.app`, the |
| 109 | // fully qualified variable name may be `ns.app.a`, `ns.a`, or `a` per the CEL namespace resolution |
| 110 | // rules. Pick the fully qualified variable name that makes sense within the container as the |
| 111 | // AttributePattern `varName` argument. |
| 112 | func AttributePattern(varName string) *AttributePatternType { |
| 113 | return interpreter.NewAttributePattern(varName) |
| 114 | } |
| 115 | |
| 116 | // AttributePatternType represents a top-level variable with an optional set of qualifier patterns. |
| 117 | // |
| 118 | // See the interpreter.AttributePattern and interpreter.AttributeQualifierPattern for more info |
| 119 | // about how to create and manipulate AttributePattern values. |
| 120 | type AttributePatternType = interpreter.AttributePattern |
| 121 | |
| 122 | // EvalDetails holds additional information observed during the Eval() call. |
| 123 | type EvalDetails struct { |
| 124 | state interpreter.EvalState |
| 125 | costTracker *interpreter.CostTracker |
| 126 | } |
| 127 | |
| 128 | // State of the evaluation, non-nil if the OptTrackState or OptExhaustiveEval is specified |
| 129 | // within EvalOptions. |
| 130 | func (ed *EvalDetails) State() interpreter.EvalState { |
| 131 | if ed == nil { |
| 132 | return interpreter.NewEvalState() |
| 133 | } |
| 134 | return ed.state |
| 135 | } |
| 136 | |
| 137 | // ActualCost returns the tracked cost through the course of execution when `CostTracking` is enabled. |
| 138 | // Otherwise, returns nil if the cost was not enabled. |
| 139 | func (ed *EvalDetails) ActualCost() *uint64 { |
| 140 | if ed == nil || ed.costTracker == nil { |
| 141 | return nil |
| 142 | } |
| 143 | cost := ed.costTracker.ActualCost() |
| 144 | return &cost |
| 145 | } |
| 146 | |
| 147 | // prog is the internal implementation of the Program interface. |
| 148 | type prog struct { |
| 149 | *Env |
| 150 | evalOpts EvalOption |
| 151 | defaultVars Activation |
| 152 | dispatcher interpreter.Dispatcher |
| 153 | interpreter interpreter.Interpreter |
| 154 | interruptCheckFrequency uint |
| 155 | |
| 156 | // Intermediate state used to configure the InterpretableDecorator set provided |
| 157 | // to the initInterpretable call. |
| 158 | plannerOptions []interpreter.PlannerOption |
| 159 | regexOptimizations []*interpreter.RegexOptimization |
| 160 | |
| 161 | // Interpretable configured from an Ast and aggregate decorator set based on program options. |
| 162 | interpretable interpreter.Interpretable |
| 163 | observable *interpreter.ObservableInterpretable |
| 164 | callCostEstimator interpreter.ActualCostEstimator |
| 165 | costOptions []interpreter.CostTrackerOption |
| 166 | costLimit *uint64 |
| 167 | } |
| 168 | |
| 169 | // newProgram creates a program instance with an environment, an ast, and an optional list of |
| 170 | // ProgramOption values. |
| 171 | // |
| 172 | // If the program cannot be configured the prog will be nil, with a non-nil error response. |
| 173 | func newProgram(e *Env, a *ast.AST, opts []ProgramOption) (Program, error) { |
| 174 | // Build the dispatcher, interpreter, and default program value. |
| 175 | disp := interpreter.NewDispatcher() |
| 176 | |
| 177 | // Ensure the default attribute factory is set after the adapter and provider are |
| 178 | // configured. |
| 179 | p := &prog{ |
| 180 | Env: e, |
| 181 | plannerOptions: []interpreter.PlannerOption{}, |
| 182 | dispatcher: disp, |
| 183 | costOptions: []interpreter.CostTrackerOption{}, |
| 184 | } |
| 185 | |
| 186 | // Configure the program via the ProgramOption values. |
| 187 | var err error |
| 188 | for _, opt := range opts { |
| 189 | p, err = opt(p) |
| 190 | if err != nil { |
| 191 | return nil, err |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | e.funcBindOnce.Do(func() { |
| 196 | var bindings []*functions.Overload |
| 197 | e.functionBindings = []*functions.Overload{} |
| 198 | for _, fn := range e.functions { |
| 199 | bindings, err = fn.Bindings() |
| 200 | if err != nil { |
| 201 | return |
| 202 | } |
| 203 | e.functionBindings = append(e.functionBindings, bindings...) |
| 204 | } |
| 205 | }) |
| 206 | if err != nil { |
| 207 | return nil, err |
| 208 | } |
| 209 | |
| 210 | // Add the function bindings created via Function() options. |
| 211 | err = disp.Add(e.functionBindings...) |
| 212 | if err != nil { |
| 213 | return nil, err |
| 214 | } |
| 215 | |
| 216 | // Set the attribute factory after the options have been set. |
| 217 | var attrFactory interpreter.AttributeFactory |
| 218 | attrFactorOpts := []interpreter.AttrFactoryOption{ |
| 219 | interpreter.EnableErrorOnBadPresenceTest(p.HasFeature(featureEnableErrorOnBadPresenceTest)), |
| 220 | } |
| 221 | if p.evalOpts&OptPartialEval == OptPartialEval { |
| 222 | attrFactory = interpreter.NewPartialAttributeFactory(e.Container, e.adapter, e.provider, attrFactorOpts...) |
| 223 | } else { |
| 224 | attrFactory = interpreter.NewAttributeFactory(e.Container, e.adapter, e.provider, attrFactorOpts...) |
| 225 | } |
| 226 | interp := interpreter.NewInterpreter(disp, e.Container, e.provider, e.adapter, attrFactory) |
| 227 | p.interpreter = interp |
| 228 | |
| 229 | // Translate the EvalOption flags into InterpretableDecorator instances. |
| 230 | plannerOptions := make([]interpreter.PlannerOption, len(p.plannerOptions)) |
| 231 | copy(plannerOptions, p.plannerOptions) |
| 232 | |
| 233 | // Enable interrupt checking if there's a non-zero check frequency |
| 234 | if p.interruptCheckFrequency > 0 { |
| 235 | plannerOptions = append(plannerOptions, interpreter.InterruptableEval()) |
| 236 | } |
| 237 | // Enable constant folding first. |
| 238 | if p.evalOpts&OptOptimize == OptOptimize { |
| 239 | plannerOptions = append(plannerOptions, interpreter.Optimize()) |
| 240 | p.regexOptimizations = append(p.regexOptimizations, interpreter.MatchesRegexOptimization) |
| 241 | } |
| 242 | // Enable regex compilation of constants immediately after folding constants. |
| 243 | if len(p.regexOptimizations) > 0 { |
| 244 | plannerOptions = append(plannerOptions, interpreter.CompileRegexConstants(p.regexOptimizations...)) |
| 245 | } |
| 246 | |
| 247 | // Enable exhaustive eval, state tracking and cost tracking last since they require a factory. |
| 248 | if p.evalOpts&(OptExhaustiveEval|OptTrackState|OptTrackCost) != 0 { |
| 249 | costOptCount := len(p.costOptions) |
| 250 | if p.costLimit != nil { |
| 251 | costOptCount++ |
| 252 | } |
| 253 | costOpts := make([]interpreter.CostTrackerOption, 0, costOptCount) |
| 254 | costOpts = append(costOpts, p.costOptions...) |
| 255 | if p.costLimit != nil { |
| 256 | costOpts = append(costOpts, interpreter.CostTrackerLimit(*p.costLimit)) |
| 257 | } |
| 258 | trackerFactory := func() (*interpreter.CostTracker, error) { |
| 259 | return interpreter.NewCostTracker(p.callCostEstimator, costOpts...) |
| 260 | } |
| 261 | var observers []interpreter.PlannerOption |
| 262 | if p.evalOpts&(OptExhaustiveEval|OptTrackState) != 0 { |
| 263 | // EvalStateObserver is required for OptExhaustiveEval. |
| 264 | observers = append(observers, interpreter.EvalStateObserver()) |
| 265 | } |
| 266 | if p.evalOpts&OptTrackCost == OptTrackCost { |
| 267 | observers = append(observers, interpreter.CostObserver(interpreter.CostTrackerFactory(trackerFactory))) |
| 268 | } |
| 269 | // Enable exhaustive eval over a basic observer since it offers a superset of features. |
| 270 | if p.evalOpts&OptExhaustiveEval == OptExhaustiveEval { |
| 271 | plannerOptions = append(plannerOptions, |
| 272 | append([]interpreter.PlannerOption{interpreter.ExhaustiveEval()}, observers...)...) |
| 273 | } else if len(observers) > 0 { |
| 274 | plannerOptions = append(plannerOptions, observers...) |
| 275 | } |
| 276 | } |
| 277 | return p.initInterpretable(a, plannerOptions) |
| 278 | } |
| 279 | |
| 280 | func (p *prog) initInterpretable(a *ast.AST, plannerOptions []interpreter.PlannerOption) (*prog, error) { |
| 281 | // When the AST has been exprAST it contains metadata that can be used to speed up program execution. |
| 282 | interpretable, err := p.interpreter.NewInterpretable(a, plannerOptions...) |
| 283 | if err != nil { |
| 284 | return nil, err |
| 285 | } |
| 286 | p.interpretable = interpretable |
| 287 | if oi, ok := interpretable.(*interpreter.ObservableInterpretable); ok { |
| 288 | p.observable = oi |
| 289 | } |
| 290 | return p, nil |
| 291 | } |
| 292 | |
| 293 | // Eval implements the Program interface method. |
| 294 | func (p *prog) Eval(input any) (out ref.Val, det *EvalDetails, err error) { |
| 295 | // Configure error recovery for unexpected panics during evaluation. Note, the use of named |
| 296 | // return values makes it possible to modify the error response during the recovery |
| 297 | // function. |
| 298 | defer func() { |
| 299 | if r := recover(); r != nil { |
| 300 | switch t := r.(type) { |
| 301 | case interpreter.EvalCancelledError: |
| 302 | err = t |
| 303 | default: |
| 304 | err = fmt.Errorf("internal error: %v", r) |
| 305 | } |
| 306 | } |
| 307 | }() |
| 308 | // Build a hierarchical activation if there are default vars set. |
| 309 | var vars Activation |
| 310 | switch v := input.(type) { |
| 311 | case Activation: |
| 312 | vars = v |
| 313 | case map[string]any: |
| 314 | vars = activationPool.Setup(v) |
| 315 | defer activationPool.Put(vars) |
| 316 | default: |
| 317 | return nil, nil, fmt.Errorf("invalid input, wanted Activation or map[string]any, got: (%T)%v", input, input) |
| 318 | } |
| 319 | if p.defaultVars != nil { |
| 320 | vars = interpreter.NewHierarchicalActivation(p.defaultVars, vars) |
| 321 | } |
| 322 | if p.observable != nil { |
| 323 | det = &EvalDetails{} |
| 324 | out = p.observable.ObserveEval(vars, func(observed any) { |
| 325 | switch o := observed.(type) { |
| 326 | case interpreter.EvalState: |
| 327 | det.state = o |
| 328 | case *interpreter.CostTracker: |
| 329 | det.costTracker = o |
| 330 | } |
| 331 | }) |
| 332 | } else { |
| 333 | out = p.interpretable.Eval(vars) |
| 334 | } |
| 335 | // The output of an internal Eval may have a value (`v`) that is a types.Err. This step |
| 336 | // translates the CEL value to a Go error response. This interface does not quite match the |
| 337 | // RPC signature which allows for multiple errors to be returned, but should be sufficient. |
| 338 | if types.IsError(out) { |
| 339 | err = out.(*types.Err) |
| 340 | } |
| 341 | return |
| 342 | } |
| 343 | |
| 344 | // ContextEval implements the Program interface. |
| 345 | func (p *prog) ContextEval(ctx context.Context, input any) (ref.Val, *EvalDetails, error) { |
| 346 | if ctx == nil { |
| 347 | return nil, nil, fmt.Errorf("context can not be nil") |
| 348 | } |
| 349 | // Configure the input, making sure to wrap Activation inputs in the special ctxActivation which |
| 350 | // exposes the #interrupted variable and manages rate-limited checks of the ctx.Done() state. |
| 351 | var vars Activation |
| 352 | switch v := input.(type) { |
| 353 | case Activation: |
| 354 | vars = ctxActivationPool.Setup(v, ctx.Done(), p.interruptCheckFrequency) |
| 355 | defer ctxActivationPool.Put(vars) |
| 356 | case map[string]any: |
| 357 | rawVars := activationPool.Setup(v) |
| 358 | defer activationPool.Put(rawVars) |
| 359 | vars = ctxActivationPool.Setup(rawVars, ctx.Done(), p.interruptCheckFrequency) |
| 360 | defer ctxActivationPool.Put(vars) |
| 361 | default: |
| 362 | return nil, nil, fmt.Errorf("invalid input, wanted Activation or map[string]any, got: (%T)%v", input, input) |
| 363 | } |
| 364 | return p.Eval(vars) |
| 365 | } |
| 366 | |
| 367 | type ctxEvalActivation struct { |
| 368 | parent Activation |
| 369 | interrupt <-chan struct{} |
| 370 | interruptCheckCount uint |
| 371 | interruptCheckFrequency uint |
| 372 | } |
| 373 | |
| 374 | // ResolveName implements the Activation interface method, but adds a special #interrupted variable |
| 375 | // which is capable of testing whether a 'done' signal is provided from a context.Context channel. |
| 376 | func (a *ctxEvalActivation) ResolveName(name string) (any, bool) { |
| 377 | if name == "#interrupted" { |
| 378 | a.interruptCheckCount++ |
| 379 | if a.interruptCheckCount%a.interruptCheckFrequency == 0 { |
| 380 | select { |
| 381 | case <-a.interrupt: |
| 382 | return true, true |
| 383 | default: |
| 384 | return nil, false |
| 385 | } |
| 386 | } |
| 387 | return nil, false |
| 388 | } |
| 389 | return a.parent.ResolveName(name) |
| 390 | } |
| 391 | |
| 392 | func (a *ctxEvalActivation) Parent() Activation { |
| 393 | return a.parent |
| 394 | } |
| 395 | |
| 396 | func (a *ctxEvalActivation) AsPartialActivation() (interpreter.PartialActivation, bool) { |
| 397 | pa, ok := a.parent.(interpreter.PartialActivation) |
| 398 | return pa, ok |
| 399 | } |
| 400 | |
| 401 | func newCtxEvalActivationPool() *ctxEvalActivationPool { |
| 402 | return &ctxEvalActivationPool{ |
| 403 | Pool: sync.Pool{ |
| 404 | New: func() any { |
| 405 | return &ctxEvalActivation{} |
| 406 | }, |
| 407 | }, |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | type ctxEvalActivationPool struct { |
| 412 | sync.Pool |
| 413 | } |
| 414 | |
| 415 | // Setup initializes a pooled Activation with the ability check for context.Context cancellation |
| 416 | func (p *ctxEvalActivationPool) Setup(vars Activation, done <-chan struct{}, interruptCheckRate uint) *ctxEvalActivation { |
| 417 | a := p.Pool.Get().(*ctxEvalActivation) |
| 418 | a.parent = vars |
| 419 | a.interrupt = done |
| 420 | a.interruptCheckCount = 0 |
| 421 | a.interruptCheckFrequency = interruptCheckRate |
| 422 | return a |
| 423 | } |
| 424 | |
| 425 | type evalActivation struct { |
| 426 | vars map[string]any |
| 427 | lazyVars map[string]any |
| 428 | } |
| 429 | |
| 430 | // ResolveName looks up the value of the input variable name, if found. |
| 431 | // |
| 432 | // Lazy bindings may be supplied within the map-based input in either of the following forms: |
| 433 | // - func() any |
| 434 | // - func() ref.Val |
| 435 | // |
| 436 | // The lazy binding will only be invoked once per evaluation. |
| 437 | // |
| 438 | // Values which are not represented as ref.Val types on input may be adapted to a ref.Val using |
| 439 | // the types.Adapter configured in the environment. |
| 440 | func (a *evalActivation) ResolveName(name string) (any, bool) { |
| 441 | v, found := a.vars[name] |
| 442 | if !found { |
| 443 | return nil, false |
| 444 | } |
| 445 | switch obj := v.(type) { |
| 446 | case func() ref.Val: |
| 447 | if resolved, found := a.lazyVars[name]; found { |
| 448 | return resolved, true |
| 449 | } |
| 450 | lazy := obj() |
| 451 | a.lazyVars[name] = lazy |
| 452 | return lazy, true |
| 453 | case func() any: |
| 454 | if resolved, found := a.lazyVars[name]; found { |
| 455 | return resolved, true |
| 456 | } |
| 457 | lazy := obj() |
| 458 | a.lazyVars[name] = lazy |
| 459 | return lazy, true |
| 460 | default: |
| 461 | return obj, true |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | // Parent implements the Activation interface |
| 466 | func (a *evalActivation) Parent() Activation { |
| 467 | return nil |
| 468 | } |
| 469 | |
| 470 | func newEvalActivationPool() *evalActivationPool { |
| 471 | return &evalActivationPool{ |
| 472 | Pool: sync.Pool{ |
| 473 | New: func() any { |
| 474 | return &evalActivation{lazyVars: make(map[string]any)} |
| 475 | }, |
| 476 | }, |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | type evalActivationPool struct { |
| 481 | sync.Pool |
| 482 | } |
| 483 | |
| 484 | // Setup initializes a pooled Activation object with the map input. |
| 485 | func (p *evalActivationPool) Setup(vars map[string]any) *evalActivation { |
| 486 | a := p.Pool.Get().(*evalActivation) |
| 487 | a.vars = vars |
| 488 | return a |
| 489 | } |
| 490 | |
| 491 | func (p *evalActivationPool) Put(value any) { |
| 492 | a := value.(*evalActivation) |
| 493 | for k := range a.lazyVars { |
| 494 | delete(a.lazyVars, k) |
| 495 | } |
| 496 | p.Pool.Put(a) |
| 497 | } |
| 498 | |
| 499 | var ( |
| 500 | // activationPool is an internally managed pool of Activation values that wrap map[string]any inputs |
| 501 | activationPool = newEvalActivationPool() |
| 502 | |
| 503 | // ctxActivationPool is an internally managed pool of Activation values that expose a special #interrupted variable |
| 504 | ctxActivationPool = newCtxEvalActivationPool() |
| 505 | ) |