| 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 |
|
| 21 |
"google.golang.org/protobuf/proto" |
| 22 |
"google.golang.org/protobuf/reflect/protodesc" |
| 23 |
"google.golang.org/protobuf/reflect/protoreflect" |
| 24 |
"google.golang.org/protobuf/reflect/protoregistry" |
| 25 |
"google.golang.org/protobuf/types/dynamicpb" |
| 26 |
|
| 27 |
"github.com/google/cel-go/checker" |
| 28 |
"github.com/google/cel-go/common/containers" |
| 29 |
"github.com/google/cel-go/common/decls" |
| 30 |
"github.com/google/cel-go/common/env" |
| 31 |
"github.com/google/cel-go/common/functions" |
| 32 |
"github.com/google/cel-go/common/types" |
| 33 |
"github.com/google/cel-go/common/types/pb" |
| 34 |
"github.com/google/cel-go/common/types/ref" |
| 35 |
"github.com/google/cel-go/interpreter" |
| 36 |
"github.com/google/cel-go/parser" |
| 37 |
|
| 38 |
exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" |
| 39 |
descpb "google.golang.org/protobuf/types/descriptorpb" |
| 40 |
) |
| 41 |
|
| 42 |
// These constants beginning with "Feature" enable optional behavior in |
| 43 |
// the library. See the documentation for each constant to see its |
| 44 |
// effects, compatibility restrictions, and standard conformance. |
| 45 |
const ( |
| 46 |
_ = iota |
| 47 |
|
| 48 |
// Enable the tracking of function call expressions replaced by macros. |
| 49 |
featureEnableMacroCallTracking |
| 50 |
|
| 51 |
// Enable the use of cross-type numeric comparisons at the type-checker. |
| 52 |
featureCrossTypeNumericComparisons |
| 53 |
|
| 54 |
// Enable eager validation of declarations to ensure that Env values created |
| 55 |
// with `Extend` inherit a validated list of declarations from the parent Env. |
| 56 |
featureEagerlyValidateDeclarations |
| 57 |
|
| 58 |
// Enable the use of the default UTC timezone when a timezone is not specified |
| 59 |
// on a CEL timestamp operation. This fixes the scenario where the input time |
| 60 |
// is not already in UTC. |
| 61 |
featureDefaultUTCTimeZone |
| 62 |
|
| 63 |
// Enable the serialization of logical operator ASTs as variadic calls, thus |
| 64 |
// compressing the logic graph to a single call when multiple like-operator |
| 65 |
// expressions occur: e.g. a && b && c && d -> call(_&&_, [a, b, c, d]) |
| 66 |
featureVariadicLogicalASTs |
| 67 |
|
| 68 |
// Enable error generation when a presence test or optional field selection is |
| 69 |
// performed on a primitive type. |
| 70 |
featureEnableErrorOnBadPresenceTest |
| 71 |
|
| 72 |
// Enable escape syntax for field identifiers (`). |
| 73 |
featureIdentEscapeSyntax |
| 74 |
) |
| 75 |
|
| 76 |
var featureIDsToNames = map[int]string{ |
| 77 |
featureEnableMacroCallTracking: "cel.feature.macro_call_tracking", |
| 78 |
featureCrossTypeNumericComparisons: "cel.feature.cross_type_numeric_comparisons", |
| 79 |
featureIdentEscapeSyntax: "cel.feature.backtick_escape_syntax", |
| 80 |
} |
| 81 |
|
| 82 |
func featureNameByID(id int) (string, bool) { |
| 83 |
name, found := featureIDsToNames[id] |
| 84 |
return name, found |
| 85 |
} |
| 86 |
|
| 87 |
func featureIDByName(name string) (int, bool) { |
| 88 |
for id, n := range featureIDsToNames { |
| 89 |
if n == name { |
| 90 |
return id, true |
| 91 |
} |
| 92 |
} |
| 93 |
return 0, false |
| 94 |
} |
| 95 |
|
| 96 |
// EnvOption is a functional interface for configuring the environment. |
| 97 |
type EnvOption func(e *Env) (*Env, error) |
| 98 |
|
| 99 |
// ClearMacros options clears all parser macros. |
| 100 |
// |
| 101 |
// Clearing macros will ensure CEL expressions can only contain linear evaluation paths, as |
| 102 |
// comprehensions such as `all` and `exists` are enabled only via macros. |
| 103 |
func ClearMacros() EnvOption { |
| 104 |
return func(e *Env) (*Env, error) { |
| 105 |
e.macros = NoMacros |
| 106 |
return e, nil |
| 107 |
} |
| 108 |
} |
| 109 |
|
| 110 |
// CustomTypeAdapter swaps the default types.Adapter implementation with a custom one. |
| 111 |
// |
| 112 |
// Note: This option must be specified before the Types and TypeDescs options when used together. |
| 113 |
func CustomTypeAdapter(adapter types.Adapter) EnvOption { |
| 114 |
return func(e *Env) (*Env, error) { |
| 115 |
e.adapter = adapter |
| 116 |
return e, nil |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
// CustomTypeProvider replaces the types.Provider implementation with a custom one. |
| 121 |
// |
| 122 |
// The `provider` variable type may either be types.Provider or ref.TypeProvider (deprecated) |
| 123 |
// |
| 124 |
// Note: This option must be specified before the Types and TypeDescs options when used together. |
| 125 |
func CustomTypeProvider(provider any) EnvOption { |
| 126 |
return func(e *Env) (*Env, error) { |
| 127 |
var err error |
| 128 |
e.provider, err = maybeInteropProvider(provider) |
| 129 |
return e, err |
| 130 |
} |
| 131 |
} |
| 132 |
|
| 133 |
// Declarations option extends the declaration set configured in the environment. |
| 134 |
// |
| 135 |
// Note: Declarations will by default be appended to the pre-existing declaration set configured |
| 136 |
// for the environment. The NewEnv call builds on top of the standard CEL declarations. For a |
| 137 |
// purely custom set of declarations use NewCustomEnv. |
| 138 |
// |
| 139 |
// Deprecated: use FunctionDecls and VariableDecls or FromConfig instead. |
| 140 |
func Declarations(decls ...*exprpb.Decl) EnvOption { |
| 141 |
declOpts := []EnvOption{} |
| 142 |
var err error |
| 143 |
var opt EnvOption |
| 144 |
// Convert the declarations to `EnvOption` values ahead of time. |
| 145 |
// Surface any errors in conversion when the options are applied. |
| 146 |
for _, d := range decls { |
| 147 |
opt, err = ExprDeclToDeclaration(d) |
| 148 |
if err != nil { |
| 149 |
break |
| 150 |
} |
| 151 |
declOpts = append(declOpts, opt) |
| 152 |
} |
| 153 |
return func(e *Env) (*Env, error) { |
| 154 |
if err != nil { |
| 155 |
return nil, err |
| 156 |
} |
| 157 |
for _, o := range declOpts { |
| 158 |
e, err = o(e) |
| 159 |
if err != nil { |
| 160 |
return nil, err |
| 161 |
} |
| 162 |
} |
| 163 |
return e, nil |
| 164 |
} |
| 165 |
} |
| 166 |
|
| 167 |
// EagerlyValidateDeclarations ensures that any collisions between configured declarations are caught |
| 168 |
// at the time of the `NewEnv` call. |
| 169 |
// |
| 170 |
// Eagerly validating declarations is also useful for bootstrapping a base `cel.Env` value. |
| 171 |
// Calls to base `Env.Extend()` will be significantly faster when declarations are eagerly validated |
| 172 |
// as declarations will be collision-checked at most once and only incrementally by way of `Extend` |
| 173 |
// |
| 174 |
// Disabled by default as not all environments are used for type-checking. |
| 175 |
func EagerlyValidateDeclarations(enabled bool) EnvOption { |
| 176 |
return features(featureEagerlyValidateDeclarations, enabled) |
| 177 |
} |
| 178 |
|
| 179 |
// HomogeneousAggregateLiterals disables mixed type list and map literal values. |
| 180 |
// |
| 181 |
// Note, it is still possible to have heterogeneous aggregates when provided as variables to the |
| 182 |
// expression, as well as via conversion of well-known dynamic types, or with unchecked |
| 183 |
// expressions. |
| 184 |
func HomogeneousAggregateLiterals() EnvOption { |
| 185 |
return ASTValidators(ValidateHomogeneousAggregateLiterals()) |
| 186 |
} |
| 187 |
|
| 188 |
// variadicLogicalOperatorASTs flatten like-operator chained logical expressions into a single |
| 189 |
// variadic call with N-terms. This behavior is useful when serializing to a protocol buffer as |
| 190 |
// it will reduce the number of recursive calls needed to deserialize the AST later. |
| 191 |
// |
| 192 |
// For example, given the following expression the call graph will be rendered accordingly: |
| 193 |
// |
| 194 |
// expression: a && b && c && (d || e) |
| 195 |
// ast: call(_&&_, [a, b, c, call(_||_, [d, e])]) |
| 196 |
func variadicLogicalOperatorASTs() EnvOption { |
| 197 |
return features(featureVariadicLogicalASTs, true) |
| 198 |
} |
| 199 |
|
| 200 |
// Macros option extends the macro set configured in the environment. |
| 201 |
// |
| 202 |
// Note: This option must be specified after ClearMacros if used together. |
| 203 |
func Macros(macros ...Macro) EnvOption { |
| 204 |
return func(e *Env) (*Env, error) { |
| 205 |
e.macros = append(e.macros, macros...) |
| 206 |
return e, nil |
| 207 |
} |
| 208 |
} |
| 209 |
|
| 210 |
// Container sets the container for resolving variable names. Defaults to an empty container. |
| 211 |
// |
| 212 |
// If all references within an expression are relative to a protocol buffer package, then |
| 213 |
// specifying a container of `google.type` would make it possible to write expressions such as |
| 214 |
// `Expr{expression: 'a < b'}` instead of having to write `google.type.Expr{...}`. |
| 215 |
func Container(name string) EnvOption { |
| 216 |
return func(e *Env) (*Env, error) { |
| 217 |
cont, err := e.Container.Extend(containers.Name(name)) |
| 218 |
if err != nil { |
| 219 |
return nil, err |
| 220 |
} |
| 221 |
e.Container = cont |
| 222 |
return e, nil |
| 223 |
} |
| 224 |
} |
| 225 |
|
| 226 |
// Abbrevs configures a set of simple names as abbreviations for fully-qualified names. |
| 227 |
// |
| 228 |
// An abbreviation (abbrev for short) is a simple name that expands to a fully-qualified name. |
| 229 |
// Abbreviations can be useful when working with variables, functions, and especially types from |
| 230 |
// multiple namespaces: |
| 231 |
// |
| 232 |
// // CEL object construction |
| 233 |
// qual.pkg.version.ObjTypeName{ |
| 234 |
// field: alt.container.ver.FieldTypeName{value: ...} |
| 235 |
// } |
| 236 |
// |
| 237 |
// Only one the qualified names above may be used as the CEL container, so at least one of these |
| 238 |
// references must be a long qualified name within an otherwise short CEL program. Using the |
| 239 |
// following abbreviations, the program becomes much simpler: |
| 240 |
// |
| 241 |
// // CEL Go option |
| 242 |
// Abbrevs("qual.pkg.version.ObjTypeName", "alt.container.ver.FieldTypeName") |
| 243 |
// // Simplified Object construction |
| 244 |
// ObjTypeName{field: FieldTypeName{value: ...}} |
| 245 |
// |
| 246 |
// There are a few rules for the qualified names and the simple abbreviations generated from them: |
| 247 |
// - Qualified names must be dot-delimited, e.g. `package.subpkg.name`. |
| 248 |
// - The last element in the qualified name is the abbreviation. |
| 249 |
// - Abbreviations must not collide with each other. |
| 250 |
// - The abbreviation must not collide with unqualified names in use. |
| 251 |
// |
| 252 |
// Abbreviations are distinct from container-based references in the following important ways: |
| 253 |
// - Abbreviations must expand to a fully-qualified name. |
| 254 |
// - Expanded abbreviations do not participate in namespace resolution. |
| 255 |
// - Abbreviation expansion is done instead of the container search for a matching identifier. |
| 256 |
// - Containers follow C++ namespace resolution rules with searches from the most qualified name |
| 257 |
// |
| 258 |
// to the least qualified name. |
| 259 |
// |
| 260 |
// - Container references within the CEL program may be relative, and are resolved to fully |
| 261 |
// |
| 262 |
// qualified names at either type-check time or program plan time, whichever comes first. |
| 263 |
// |
| 264 |
// If there is ever a case where an identifier could be in both the container and as an |
| 265 |
// abbreviation, the abbreviation wins as this will ensure that the meaning of a program is |
| 266 |
// preserved between compilations even as the container evolves. |
| 267 |
func Abbrevs(qualifiedNames ...string) EnvOption { |
| 268 |
return func(e *Env) (*Env, error) { |
| 269 |
cont, err := e.Container.Extend(containers.Abbrevs(qualifiedNames...)) |
| 270 |
if err != nil { |
| 271 |
return nil, err |
| 272 |
} |
| 273 |
e.Container = cont |
| 274 |
return e, nil |
| 275 |
} |
| 276 |
} |
| 277 |
|
| 278 |
// customTypeRegistry is an internal-only interface containing the minimum methods required to support |
| 279 |
// custom types. It is a subset of methods from ref.TypeRegistry. |
| 280 |
type customTypeRegistry interface { |
| 281 |
RegisterDescriptor(protoreflect.FileDescriptor) error |
| 282 |
RegisterType(...ref.Type) error |
| 283 |
} |
| 284 |
|
| 285 |
// Types adds one or more type declarations to the environment, allowing for construction of |
| 286 |
// type-literals whose definitions are included in the common expression built-in set. |
| 287 |
// |
| 288 |
// The input types may either be instances of `proto.Message` or `ref.Type`. Any other type |
| 289 |
// provided to this option will result in an error. |
| 290 |
// |
| 291 |
// Well-known protobuf types within the `google.protobuf.*` package are included in the standard |
| 292 |
// environment by default. |
| 293 |
// |
| 294 |
// Note: This option must be specified after the CustomTypeProvider option when used together. |
| 295 |
func Types(addTypes ...any) EnvOption { |
| 296 |
return func(e *Env) (*Env, error) { |
| 297 |
reg, isReg := e.provider.(customTypeRegistry) |
| 298 |
if !isReg { |
| 299 |
return nil, fmt.Errorf("custom types not supported by provider: %T", e.provider) |
| 300 |
} |
| 301 |
for _, t := range addTypes { |
| 302 |
switch v := t.(type) { |
| 303 |
case proto.Message: |
| 304 |
fdMap := pb.CollectFileDescriptorSet(v) |
| 305 |
for _, fd := range fdMap { |
| 306 |
err := reg.RegisterDescriptor(fd) |
| 307 |
if err != nil { |
| 308 |
return nil, err |
| 309 |
} |
| 310 |
} |
| 311 |
case ref.Type: |
| 312 |
err := reg.RegisterType(v) |
| 313 |
if err != nil { |
| 314 |
return nil, err |
| 315 |
} |
| 316 |
default: |
| 317 |
return nil, fmt.Errorf("unsupported type: %T", t) |
| 318 |
} |
| 319 |
} |
| 320 |
return e, nil |
| 321 |
} |
| 322 |
} |
| 323 |
|
| 324 |
// TypeDescs adds type declarations from any protoreflect.FileDescriptor, protoregistry.Files, |
| 325 |
// google.protobuf.FileDescriptorProto or google.protobuf.FileDescriptorSet provided. |
| 326 |
// |
| 327 |
// Note that messages instantiated from these descriptors will be *dynamicpb.Message values |
| 328 |
// rather than the concrete message type. |
| 329 |
// |
| 330 |
// TypeDescs are hermetic to a single Env object, but may be copied to other Env values via |
| 331 |
// extension or by re-using the same EnvOption with another NewEnv() call. |
| 332 |
func TypeDescs(descs ...any) EnvOption { |
| 333 |
return func(e *Env) (*Env, error) { |
| 334 |
reg, isReg := e.provider.(customTypeRegistry) |
| 335 |
if !isReg { |
| 336 |
return nil, fmt.Errorf("custom types not supported by provider: %T", e.provider) |
| 337 |
} |
| 338 |
// Scan the input descriptors for FileDescriptorProto messages and accumulate them into a |
| 339 |
// synthetic FileDescriptorSet as the FileDescriptorProto messages may refer to each other |
| 340 |
// and will not resolve properly unless they are part of the same set. |
| 341 |
var fds *descpb.FileDescriptorSet |
| 342 |
for _, d := range descs { |
| 343 |
switch f := d.(type) { |
| 344 |
case *descpb.FileDescriptorProto: |
| 345 |
if fds == nil { |
| 346 |
fds = &descpb.FileDescriptorSet{ |
| 347 |
File: []*descpb.FileDescriptorProto{}, |
| 348 |
} |
| 349 |
} |
| 350 |
fds.File = append(fds.File, f) |
| 351 |
} |
| 352 |
} |
| 353 |
if fds != nil { |
| 354 |
if err := registerFileSet(reg, fds); err != nil { |
| 355 |
return nil, err |
| 356 |
} |
| 357 |
} |
| 358 |
for _, d := range descs { |
| 359 |
switch f := d.(type) { |
| 360 |
case *protoregistry.Files: |
| 361 |
if err := registerFiles(reg, f); err != nil { |
| 362 |
return nil, err |
| 363 |
} |
| 364 |
case protoreflect.FileDescriptor: |
| 365 |
if err := reg.RegisterDescriptor(f); err != nil { |
| 366 |
return nil, err |
| 367 |
} |
| 368 |
case *descpb.FileDescriptorSet: |
| 369 |
if err := registerFileSet(reg, f); err != nil { |
| 370 |
return nil, err |
| 371 |
} |
| 372 |
case *descpb.FileDescriptorProto: |
| 373 |
// skip, handled as a synthetic file descriptor set. |
| 374 |
default: |
| 375 |
return nil, fmt.Errorf("unsupported type descriptor: %T", d) |
| 376 |
} |
| 377 |
} |
| 378 |
return e, nil |
| 379 |
} |
| 380 |
} |
| 381 |
|
| 382 |
func registerFileSet(reg customTypeRegistry, fileSet *descpb.FileDescriptorSet) error { |
| 383 |
files, err := protodesc.NewFiles(fileSet) |
| 384 |
if err != nil { |
| 385 |
return fmt.Errorf("protodesc.NewFiles(%v) failed: %v", fileSet, err) |
| 386 |
} |
| 387 |
return registerFiles(reg, files) |
| 388 |
} |
| 389 |
|
| 390 |
func registerFiles(reg customTypeRegistry, files *protoregistry.Files) error { |
| 391 |
var err error |
| 392 |
files.RangeFiles(func(fd protoreflect.FileDescriptor) bool { |
| 393 |
err = reg.RegisterDescriptor(fd) |
| 394 |
return err == nil |
| 395 |
}) |
| 396 |
return err |
| 397 |
} |
| 398 |
|
| 399 |
// ProgramOption is a functional interface for configuring evaluation bindings and behaviors. |
| 400 |
type ProgramOption func(p *prog) (*prog, error) |
| 401 |
|
| 402 |
// CustomDecorator appends an InterpreterDecorator to the program. |
| 403 |
// |
| 404 |
// InterpretableDecorators can be used to inspect, alter, or replace the Program plan. |
| 405 |
func CustomDecorator(dec interpreter.InterpretableDecorator) ProgramOption { |
| 406 |
return func(p *prog) (*prog, error) { |
| 407 |
p.plannerOptions = append(p.plannerOptions, interpreter.CustomDecorator(dec)) |
| 408 |
return p, nil |
| 409 |
} |
| 410 |
} |
| 411 |
|
| 412 |
// Functions adds function overloads that extend or override the set of CEL built-ins. |
| 413 |
// |
| 414 |
// Deprecated: use Function() instead to declare the function, its overload signatures, |
| 415 |
// and the overload implementations. |
| 416 |
func Functions(funcs ...*functions.Overload) ProgramOption { |
| 417 |
return func(p *prog) (*prog, error) { |
| 418 |
if err := p.dispatcher.Add(funcs...); err != nil { |
| 419 |
return nil, err |
| 420 |
} |
| 421 |
return p, nil |
| 422 |
} |
| 423 |
} |
| 424 |
|
| 425 |
// Globals sets the global variable values for a given program. These values may be shadowed by |
| 426 |
// variables with the same name provided to the Eval() call. If Globals is used in a Library with |
| 427 |
// a Lib EnvOption, vars may shadow variables provided by previously added libraries. |
| 428 |
// |
| 429 |
// The vars value may either be an `cel.Activation` instance or a `map[string]any`. |
| 430 |
func Globals(vars any) ProgramOption { |
| 431 |
return func(p *prog) (*prog, error) { |
| 432 |
defaultVars, err := NewActivation(vars) |
| 433 |
if err != nil { |
| 434 |
return nil, err |
| 435 |
} |
| 436 |
if p.defaultVars != nil { |
| 437 |
defaultVars = interpreter.NewHierarchicalActivation(p.defaultVars, defaultVars) |
| 438 |
} |
| 439 |
p.defaultVars = defaultVars |
| 440 |
return p, nil |
| 441 |
} |
| 442 |
} |
| 443 |
|
| 444 |
// OptimizeRegex provides a way to replace the InterpretableCall for regex functions. This can be used |
| 445 |
// to compile regex string constants at program creation time and report any errors and then use the |
| 446 |
// compiled regex for all regex function invocations. |
| 447 |
func OptimizeRegex(regexOptimizations ...*interpreter.RegexOptimization) ProgramOption { |
| 448 |
return func(p *prog) (*prog, error) { |
| 449 |
p.regexOptimizations = append(p.regexOptimizations, regexOptimizations...) |
| 450 |
return p, nil |
| 451 |
} |
| 452 |
} |
| 453 |
|
| 454 |
// ConfigOptionFactory declares a signature which accepts a configuration element, e.g. env.Extension |
| 455 |
// and optionally produces an EnvOption in response. |
| 456 |
// |
| 457 |
// If there are multiple ConfigOptionFactory values which could apply to the same configuration node |
| 458 |
// the first one that returns an EnvOption and a `true` response will be used, and the config node |
| 459 |
// will not be passed along to any other option factory. |
| 460 |
// |
| 461 |
// Only the *env.Extension type is provided at this time, but validators, optimizers, and other tuning |
| 462 |
// parameters may be supported in the future. |
| 463 |
type ConfigOptionFactory func(any) (EnvOption, bool) |
| 464 |
|
| 465 |
// FromConfig produces and applies a set of EnvOption values derived from an env.Config object. |
| 466 |
// |
| 467 |
// For configuration elements which refer to features outside of the `cel` package, an optional set of |
| 468 |
// ConfigOptionFactory values may be passed in to support the conversion from static configuration to |
| 469 |
// configured cel.Env value. |
| 470 |
// |
| 471 |
// Note: disabling the standard library will clear the EnvOptions values previously set for the |
| 472 |
// environment with the exception of propagating types and adapters over to the new environment. |
| 473 |
// |
| 474 |
// Note: to support custom types referenced in the configuration file, you must ensure that one of |
| 475 |
// the following options appears before the FromConfig option: Types, TypeDescs, or CustomTypeProvider |
| 476 |
// as the type provider configured at the time when the config is processed is the one used to derive |
| 477 |
// type references from the configuration. |
| 478 |
func FromConfig(config *env.Config, optFactories ...ConfigOptionFactory) EnvOption { |
| 479 |
return func(e *Env) (*Env, error) { |
| 480 |
if err := config.Validate(); err != nil { |
| 481 |
return nil, err |
| 482 |
} |
| 483 |
opts, err := configToEnvOptions(config, e.CELTypeProvider(), optFactories) |
| 484 |
if err != nil { |
| 485 |
return nil, err |
| 486 |
} |
| 487 |
for _, o := range opts { |
| 488 |
e, err = o(e) |
| 489 |
if err != nil { |
| 490 |
return nil, err |
| 491 |
} |
| 492 |
} |
| 493 |
return e, nil |
| 494 |
} |
| 495 |
} |
| 496 |
|
| 497 |
// configToEnvOptions generates a set of EnvOption values (or error) based on a config, a type provider, |
| 498 |
// and an optional set of environment options. |
| 499 |
func configToEnvOptions(config *env.Config, provider types.Provider, optFactories []ConfigOptionFactory) ([]EnvOption, error) { |
| 500 |
envOpts := []EnvOption{} |
| 501 |
// Configure the standard lib subset. |
| 502 |
if config.StdLib != nil { |
| 503 |
envOpts = append(envOpts, func(e *Env) (*Env, error) { |
| 504 |
if e.HasLibrary("cel.lib.std") { |
| 505 |
return nil, errors.New("invalid subset of stdlib: create a custom env") |
| 506 |
} |
| 507 |
return e, nil |
| 508 |
}) |
| 509 |
if !config.StdLib.Disabled { |
| 510 |
envOpts = append(envOpts, StdLib(StdLibSubset(config.StdLib))) |
| 511 |
} |
| 512 |
} else { |
| 513 |
envOpts = append(envOpts, StdLib()) |
| 514 |
} |
| 515 |
|
| 516 |
// Configure the container |
| 517 |
if config.Container != "" { |
| 518 |
envOpts = append(envOpts, Container(config.Container)) |
| 519 |
} |
| 520 |
|
| 521 |
// Configure abbreviations |
| 522 |
for _, imp := range config.Imports { |
| 523 |
envOpts = append(envOpts, Abbrevs(imp.Name)) |
| 524 |
} |
| 525 |
|
| 526 |
// Configure the context variable declaration |
| 527 |
if config.ContextVariable != nil { |
| 528 |
typeName := config.ContextVariable.TypeName |
| 529 |
if _, found := provider.FindStructType(typeName); !found { |
| 530 |
return nil, fmt.Errorf("invalid context proto type: %q", typeName) |
| 531 |
} |
| 532 |
// Attempt to instantiate the proto in order to reflect to its descriptor |
| 533 |
msg := provider.NewValue(typeName, map[string]ref.Val{}) |
| 534 |
pbMsg, ok := msg.Value().(proto.Message) |
| 535 |
if !ok { |
| 536 |
return nil, fmt.Errorf("unsupported context type: %T", msg.Value()) |
| 537 |
} |
| 538 |
envOpts = append(envOpts, DeclareContextProto(pbMsg.ProtoReflect().Descriptor())) |
| 539 |
} |
| 540 |
|
| 541 |
// Configure variables |
| 542 |
if len(config.Variables) != 0 { |
| 543 |
vars := make([]*decls.VariableDecl, 0, len(config.Variables)) |
| 544 |
for _, v := range config.Variables { |
| 545 |
vDef, err := v.AsCELVariable(provider) |
| 546 |
if err != nil { |
| 547 |
return nil, err |
| 548 |
} |
| 549 |
vars = append(vars, vDef) |
| 550 |
} |
| 551 |
envOpts = append(envOpts, VariableDecls(vars...)) |
| 552 |
} |
| 553 |
|
| 554 |
// Configure functions |
| 555 |
if len(config.Functions) != 0 { |
| 556 |
funcs := make([]*decls.FunctionDecl, 0, len(config.Functions)) |
| 557 |
for _, f := range config.Functions { |
| 558 |
fnDef, err := f.AsCELFunction(provider) |
| 559 |
if err != nil { |
| 560 |
return nil, err |
| 561 |
} |
| 562 |
funcs = append(funcs, fnDef) |
| 563 |
} |
| 564 |
envOpts = append(envOpts, FunctionDecls(funcs...)) |
| 565 |
} |
| 566 |
|
| 567 |
// Configure features |
| 568 |
for _, feat := range config.Features { |
| 569 |
// Note, if a feature is not found, it is skipped as it is possible the feature |
| 570 |
// is not intended to be supported publicly. In the future, a refinement of |
| 571 |
// to this strategy to report unrecognized features and validators should probably |
| 572 |
// be covered as a standard ConfigOptionFactory |
| 573 |
if id, found := featureIDByName(feat.Name); found { |
| 574 |
envOpts = append(envOpts, features(id, feat.Enabled)) |
| 575 |
} |
| 576 |
} |
| 577 |
|
| 578 |
// Configure validators |
| 579 |
for _, val := range config.Validators { |
| 580 |
if fac, found := astValidatorFactories[val.Name]; found { |
| 581 |
envOpts = append(envOpts, func(e *Env) (*Env, error) { |
| 582 |
validator, err := fac(val) |
| 583 |
if err != nil { |
| 584 |
return nil, fmt.Errorf("%w", err) |
| 585 |
} |
| 586 |
return ASTValidators(validator)(e) |
| 587 |
}) |
| 588 |
} else if opt, handled := handleExtendedConfigOption(val, optFactories); handled { |
| 589 |
envOpts = append(envOpts, opt) |
| 590 |
} |
| 591 |
// we don't error when the validator isn't found as it may be part |
| 592 |
// of an extension library and enabled implicitly. |
| 593 |
} |
| 594 |
|
| 595 |
// Configure extensions |
| 596 |
for _, ext := range config.Extensions { |
| 597 |
// version number has been validated by the call to `Validate` |
| 598 |
ver, _ := ext.VersionNumber() |
| 599 |
if ext.Name == "optional" { |
| 600 |
envOpts = append(envOpts, OptionalTypes(OptionalTypesVersion(ver))) |
| 601 |
} else { |
| 602 |
opt, handled := handleExtendedConfigOption(ext, optFactories) |
| 603 |
if !handled { |
| 604 |
return nil, fmt.Errorf("unrecognized extension: %s", ext.Name) |
| 605 |
} |
| 606 |
envOpts = append(envOpts, opt) |
| 607 |
} |
| 608 |
} |
| 609 |
|
| 610 |
return envOpts, nil |
| 611 |
} |
| 612 |
|
| 613 |
func handleExtendedConfigOption(conf any, optFactories []ConfigOptionFactory) (EnvOption, bool) { |
| 614 |
for _, optFac := range optFactories { |
| 615 |
if opt, useOption := optFac(conf); useOption { |
| 616 |
return opt, true |
| 617 |
} |
| 618 |
} |
| 619 |
return nil, false |
| 620 |
} |
| 621 |
|
| 622 |
// EvalOption indicates an evaluation option that may affect the evaluation behavior or information |
| 623 |
// in the output result. |
| 624 |
type EvalOption int |
| 625 |
|
| 626 |
const ( |
| 627 |
// OptTrackState will cause the runtime to return an immutable EvalState value in the Result. |
| 628 |
OptTrackState EvalOption = 1 << iota |
| 629 |
|
| 630 |
// OptExhaustiveEval causes the runtime to disable short-circuits and track state. |
| 631 |
OptExhaustiveEval EvalOption = 1<<iota | OptTrackState |
| 632 |
|
| 633 |
// OptOptimize precomputes functions and operators with constants as arguments at program |
| 634 |
// creation time. It also pre-compiles regex pattern constants passed to 'matches', reports any compilation errors |
| 635 |
// at program creation and uses the compiled regex pattern for all 'matches' function invocations. |
| 636 |
// This flag is useful when the expression will be evaluated repeatedly against |
| 637 |
// a series of different inputs. |
| 638 |
OptOptimize EvalOption = 1 << iota |
| 639 |
|
| 640 |
// OptPartialEval enables the evaluation of a partial state where the input data that may be |
| 641 |
// known to be missing, either as top-level variables, or somewhere within a variable's object |
| 642 |
// member graph. |
| 643 |
// |
| 644 |
// By itself, OptPartialEval does not change evaluation behavior unless the input to the |
| 645 |
// Program Eval() call is created via PartialVars(). |
| 646 |
OptPartialEval EvalOption = 1 << iota |
| 647 |
|
| 648 |
// OptTrackCost enables the runtime cost calculation while validation and return cost within evalDetails |
| 649 |
// cost calculation is available via func ActualCost() |
| 650 |
OptTrackCost EvalOption = 1 << iota |
| 651 |
|
| 652 |
// OptCheckStringFormat enables compile-time checking of string.format calls for syntax/cardinality. |
| 653 |
// |
| 654 |
// Deprecated: use ext.StringsValidateFormatCalls() as this option is now a no-op. |
| 655 |
OptCheckStringFormat EvalOption = 1 << iota |
| 656 |
) |
| 657 |
|
| 658 |
// EvalOptions sets one or more evaluation options which may affect the evaluation or Result. |
| 659 |
func EvalOptions(opts ...EvalOption) ProgramOption { |
| 660 |
return func(p *prog) (*prog, error) { |
| 661 |
for _, opt := range opts { |
| 662 |
p.evalOpts |= opt |
| 663 |
} |
| 664 |
return p, nil |
| 665 |
} |
| 666 |
} |
| 667 |
|
| 668 |
// InterruptCheckFrequency configures the number of iterations within a comprehension to evaluate |
| 669 |
// before checking whether the function evaluation has been interrupted. |
| 670 |
func InterruptCheckFrequency(checkFrequency uint) ProgramOption { |
| 671 |
return func(p *prog) (*prog, error) { |
| 672 |
p.interruptCheckFrequency = checkFrequency |
| 673 |
return p, nil |
| 674 |
} |
| 675 |
} |
| 676 |
|
| 677 |
// CostEstimatorOptions configure type-check time options for estimating expression cost. |
| 678 |
func CostEstimatorOptions(costOpts ...checker.CostOption) EnvOption { |
| 679 |
return func(e *Env) (*Env, error) { |
| 680 |
e.costOptions = append(e.costOptions, costOpts...) |
| 681 |
return e, nil |
| 682 |
} |
| 683 |
} |
| 684 |
|
| 685 |
// CostTrackerOptions configures a set of options for cost-tracking. |
| 686 |
// |
| 687 |
// Note, CostTrackerOptions is a no-op unless CostTracking is also enabled. |
| 688 |
func CostTrackerOptions(costOpts ...interpreter.CostTrackerOption) ProgramOption { |
| 689 |
return func(p *prog) (*prog, error) { |
| 690 |
p.costOptions = append(p.costOptions, costOpts...) |
| 691 |
return p, nil |
| 692 |
} |
| 693 |
} |
| 694 |
|
| 695 |
// CostTracking enables cost tracking and registers a ActualCostEstimator that can optionally provide a runtime cost estimate for any function calls. |
| 696 |
func CostTracking(costEstimator interpreter.ActualCostEstimator) ProgramOption { |
| 697 |
return func(p *prog) (*prog, error) { |
| 698 |
p.callCostEstimator = costEstimator |
| 699 |
p.evalOpts |= OptTrackCost |
| 700 |
return p, nil |
| 701 |
} |
| 702 |
} |
| 703 |
|
| 704 |
// CostLimit enables cost tracking and sets configures program evaluation to exit early with a |
| 705 |
// "runtime cost limit exceeded" error if the runtime cost exceeds the costLimit. |
| 706 |
// The CostLimit is a metric that corresponds to the number and estimated expense of operations |
| 707 |
// performed while evaluating an expression. It is indicative of CPU usage, not memory usage. |
| 708 |
func CostLimit(costLimit uint64) ProgramOption { |
| 709 |
return func(p *prog) (*prog, error) { |
| 710 |
p.costLimit = &costLimit |
| 711 |
p.evalOpts |= OptTrackCost |
| 712 |
return p, nil |
| 713 |
} |
| 714 |
} |
| 715 |
|
| 716 |
func fieldToCELType(field protoreflect.FieldDescriptor) (*Type, error) { |
| 717 |
if field.Kind() == protoreflect.MessageKind || field.Kind() == protoreflect.GroupKind { |
| 718 |
msgName := (string)(field.Message().FullName()) |
| 719 |
return ObjectType(msgName), nil |
| 720 |
} |
| 721 |
if primitiveType, found := types.ProtoCELPrimitives[field.Kind()]; found { |
| 722 |
return primitiveType, nil |
| 723 |
} |
| 724 |
if field.Kind() == protoreflect.EnumKind { |
| 725 |
return IntType, nil |
| 726 |
} |
| 727 |
return nil, fmt.Errorf("field %s type %s not implemented", field.FullName(), field.Kind().String()) |
| 728 |
} |
| 729 |
|
| 730 |
func fieldToVariable(field protoreflect.FieldDescriptor) (*decls.VariableDecl, error) { |
| 731 |
name := string(field.Name()) |
| 732 |
if field.IsMap() { |
| 733 |
mapKey := field.MapKey() |
| 734 |
mapValue := field.MapValue() |
| 735 |
keyType, err := fieldToCELType(mapKey) |
| 736 |
if err != nil { |
| 737 |
return nil, err |
| 738 |
} |
| 739 |
valueType, err := fieldToCELType(mapValue) |
| 740 |
if err != nil { |
| 741 |
return nil, err |
| 742 |
} |
| 743 |
return decls.NewVariable(name, MapType(keyType, valueType)), nil |
| 744 |
} |
| 745 |
if field.IsList() { |
| 746 |
elemType, err := fieldToCELType(field) |
| 747 |
if err != nil { |
| 748 |
return nil, err |
| 749 |
} |
| 750 |
return decls.NewVariable(name, ListType(elemType)), nil |
| 751 |
} |
| 752 |
celType, err := fieldToCELType(field) |
| 753 |
if err != nil { |
| 754 |
return nil, err |
| 755 |
} |
| 756 |
return decls.NewVariable(name, celType), nil |
| 757 |
} |
| 758 |
|
| 759 |
// DeclareContextProto returns an option to extend CEL environment with declarations from the given context proto. |
| 760 |
// Each field of the proto defines a variable of the same name in the environment. |
| 761 |
// https://github.com/google/cel-spec/blob/master/doc/langdef.md#evaluation-environment |
| 762 |
func DeclareContextProto(descriptor protoreflect.MessageDescriptor) EnvOption { |
| 763 |
return func(e *Env) (*Env, error) { |
| 764 |
if e.contextProto != nil { |
| 765 |
return nil, fmt.Errorf("context proto already declared as %q, got %q", |
| 766 |
e.contextProto.FullName(), descriptor.FullName()) |
| 767 |
} |
| 768 |
e.contextProto = descriptor |
| 769 |
fields := descriptor.Fields() |
| 770 |
vars := make([]*decls.VariableDecl, 0, fields.Len()) |
| 771 |
for i := 0; i < fields.Len(); i++ { |
| 772 |
field := fields.Get(i) |
| 773 |
variable, err := fieldToVariable(field) |
| 774 |
if err != nil { |
| 775 |
return nil, err |
| 776 |
} |
| 777 |
vars = append(vars, variable) |
| 778 |
} |
| 779 |
var err error |
| 780 |
e, err = VariableDecls(vars...)(e) |
| 781 |
if err != nil { |
| 782 |
return nil, err |
| 783 |
} |
| 784 |
return Types(dynamicpb.NewMessage(descriptor))(e) |
| 785 |
} |
| 786 |
} |
| 787 |
|
| 788 |
// ContextProtoVars uses the fields of the input proto.Messages as top-level variables within an Activation. |
| 789 |
// |
| 790 |
// Consider using with `DeclareContextProto` to simplify variable type declarations and publishing when using |
| 791 |
// protocol buffers. |
| 792 |
func ContextProtoVars(ctx proto.Message) (Activation, error) { |
| 793 |
if ctx == nil || !ctx.ProtoReflect().IsValid() { |
| 794 |
return interpreter.EmptyActivation(), nil |
| 795 |
} |
| 796 |
reg, err := types.NewRegistry(ctx) |
| 797 |
if err != nil { |
| 798 |
return nil, err |
| 799 |
} |
| 800 |
pbRef := ctx.ProtoReflect() |
| 801 |
typeName := string(pbRef.Descriptor().FullName()) |
| 802 |
fields := pbRef.Descriptor().Fields() |
| 803 |
vars := make(map[string]any, fields.Len()) |
| 804 |
for i := 0; i < fields.Len(); i++ { |
| 805 |
field := fields.Get(i) |
| 806 |
sft, found := reg.FindStructFieldType(typeName, field.TextName()) |
| 807 |
if !found { |
| 808 |
return nil, fmt.Errorf("no such field: %s", field.TextName()) |
| 809 |
} |
| 810 |
fieldVal, err := sft.GetFrom(ctx) |
| 811 |
if err != nil { |
| 812 |
return nil, err |
| 813 |
} |
| 814 |
vars[field.TextName()] = fieldVal |
| 815 |
} |
| 816 |
return NewActivation(vars) |
| 817 |
} |
| 818 |
|
| 819 |
// EnableMacroCallTracking ensures that call expressions which are replaced by macros |
| 820 |
// are tracked in the `SourceInfo` of parsed and checked expressions. |
| 821 |
func EnableMacroCallTracking() EnvOption { |
| 822 |
return features(featureEnableMacroCallTracking, true) |
| 823 |
} |
| 824 |
|
| 825 |
// EnableIdentifierEscapeSyntax enables identifier escaping (`) syntax for |
| 826 |
// fields. |
| 827 |
func EnableIdentifierEscapeSyntax() EnvOption { |
| 828 |
return features(featureIdentEscapeSyntax, true) |
| 829 |
} |
| 830 |
|
| 831 |
// CrossTypeNumericComparisons makes it possible to compare across numeric types, e.g. double < int |
| 832 |
func CrossTypeNumericComparisons(enabled bool) EnvOption { |
| 833 |
return features(featureCrossTypeNumericComparisons, enabled) |
| 834 |
} |
| 835 |
|
| 836 |
// DefaultUTCTimeZone ensures that time-based operations use the UTC timezone rather than the |
| 837 |
// input time's local timezone. |
| 838 |
func DefaultUTCTimeZone(enabled bool) EnvOption { |
| 839 |
return features(featureDefaultUTCTimeZone, enabled) |
| 840 |
} |
| 841 |
|
| 842 |
// features sets the given feature flags. See list of Feature constants above. |
| 843 |
func features(flag int, enabled bool) EnvOption { |
| 844 |
return func(e *Env) (*Env, error) { |
| 845 |
e.features[flag] = enabled |
| 846 |
return e, nil |
| 847 |
} |
| 848 |
} |
| 849 |
|
| 850 |
// ParserRecursionLimit adjusts the AST depth the parser will tolerate. |
| 851 |
// Defaults defined in the parser package. |
| 852 |
func ParserRecursionLimit(limit int) EnvOption { |
| 853 |
return func(e *Env) (*Env, error) { |
| 854 |
e.prsrOpts = append(e.prsrOpts, parser.MaxRecursionDepth(limit)) |
| 855 |
return e, nil |
| 856 |
} |
| 857 |
} |
| 858 |
|
| 859 |
// ParserExpressionSizeLimit adjusts the number of code points the expression parser is allowed to parse. |
| 860 |
// Defaults defined in the parser package. |
| 861 |
func ParserExpressionSizeLimit(limit int) EnvOption { |
| 862 |
return func(e *Env) (*Env, error) { |
| 863 |
e.prsrOpts = append(e.prsrOpts, parser.ExpressionSizeCodePointLimit(limit)) |
| 864 |
return e, nil |
| 865 |
} |
| 866 |
} |
| 867 |
|
| 868 |
// EnableHiddenAccumulatorName sets the parser to use the identifier '@result' for accumulators |
| 869 |
// which is not normally accessible from CEL source. |
| 870 |
func EnableHiddenAccumulatorName(enabled bool) EnvOption { |
| 871 |
return func(e *Env) (*Env, error) { |
| 872 |
e.prsrOpts = append(e.prsrOpts, parser.EnableHiddenAccumulatorName(enabled)) |
| 873 |
return e, nil |
| 874 |
} |
| 875 |
} |
| 876 |
|
| 877 |
func maybeInteropProvider(provider any) (types.Provider, error) { |
| 878 |
switch p := provider.(type) { |
| 879 |
case types.Provider: |
| 880 |
return p, nil |
| 881 |
case ref.TypeProvider: |
| 882 |
return &interopCELTypeProvider{TypeProvider: p}, nil |
| 883 |
default: |
| 884 |
return nil, fmt.Errorf("unsupported type provider: %T", provider) |
| 885 |
} |
| 886 |
} |