Debian Codegraph @

debian/missing-sources/github.com/google/cel-go/cel/validator.go

raw symbols SCIP
1 // Copyright 2023 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 "fmt"
19 "reflect"
20 "regexp"
21
22 "github.com/google/cel-go/common/ast"
23 "github.com/google/cel-go/common/env"
24 "github.com/google/cel-go/common/overloads"
25 )
26
27 const (
28 durationValidatorName = "cel.validator.duration"
29 regexValidatorName = "cel.validator.matches"
30 timestampValidatorName = "cel.validator.timestamp"
31 homogeneousValidatorName = "cel.validator.homogeneous_literals"
32 nestingLimitValidatorName = "cel.validator.comprehension_nesting_limit"
33
34 // HomogeneousAggregateLiteralExemptFunctions is the ValidatorConfig key used to configure
35 // the set of function names which are exempt from homogeneous type checks. The expected type
36 // is a string list of function names.
37 //
38 // As an example, the `<string>.format([args])` call expects the input arguments list to be
39 // comprised of a variety of types which correspond to the types expected by the format control
40 // clauses; however, all other uses of a mixed element type list, would be unexpected.
41 HomogeneousAggregateLiteralExemptFunctions = homogeneousValidatorName + ".exempt"
42 )
43
44 var (
45 astValidatorFactories = map[string]ASTValidatorFactory{
46 nestingLimitValidatorName: func(val *env.Validator) (ASTValidator, error) {
47 if limit, found := val.ConfigValue("limit"); found {
48 // In case of protos, config value is of type by google.protobuf.Value, which numeric values are always a double.
49 if val, isDouble := limit.(float64); isDouble {
50 if val != float64(int64(val)) {
51 return nil, fmt.Errorf("invalid validator: %s, limit value is not a whole number: %v", nestingLimitValidatorName, limit)
52 }
53 return ValidateComprehensionNestingLimit(int(val)), nil
54 }
55
56 if val, isInt := limit.(int); isInt {
57 return ValidateComprehensionNestingLimit(val), nil
58 }
59 return nil, fmt.Errorf("invalid validator: %s unsupported limit type: %v", nestingLimitValidatorName, limit)
60 }
61 return nil, fmt.Errorf("invalid validator: %s missing limit", nestingLimitValidatorName)
62 },
63 durationValidatorName: func(*env.Validator) (ASTValidator, error) {
64 return ValidateDurationLiterals(), nil
65 },
66 regexValidatorName: func(*env.Validator) (ASTValidator, error) {
67 return ValidateRegexLiterals(), nil
68 },
69 timestampValidatorName: func(*env.Validator) (ASTValidator, error) {
70 return ValidateTimestampLiterals(), nil
71 },
72 homogeneousValidatorName: func(*env.Validator) (ASTValidator, error) {
73 return ValidateHomogeneousAggregateLiterals(), nil
74 },
75 }
76 )
77
78 // ASTValidatorFactory creates an ASTValidator as configured by the input map
79 type ASTValidatorFactory func(*env.Validator) (ASTValidator, error)
80
81 // ASTValidators configures a set of ASTValidator instances into the target environment.
82 //
83 // Validators are applied in the order in which the are specified and are treated as singletons.
84 // The same ASTValidator with a given name will not be applied more than once.
85 func ASTValidators(validators ...ASTValidator) EnvOption {
86 return func(e *Env) (*Env, error) {
87 for _, v := range validators {
88 if !e.HasValidator(v.Name()) {
89 e.validators = append(e.validators, v)
90 }
91 }
92 return e, nil
93 }
94 }
95
96 // ASTValidator defines a singleton interface for validating a type-checked Ast against an environment.
97 //
98 // Note: the Issues argument is mutable in the sense that it is intended to collect errors which will be
99 // reported to the caller.
100 type ASTValidator interface {
101 // Name returns the name of the validator. Names must be unique.
102 Name() string
103
104 // Validate validates a given Ast within an Environment and collects a set of potential issues.
105 //
106 // The ValidatorConfig is generated from the set of ASTValidatorConfigurer instances prior to
107 // the invocation of the Validate call. The expectation is that the validator configuration
108 // is created in sequence and immutable once provided to the Validate call.
109 //
110 // See individual validators for more information on their configuration keys and configuration
111 // properties.
112 Validate(*Env, ValidatorConfig, *ast.AST, *Issues)
113 }
114
115 // ConfigurableASTValidator supports conversion of an object to an `env.Validator` instance used for
116 // YAML serialization.
117 type ConfigurableASTValidator interface {
118 // ToConfig converts the internal configuration of an ASTValidator into an env.Validator instance
119 // which minimally must include the validator name, but may also include a map[string]any config
120 // object to be serialized to YAML. The string keys represent the configuration parameter name,
121 // and the any value must mirror the internally supported type associated with the config key.
122 //
123 // Note: only primitive CEL types are supported by CEL validators at this time.
124 ToConfig() *env.Validator
125 }
126
127 // ValidatorConfig provides an accessor method for querying validator configuration state.
128 type ValidatorConfig interface {
129 GetOrDefault(name string, value any) any
130 }
131
132 // MutableValidatorConfig provides mutation methods for querying and updating validator configuration
133 // settings.
134 type MutableValidatorConfig interface {
135 ValidatorConfig
136 Set(name string, value any) error
137 }
138
139 // ASTValidatorConfigurer indicates that this object, currently expected to be an ASTValidator,
140 // participates in validator configuration settings.
141 //
142 // This interface may be split from the expectation of being an ASTValidator instance in the future.
143 type ASTValidatorConfigurer interface {
144 Configure(MutableValidatorConfig) error
145 }
146
147 // validatorConfig implements the ValidatorConfig and MutableValidatorConfig interfaces.
148 type validatorConfig struct {
149 data map[string]any
150 }
151
152 // newValidatorConfig initializes the validator config with default values for core CEL validators.
153 func newValidatorConfig() *validatorConfig {
154 return &validatorConfig{
155 data: map[string]any{
156 HomogeneousAggregateLiteralExemptFunctions: []string{},
157 },
158 }
159 }
160
161 // GetOrDefault returns the configured value for the name, if present, else the input default value.
162 //
163 // Note, the type-agreement between the input default and configured value is not checked on read.
164 func (config *validatorConfig) GetOrDefault(name string, value any) any {
165 v, found := config.data[name]
166 if !found {
167 return value
168 }
169 return v
170 }
171
172 // Set configures a validator option with the given name and value.
173 //
174 // If the value had previously been set, the new value must have the same reflection type as the old one,
175 // or the call will error.
176 func (config *validatorConfig) Set(name string, value any) error {
177 v, found := config.data[name]
178 if found && reflect.TypeOf(v) != reflect.TypeOf(value) {
179 return fmt.Errorf("incompatible configuration type for %s, got %T, wanted %T", name, value, v)
180 }
181 config.data[name] = value
182 return nil
183 }
184
185 // ExtendedValidations collects a set of common AST validations which reduce the likelihood of runtime errors.
186 //
187 // - Validate duration and timestamp literals
188 // - Ensure regex strings are valid
189 // - Disable mixed type list and map literals
190 func ExtendedValidations() EnvOption {
191 return ASTValidators(
192 ValidateDurationLiterals(),
193 ValidateTimestampLiterals(),
194 ValidateRegexLiterals(),
195 ValidateHomogeneousAggregateLiterals(),
196 )
197 }
198
199 // ValidateDurationLiterals ensures that duration literal arguments are valid immediately after type-check.
200 func ValidateDurationLiterals() ASTValidator {
201 return newFormatValidator(overloads.TypeConvertDuration, 0, evalCall)
202 }
203
204 // ValidateTimestampLiterals ensures that timestamp literal arguments are valid immediately after type-check.
205 func ValidateTimestampLiterals() ASTValidator {
206 return newFormatValidator(overloads.TypeConvertTimestamp, 0, evalCall)
207 }
208
209 // ValidateRegexLiterals ensures that regex patterns are validated after type-check.
210 func ValidateRegexLiterals() ASTValidator {
211 return newFormatValidator(overloads.Matches, 0, compileRegex)
212 }
213
214 // ValidateHomogeneousAggregateLiterals checks that all list and map literals entries have the same types, i.e.
215 // no mixed list element types or mixed map key or map value types.
216 //
217 // Note: the string format call relies on a mixed element type list for ease of use, so this check skips all
218 // literals which occur within string format calls.
219 func ValidateHomogeneousAggregateLiterals() ASTValidator {
220 return homogeneousAggregateLiteralValidator{}
221 }
222
223 // ValidateComprehensionNestingLimit ensures that comprehension nesting does not exceed the specified limit.
224 //
225 // This validator can be useful for preventing arbitrarily nested comprehensions which can take high polynomial
226 // time to complete.
227 //
228 // Note, this limit does not apply to comprehensions with an empty iteration range, as these comprehensions have
229 // no actual looping cost. The cel.bind() utilizes the comprehension structure to perform local variable
230 // assignments and supplies an empty iteration range, so they won't count against the nesting limit either.
231 func ValidateComprehensionNestingLimit(limit int) ASTValidator {
232 return nestingLimitValidator{limit: limit}
233 }
234
235 type argChecker func(env *Env, call, arg ast.Expr) error
236
237 func newFormatValidator(funcName string, argNum int, check argChecker) formatValidator {
238 return formatValidator{
239 funcName: funcName,
240 check: check,
241 argNum: argNum,
242 }
243 }
244
245 type formatValidator struct {
246 funcName string
247 argNum int
248 check argChecker
249 }
250
251 // Name returns the unique name of this function format validator.
252 func (v formatValidator) Name() string {
253 return fmt.Sprintf("cel.validator.%s", v.funcName)
254 }
255
256 // ToConfig converts the ASTValidator to an env.Validator specifying the validator name.
257 func (v formatValidator) ToConfig() *env.Validator {
258 return env.NewValidator(v.Name())
259 }
260
261 // Validate searches the AST for uses of a given function name with a constant argument and performs a check
262 // on whether the argument is a valid literal value.
263 func (v formatValidator) Validate(e *Env, _ ValidatorConfig, a *ast.AST, iss *Issues) {
264 root := ast.NavigateAST(a)
265 funcCalls := ast.MatchDescendants(root, ast.FunctionMatcher(v.funcName))
266 for _, call := range funcCalls {
267 callArgs := call.AsCall().Args()
268 if len(callArgs) <= v.argNum {
269 continue
270 }
271 litArg := callArgs[v.argNum]
272 if litArg.Kind() != ast.LiteralKind {
273 continue
274 }
275 if err := v.check(e, call, litArg); err != nil {
276 iss.ReportErrorAtID(litArg.ID(), "invalid %s argument", v.funcName)
277 }
278 }
279 }
280
281 func evalCall(env *Env, call, arg ast.Expr) error {
282 ast := &Ast{impl: ast.NewAST(call, ast.NewSourceInfo(nil))}
283 prg, err := env.Program(ast)
284 if err != nil {
285 return err
286 }
287 _, _, err = prg.Eval(NoVars())
288 return err
289 }
290
291 func compileRegex(_ *Env, _, arg ast.Expr) error {
292 pattern := arg.AsLiteral().Value().(string)
293 _, err := regexp.Compile(pattern)
294 return err
295 }
296
297 type homogeneousAggregateLiteralValidator struct{}
298
299 // Name returns the unique name of the homogeneous type validator.
300 func (homogeneousAggregateLiteralValidator) Name() string {
301 return homogeneousValidatorName
302 }
303
304 // ToConfig converts the ASTValidator to an env.Validator specifying the validator name.
305 func (v homogeneousAggregateLiteralValidator) ToConfig() *env.Validator {
306 return env.NewValidator(v.Name())
307 }
308
309 // Validate validates that all lists and map literals have homogeneous types, i.e. don't contain dyn types.
310 //
311 // This validator makes an exception for list and map literals which occur at any level of nesting within
312 // string format calls.
313 func (v homogeneousAggregateLiteralValidator) Validate(_ *Env, c ValidatorConfig, a *ast.AST, iss *Issues) {
314 var exemptedFunctions []string
315 exemptedFunctions = c.GetOrDefault(HomogeneousAggregateLiteralExemptFunctions, exemptedFunctions).([]string)
316 root := ast.NavigateAST(a)
317 listExprs := ast.MatchDescendants(root, ast.KindMatcher(ast.ListKind))
318 for _, listExpr := range listExprs {
319 if inExemptFunction(listExpr, exemptedFunctions) {
320 continue
321 }
322 l := listExpr.AsList()
323 elements := l.Elements()
324 optIndices := l.OptionalIndices()
325 var elemType *Type
326 for i, e := range elements {
327 et := a.GetType(e.ID())
328 if isOptionalIndex(i, optIndices) {
329 et = et.Parameters()[0]
330 }
331 if elemType == nil {
332 elemType = et
333 continue
334 }
335 if !elemType.IsEquivalentType(et) {
336 v.typeMismatch(iss, e.ID(), elemType, et)
337 break
338 }
339 }
340 }
341 mapExprs := ast.MatchDescendants(root, ast.KindMatcher(ast.MapKind))
342 for _, mapExpr := range mapExprs {
343 if inExemptFunction(mapExpr, exemptedFunctions) {
344 continue
345 }
346 m := mapExpr.AsMap()
347 entries := m.Entries()
348 var keyType, valType *Type
349 for _, e := range entries {
350 mapEntry := e.AsMapEntry()
351 key, val := mapEntry.Key(), mapEntry.Value()
352 kt, vt := a.GetType(key.ID()), a.GetType(val.ID())
353 if mapEntry.IsOptional() {
354 vt = vt.Parameters()[0]
355 }
356 if keyType == nil && valType == nil {
357 keyType, valType = kt, vt
358 continue
359 }
360 if !keyType.IsEquivalentType(kt) {
361 v.typeMismatch(iss, key.ID(), keyType, kt)
362 }
363 if !valType.IsEquivalentType(vt) {
364 v.typeMismatch(iss, val.ID(), valType, vt)
365 }
366 }
367 }
368 }
369
370 func inExemptFunction(e ast.NavigableExpr, exemptFunctions []string) bool {
371 parent, found := e.Parent()
372 for found {
373 if parent.Kind() == ast.CallKind {
374 fnName := parent.AsCall().FunctionName()
375 for _, exempt := range exemptFunctions {
376 if exempt == fnName {
377 return true
378 }
379 }
380 }
381 parent, found = parent.Parent()
382 }
383 return false
384 }
385
386 func isOptionalIndex(i int, optIndices []int32) bool {
387 for _, optInd := range optIndices {
388 if i == int(optInd) {
389 return true
390 }
391 }
392 return false
393 }
394
395 func (homogeneousAggregateLiteralValidator) typeMismatch(iss *Issues, id int64, expected, actual *Type) {
396 iss.ReportErrorAtID(id, "expected type '%s' but found '%s'", FormatCELType(expected), FormatCELType(actual))
397 }
398
399 type nestingLimitValidator struct {
400 limit int
401 }
402
403 // Name returns the name of the nesting limit validator.
404 func (v nestingLimitValidator) Name() string {
405 return nestingLimitValidatorName
406 }
407
408 // ToConfig converts the ASTValidator to an env.Validator specifying the validator name and the nesting limit
409 // as an integer value: {"limit": int}
410 func (v nestingLimitValidator) ToConfig() *env.Validator {
411 return env.NewValidator(v.Name()).SetConfig(map[string]any{"limit": v.limit})
412 }
413
414 // Validate implements the ASTValidator interface method.
415 func (v nestingLimitValidator) Validate(e *Env, _ ValidatorConfig, a *ast.AST, iss *Issues) {
416 root := ast.NavigateAST(a)
417 comprehensions := ast.MatchDescendants(root, ast.KindMatcher(ast.ComprehensionKind))
418 if len(comprehensions) <= v.limit {
419 return
420 }
421 for _, comp := range comprehensions {
422 count := 0
423 e := comp
424 hasParent := true
425 for hasParent {
426 // When the expression is not a comprehension, continue to the next ancestor.
427 if e.Kind() != ast.ComprehensionKind {
428 e, hasParent = e.Parent()
429 continue
430 }
431 // When the comprehension has an empty range, continue to the next ancestor
432 // as this comprehension does not have any associated cost.
433 iterRange := e.AsComprehension().IterRange()
434 if iterRange.Kind() == ast.ListKind && iterRange.AsList().Size() == 0 {
435 e, hasParent = e.Parent()
436 continue
437 }
438 // Otherwise check the nesting limit.
439 count++
440 if count > v.limit {
441 iss.ReportErrorAtID(comp.ID(), "comprehension exceeds nesting limit")
442 break
443 }
444 e, hasParent = e.Parent()
445 }
446 }
447 }