Debian Codegraph @

common/env/env.go

raw
1 // Copyright 2025 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // 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 env provides a representation of a CEL environment.
16 package env
17
18 import (
19 "errors"
20 "fmt"
21 "math"
22 "strconv"
23 "strings"
24
25 "github.com/google/cel-go/common/decls"
26 "github.com/google/cel-go/common/types"
27 )
28
29 // NewConfig creates an instance of a YAML serializable CEL environment configuration.
30 func NewConfig(name string) *Config {
31 return &Config{
32 Name: name,
33 }
34 }
35
36 // Config represents a serializable form of the CEL environment configuration.
37 //
38 // Note: custom validations, feature flags, and performance tuning parameters are not (yet)
39 // considered part of the core CEL environment configuration and should be managed separately
40 // until a common convention for such settings is developed.
41 type Config struct {
42 Name string `yaml:"name,omitempty"`
43 Description string `yaml:"description,omitempty"`
44 Container string `yaml:"container,omitempty"`
45 Imports []*Import `yaml:"imports,omitempty"`
46 StdLib *LibrarySubset `yaml:"stdlib,omitempty"`
47 Extensions []*Extension `yaml:"extensions,omitempty"`
48 ContextVariable *ContextVariable `yaml:"context_variable,omitempty"`
49 Variables []*Variable `yaml:"variables,omitempty"`
50 Functions []*Function `yaml:"functions,omitempty"`
51 Validators []*Validator `yaml:"validators,omitempty"`
52 Features []*Feature `yaml:"features,omitempty"`
53 }
54
55 // Validate validates the whole configuration is well-formed.
56 func (c *Config) Validate() error {
57 if c == nil {
58 return nil
59 }
60 var errs []error
61 for _, imp := range c.Imports {
62 if err := imp.Validate(); err != nil {
63 errs = append(errs, err)
64 }
65 }
66 if err := c.StdLib.Validate(); err != nil {
67 errs = append(errs, err)
68 }
69 for _, ext := range c.Extensions {
70 if err := ext.Validate(); err != nil {
71 errs = append(errs, err)
72 }
73 }
74 if err := c.ContextVariable.Validate(); err != nil {
75 errs = append(errs, err)
76 }
77 if c.ContextVariable != nil && len(c.Variables) != 0 {
78 errs = append(errs, errors.New("invalid config: either context variable or variables may be set, but not both"))
79 }
80 for _, v := range c.Variables {
81 if err := v.Validate(); err != nil {
82 errs = append(errs, err)
83 }
84 }
85 for _, fn := range c.Functions {
86 if err := fn.Validate(); err != nil {
87 errs = append(errs, err)
88 }
89 }
90 for _, feat := range c.Features {
91 if err := feat.Validate(); err != nil {
92 errs = append(errs, err)
93 }
94 }
95 for _, val := range c.Validators {
96 if err := val.Validate(); err != nil {
97 errs = append(errs, err)
98 }
99 }
100 return errors.Join(errs...)
101 }
102
103 // SetContainer configures the container name for this configuration.
104 func (c *Config) SetContainer(container string) *Config {
105 c.Container = container
106 return c
107 }
108
109 // AddVariableDecls adds one or more variables to the config, converting them to serializable values first.
110 //
111 // VariableDecl inputs are expected to be well-formed.
112 func (c *Config) AddVariableDecls(vars ...*decls.VariableDecl) *Config {
113 convVars := make([]*Variable, len(vars))
114 for i, v := range vars {
115 if v == nil {
116 continue
117 }
118 cv := NewVariable(v.Name(), SerializeTypeDesc(v.Type()))
119 cv.Description = v.Description()
120 convVars[i] = cv
121 }
122 return c.AddVariables(convVars...)
123 }
124
125 // AddVariables adds one or more variables to the config.
126 func (c *Config) AddVariables(vars ...*Variable) *Config {
127 c.Variables = append(c.Variables, vars...)
128 return c
129 }
130
131 // SetContextVariable configures the ContextVariable for this configuration.
132 func (c *Config) SetContextVariable(ctx *ContextVariable) *Config {
133 c.ContextVariable = ctx
134 return c
135 }
136
137 // AddFunctionDecls adds one or more functions to the config, converting them to serializable values first.
138 //
139 // FunctionDecl inputs are expected to be well-formed.
140 func (c *Config) AddFunctionDecls(funcs ...*decls.FunctionDecl) *Config {
141 convFuncs := make([]*Function, len(funcs))
142 for i, fn := range funcs {
143 if fn == nil {
144 continue
145 }
146 overloads := make([]*Overload, 0, len(fn.OverloadDecls()))
147 for _, o := range fn.OverloadDecls() {
148 overloadID := o.ID()
149 args := make([]*TypeDesc, 0, len(o.ArgTypes()))
150 for _, a := range o.ArgTypes() {
151 args = append(args, SerializeTypeDesc(a))
152 }
153 ret := SerializeTypeDesc(o.ResultType())
154 var overload *Overload
155 if o.IsMemberFunction() {
156 overload = NewMemberOverload(overloadID, args[0], args[1:], ret)
157 } else {
158 overload = NewOverload(overloadID, args, ret)
159 }
160 exampleCount := len(o.Examples())
161 if exampleCount > 0 {
162 overload.Examples = o.Examples()
163 }
164 overloads = append(overloads, overload)
165 }
166 cf := NewFunction(fn.Name(), overloads...)
167 cf.Description = fn.Description()
168 convFuncs[i] = cf
169 }
170 return c.AddFunctions(convFuncs...)
171 }
172
173 // AddFunctions adds one or more functions to the config.
174 func (c *Config) AddFunctions(funcs ...*Function) *Config {
175 c.Functions = append(c.Functions, funcs...)
176 return c
177 }
178
179 // SetStdLib configures the LibrarySubset for the standard library.
180 func (c *Config) SetStdLib(subset *LibrarySubset) *Config {
181 c.StdLib = subset
182 return c
183 }
184
185 // AddImports appends a set of imports to the config.
186 func (c *Config) AddImports(imps ...*Import) *Config {
187 c.Imports = append(c.Imports, imps...)
188 return c
189 }
190
191 // AddExtensions appends a set of extensions to the config.
192 func (c *Config) AddExtensions(exts ...*Extension) *Config {
193 c.Extensions = append(c.Extensions, exts...)
194 return c
195 }
196
197 // AddValidators appends one or more validators to the config.
198 func (c *Config) AddValidators(vals ...*Validator) *Config {
199 c.Validators = append(c.Validators, vals...)
200 return c
201 }
202
203 // AddFeatures appends one or more features to the config.
204 func (c *Config) AddFeatures(feats ...*Feature) *Config {
205 c.Features = append(c.Features, feats...)
206 return c
207 }
208
209 // NewImport returns a serializable import value from the qualified type name.
210 func NewImport(name string) *Import {
211 return &Import{Name: name}
212 }
213
214 // Import represents a type name that will be appreviated by its simple name using
215 // the cel.Abbrevs() option.
216 type Import struct {
217 Name string `yaml:"name"`
218 }
219
220 // Validate validates the import configuration is well-formed.
221 func (imp *Import) Validate() error {
222 if imp == nil {
223 return errors.New("invalid import: nil")
224 }
225 if imp.Name == "" {
226 return errors.New("invalid import: missing type name")
227 }
228 return nil
229 }
230
231 // NewVariable returns a serializable variable from a name and type definition
232 func NewVariable(name string, t *TypeDesc) *Variable {
233 return NewVariableWithDoc(name, t, "")
234 }
235
236 // NewVariableWithDoc returns a serializable variable from a name, type definition, and doc string.
237 func NewVariableWithDoc(name string, t *TypeDesc, doc string) *Variable {
238 return &Variable{Name: name, TypeDesc: t, Description: doc}
239 }
240
241 // Variable represents a typed variable declaration which will be published via the
242 // cel.VariableDecls() option.
243 type Variable struct {
244 Name string `yaml:"name"`
245 Description string `yaml:"description,omitempty"`
246
247 // Type represents the type declaration for the variable.
248 //
249 // Deprecated: use the embedded *TypeDesc fields directly.
250 Type *TypeDesc `yaml:"type,omitempty"`
251
252 // TypeDesc is an embedded set of fields allowing for the specification of the Variable type.
253 *TypeDesc `yaml:",inline"`
254 }
255
256 // Validate validates the variable configuration is well-formed.
257 func (v *Variable) Validate() error {
258 if v == nil {
259 return errors.New("invalid variable: nil")
260 }
261 if v.Name == "" {
262 return errors.New("invalid variable: missing variable name")
263 }
264 if err := v.GetType().Validate(); err != nil {
265 return fmt.Errorf("invalid variable %q: %w", v.Name, err)
266 }
267 return nil
268 }
269
270 // GetType returns the variable type description.
271 //
272 // Note, if both the embedded TypeDesc and the field Type are non-nil, the embedded TypeDesc will
273 // take precedence.
274 func (v *Variable) GetType() *TypeDesc {
275 if v == nil {
276 return nil
277 }
278 if v.TypeDesc != nil {
279 return v.TypeDesc
280 }
281 if v.Type != nil {
282 return v.Type
283 }
284 return nil
285 }
286
287 // AsCELVariable converts the serializable form of the Variable into a CEL environment declaration.
288 func (v *Variable) AsCELVariable(tp types.Provider) (*decls.VariableDecl, error) {
289 if err := v.Validate(); err != nil {
290 return nil, err
291 }
292 t, err := v.GetType().AsCELType(tp)
293 if err != nil {
294 return nil, fmt.Errorf("invalid variable %q: %w", v.Name, err)
295 }
296 return decls.NewVariableWithDoc(v.Name, t, v.Description), nil
297 }
298
299 // NewContextVariable returns a serializable context variable with a specific type name.
300 func NewContextVariable(typeName string) *ContextVariable {
301 return &ContextVariable{TypeName: typeName}
302 }
303
304 // ContextVariable represents a structured message whose fields are to be treated as the top-level
305 // variable identifiers within CEL expressions.
306 type ContextVariable struct {
307 // TypeName represents the fully qualified typename of the context variable.
308 // Currently, only protobuf types are supported.
309 TypeName string `yaml:"type_name"`
310 }
311
312 // Validate validates the context-variable configuration is well-formed.
313 func (ctx *ContextVariable) Validate() error {
314 if ctx == nil {
315 return nil
316 }
317 if ctx.TypeName == "" {
318 return errors.New("invalid context variable: missing type name")
319 }
320 return nil
321 }
322
323 // NewFunction creates a serializable function and overload set.
324 func NewFunction(name string, overloads ...*Overload) *Function {
325 return &Function{Name: name, Overloads: overloads}
326 }
327
328 // NewFunctionWithDoc creates a serializable function and overload set.
329 func NewFunctionWithDoc(name, doc string, overloads ...*Overload) *Function {
330 return &Function{Name: name, Description: doc, Overloads: overloads}
331 }
332
333 // Function represents the serializable format of a function and its overloads.
334 type Function struct {
335 Name string `yaml:"name"`
336 Description string `yaml:"description,omitempty"`
337 Overloads []*Overload `yaml:"overloads,omitempty"`
338 }
339
340 // Validate validates the function configuration is well-formed.
341 func (fn *Function) Validate() error {
342 if fn == nil {
343 return errors.New("invalid function: nil")
344 }
345 if fn.Name == "" {
346 return errors.New("invalid function: missing function name")
347 }
348 if len(fn.Overloads) == 0 {
349 return fmt.Errorf("invalid function %q: missing overloads", fn.Name)
350 }
351 var errs []error
352 for _, o := range fn.Overloads {
353 if err := o.Validate(); err != nil {
354 errs = append(errs, fmt.Errorf("invalid function %q: %w", fn.Name, err))
355 }
356 }
357 return errors.Join(errs...)
358 }
359
360 // AsCELFunction converts the serializable form of the Function into CEL environment declaration.
361 func (fn *Function) AsCELFunction(tp types.Provider) (*decls.FunctionDecl, error) {
362 if err := fn.Validate(); err != nil {
363 return nil, err
364 }
365 opts := make([]decls.FunctionOpt, 0, len(fn.Overloads)+1)
366 for _, o := range fn.Overloads {
367 opt, err := o.AsFunctionOption(tp)
368 opts = append(opts, opt)
369 if err != nil {
370 return nil, fmt.Errorf("invalid function %q: %w", fn.Name, err)
371 }
372 }
373 if len(fn.Description) != 0 {
374 opts = append(opts, decls.FunctionDocs(fn.Description))
375 }
376 return decls.NewFunction(fn.Name, opts...)
377 }
378
379 // NewOverload returns a new serializable representation of a global overload.
380 func NewOverload(id string, args []*TypeDesc, ret *TypeDesc, examples ...string) *Overload {
381 return &Overload{ID: id, Args: args, Return: ret, Examples: examples}
382 }
383
384 // NewMemberOverload returns a new serializable representation of a member (receiver) overload.
385 func NewMemberOverload(id string, target *TypeDesc, args []*TypeDesc, ret *TypeDesc, examples ...string) *Overload {
386 return &Overload{ID: id, Target: target, Args: args, Return: ret, Examples: examples}
387 }
388
389 // Overload represents the serializable format of a function overload.
390 type Overload struct {
391 ID string `yaml:"id"`
392 Examples []string `yaml:"examples,omitempty"`
393 Target *TypeDesc `yaml:"target,omitempty"`
394 Args []*TypeDesc `yaml:"args,omitempty"`
395 Return *TypeDesc `yaml:"return,omitempty"`
396 }
397
398 // Validate validates the overload configuration is well-formed.
399 func (od *Overload) Validate() error {
400 if od == nil {
401 return errors.New("invalid overload: nil")
402 }
403 if od.ID == "" {
404 return errors.New("invalid overload: missing overload id")
405 }
406 var errs []error
407 if od.Target != nil {
408 if err := od.Target.Validate(); err != nil {
409 errs = append(errs, fmt.Errorf("invalid overload %q target: %w", od.ID, err))
410 }
411 }
412 for i, arg := range od.Args {
413 if err := arg.Validate(); err != nil {
414 errs = append(errs, fmt.Errorf("invalid overload %q arg[%d]: %w", od.ID, i, err))
415 }
416 }
417 if err := od.Return.Validate(); err != nil {
418 errs = append(errs, fmt.Errorf("invalid overload %q return: %w", od.ID, err))
419 }
420 return errors.Join(errs...)
421 }
422
423 // AsFunctionOption converts the serializable form of the Overload into a function declaration option.
424 func (od *Overload) AsFunctionOption(tp types.Provider) (decls.FunctionOpt, error) {
425 if err := od.Validate(); err != nil {
426 return nil, err
427 }
428 args := make([]*types.Type, len(od.Args))
429 var err error
430 var errs []error
431 for i, a := range od.Args {
432 args[i], err = a.AsCELType(tp)
433 if err != nil {
434 errs = append(errs, err)
435 }
436 }
437 result, err := od.Return.AsCELType(tp)
438 if err != nil {
439 errs = append(errs, err)
440 }
441 if od.Target != nil {
442 t, err := od.Target.AsCELType(tp)
443 if err != nil {
444 return nil, errors.Join(append(errs, err)...)
445 }
446 args = append([]*types.Type{t}, args...)
447 return decls.MemberOverload(od.ID, args, result), nil
448 }
449 if len(errs) != 0 {
450 return nil, errors.Join(errs...)
451 }
452 return decls.Overload(od.ID, args, result, decls.OverloadExamples(od.Examples...)), nil
453 }
454
455 // NewExtension creates a serializable Extension from a name and version string.
456 func NewExtension(name string, version uint32) *Extension {
457 versionString := "latest"
458 if version < math.MaxUint32 {
459 versionString = strconv.FormatUint(uint64(version), 10)
460 }
461 return &Extension{
462 Name: name,
463 Version: versionString,
464 }
465 }
466
467 // Extension represents a named and optionally versioned extension library configured in the environment.
468 type Extension struct {
469 // Name is either the LibraryName() or some short-hand simple identifier which is understood by the config-handler.
470 Name string `yaml:"name"`
471
472 // Version may either be an unsigned long value or the string 'latest'. If empty, the value is treated as '0'.
473 Version string `yaml:"version,omitempty"`
474 }
475
476 // Validate validates the extension configuration is well-formed.
477 func (e *Extension) Validate() error {
478 _, err := e.VersionNumber()
479 return err
480 }
481
482 // VersionNumber returns the parsed version string, or an error if the version cannot be parsed.
483 func (e *Extension) VersionNumber() (uint32, error) {
484 if e == nil {
485 return 0, fmt.Errorf("invalid extension: nil")
486 }
487 if e.Name == "" {
488 return 0, fmt.Errorf("invalid extension: missing name")
489 }
490 if e.Version == "latest" {
491 return math.MaxUint32, nil
492 }
493 if e.Version == "" {
494 return 0, nil
495 }
496 ver, err := strconv.ParseUint(e.Version, 10, 32)
497 if err != nil {
498 return 0, fmt.Errorf("invalid extension %q version: %w", e.Name, err)
499 }
500 return uint32(ver), nil
501 }
502
503 // NewLibrarySubset returns an empty library subsetting config which permits all library features.
504 func NewLibrarySubset() *LibrarySubset {
505 return &LibrarySubset{}
506 }
507
508 // LibrarySubset indicates a subset of the macros and function supported by a subsettable library.
509 type LibrarySubset struct {
510 // Disabled indicates whether the library has been disabled, typically only used for
511 // default-enabled libraries like stdlib.
512 Disabled bool `yaml:"disabled,omitempty"`
513
514 // DisableMacros disables macros for the given library.
515 DisableMacros bool `yaml:"disable_macros,omitempty"`
516
517 // IncludeMacros specifies a set of macro function names to include in the subset.
518 IncludeMacros []string `yaml:"include_macros,omitempty"`
519
520 // ExcludeMacros specifies a set of macro function names to exclude from the subset.
521 // Note: if IncludeMacros is non-empty, then ExcludeFunctions is ignored.
522 ExcludeMacros []string `yaml:"exclude_macros,omitempty"`
523
524 // IncludeFunctions specifies a set of functions to include in the subset.
525 //
526 // Note: the overloads specified in the subset need only specify their ID.
527 // Note: if IncludeFunctions is non-empty, then ExcludeFunctions is ignored.
528 IncludeFunctions []*Function `yaml:"include_functions,omitempty"`
529
530 // ExcludeFunctions specifies the set of functions to exclude from the subset.
531 //
532 // Note: the overloads specified in the subset need only specify their ID.
533 ExcludeFunctions []*Function `yaml:"exclude_functions,omitempty"`
534 }
535
536 // Validate validates the library configuration is well-formed.
537 //
538 // For example, setting both the IncludeMacros and ExcludeMacros together could be confusing
539 // and create a broken expectation, likewise for IncludeFunctions and ExcludeFunctions.
540 func (lib *LibrarySubset) Validate() error {
541 if lib == nil {
542 return nil
543 }
544 var errs []error
545 if len(lib.IncludeMacros) != 0 && len(lib.ExcludeMacros) != 0 {
546 errs = append(errs, errors.New("invalid subset: cannot both include and exclude macros"))
547 }
548 if len(lib.IncludeFunctions) != 0 && len(lib.ExcludeFunctions) != 0 {
549 errs = append(errs, errors.New("invalid subset: cannot both include and exclude functions"))
550 }
551 return errors.Join(errs...)
552 }
553
554 // SubsetFunction produces a function declaration which matches the supported subset, or nil
555 // if the function is not supported by the LibrarySubset.
556 //
557 // For IncludeFunctions, if the function does not specify a set of overloads to include, the
558 // whole function definition is included. If overloads are set, then a new function which
559 // includes only the specified overloads is produced.
560 //
561 // For ExcludeFunctions, if the function does not specify a set of overloads to exclude, the
562 // whole function definition is excluded. If overloads are set, then a new function which
563 // includes only the permitted overloads is produced.
564 func (lib *LibrarySubset) SubsetFunction(fn *decls.FunctionDecl) (*decls.FunctionDecl, bool) {
565 // When lib is null, it should indicate that all values are included in the subset.
566 if lib == nil {
567 return fn, true
568 }
569 if lib.Disabled {
570 return nil, false
571 }
572 if len(lib.IncludeFunctions) != 0 {
573 for _, include := range lib.IncludeFunctions {
574 if include.Name != fn.Name() {
575 continue
576 }
577 if len(include.Overloads) == 0 {
578 return fn, true
579 }
580 overloadIDs := make([]string, len(include.Overloads))
581 for i, o := range include.Overloads {
582 overloadIDs[i] = o.ID
583 }
584 return fn.Subset(decls.IncludeOverloads(overloadIDs...)), true
585 }
586 return nil, false
587 }
588 if len(lib.ExcludeFunctions) != 0 {
589 for _, exclude := range lib.ExcludeFunctions {
590 if exclude.Name != fn.Name() {
591 continue
592 }
593 if len(exclude.Overloads) == 0 {
594 return nil, false
595 }
596 overloadIDs := make([]string, len(exclude.Overloads))
597 for i, o := range exclude.Overloads {
598 overloadIDs[i] = o.ID
599 }
600 return fn.Subset(decls.ExcludeOverloads(overloadIDs...)), true
601 }
602 return fn, true
603 }
604 return fn, true
605 }
606
607 // SubsetMacro indicates whether the macro function should be included in the library subset.
608 func (lib *LibrarySubset) SubsetMacro(macroFunction string) bool {
609 // When lib is null, it should indicate that all values are included in the subset.
610 if lib == nil {
611 return true
612 }
613 if lib.Disabled || lib.DisableMacros {
614 return false
615 }
616 if len(lib.IncludeMacros) != 0 {
617 for _, name := range lib.IncludeMacros {
618 if name == macroFunction {
619 return true
620 }
621 }
622 return false
623 }
624 if len(lib.ExcludeMacros) != 0 {
625 for _, name := range lib.ExcludeMacros {
626 if name == macroFunction {
627 return false
628 }
629 }
630 return true
631 }
632 return true
633 }
634
635 // SetDisabled disables or enables the library.
636 func (lib *LibrarySubset) SetDisabled(value bool) *LibrarySubset {
637 lib.Disabled = value
638 return lib
639 }
640
641 // SetDisableMacros disables the macros for the library.
642 func (lib *LibrarySubset) SetDisableMacros(value bool) *LibrarySubset {
643 lib.DisableMacros = value
644 return lib
645 }
646
647 // AddIncludedMacros allow-lists one or more macros by function name.
648 //
649 // Note, this option will override any excluded macros.
650 func (lib *LibrarySubset) AddIncludedMacros(macros ...string) *LibrarySubset {
651 lib.IncludeMacros = append(lib.IncludeMacros, macros...)
652 return lib
653 }
654
655 // AddExcludedMacros deny-lists one or more macros by function name.
656 func (lib *LibrarySubset) AddExcludedMacros(macros ...string) *LibrarySubset {
657 lib.ExcludeMacros = append(lib.ExcludeMacros, macros...)
658 return lib
659 }
660
661 // AddIncludedFunctions allow-lists one or more functions from the subset.
662 //
663 // Note, this option will override any excluded functions.
664 func (lib *LibrarySubset) AddIncludedFunctions(funcs ...*Function) *LibrarySubset {
665 lib.IncludeFunctions = append(lib.IncludeFunctions, funcs...)
666 return lib
667 }
668
669 // AddExcludedFunctions deny-lists one or more functions from the subset.
670 func (lib *LibrarySubset) AddExcludedFunctions(funcs ...*Function) *LibrarySubset {
671 lib.ExcludeFunctions = append(lib.ExcludeFunctions, funcs...)
672 return lib
673 }
674
675 // NewValidator returns a named Validator instance.
676 func NewValidator(name string) *Validator {
677 return &Validator{Name: name}
678 }
679
680 // Validator represents a named validator with an optional map-based configuration object.
681 //
682 // Note: the map-keys must directly correspond to the internal representation of the original
683 // validator, and should only use primitive scalar types as values at this time.
684 type Validator struct {
685 Name string `yaml:"name"`
686 Config map[string]any `yaml:"config,omitempty"`
687 }
688
689 // Validate validates the configuration of the validator object.
690 func (v *Validator) Validate() error {
691 if v == nil {
692 return errors.New("invalid validator: nil")
693 }
694 if v.Name == "" {
695 return errors.New("invalid validator: missing name")
696 }
697 return nil
698 }
699
700 // SetConfig sets the set of map key-value pairs associated with this validator's configuration.
701 func (v *Validator) SetConfig(config map[string]any) *Validator {
702 v.Config = config
703 return v
704 }
705
706 // ConfigValue retrieves the value associated with the config key name, if one exists.
707 func (v *Validator) ConfigValue(name string) (any, bool) {
708 if v == nil {
709 return nil, false
710 }
711 value, found := v.Config[name]
712 return value, found
713 }
714
715 // NewFeature creates a new feature flag with a boolean enablement flag.
716 func NewFeature(name string, enabled bool) *Feature {
717 return &Feature{Name: name, Enabled: enabled}
718 }
719
720 // Feature represents a named boolean feature flag supported by CEL.
721 type Feature struct {
722 Name string `yaml:"name"`
723 Enabled bool `yaml:"enabled"`
724 }
725
726 // Validate validates whether the feature is well-configured.
727 func (feat *Feature) Validate() error {
728 if feat == nil {
729 return errors.New("invalid feature: nil")
730 }
731 if feat.Name == "" {
732 return errors.New("invalid feature: missing name")
733 }
734 return nil
735 }
736
737 // NewTypeDesc describes a simple or complex type with parameters.
738 func NewTypeDesc(typeName string, params ...*TypeDesc) *TypeDesc {
739 return &TypeDesc{TypeName: typeName, Params: params}
740 }
741
742 // NewTypeParam describe a type-param type.
743 func NewTypeParam(paramName string) *TypeDesc {
744 return &TypeDesc{TypeName: paramName, IsTypeParam: true}
745 }
746
747 // TypeDesc represents the serializable format of a CEL *types.Type value.
748 type TypeDesc struct {
749 TypeName string `yaml:"type_name"`
750 Params []*TypeDesc `yaml:"params,omitempty"`
751 IsTypeParam bool `yaml:"is_type_param,omitempty"`
752 }
753
754 // String implements the strings.Stringer interface method.
755 func (td *TypeDesc) String() string {
756 ps := make([]string, len(td.Params))
757 for i, p := range td.Params {
758 ps[i] = p.String()
759 }
760 typeName := td.TypeName
761 if len(ps) != 0 {
762 typeName = fmt.Sprintf("%s(%s)", typeName, strings.Join(ps, ","))
763 }
764 return typeName
765 }
766
767 // Validate validates the type configuration is well-formed.
768 func (td *TypeDesc) Validate() error {
769 if td == nil {
770 return errors.New("invalid type: nil")
771 }
772 if td.TypeName == "" {
773 return errors.New("invalid type: missing type name")
774 }
775 if td.IsTypeParam && len(td.Params) != 0 {
776 return errors.New("invalid type: param type cannot have parameters")
777 }
778 switch td.TypeName {
779 case "list":
780 if len(td.Params) != 1 {
781 return fmt.Errorf("invalid type: list expects 1 parameter, got %d", len(td.Params))
782 }
783 return td.Params[0].Validate()
784 case "map":
785 if len(td.Params) != 2 {
786 return fmt.Errorf("invalid type: map expects 2 parameters, got %d", len(td.Params))
787 }
788 if err := td.Params[0].Validate(); err != nil {
789 return err
790 }
791 if err := td.Params[1].Validate(); err != nil {
792 return err
793 }
794 case "optional_type":
795 if len(td.Params) != 1 {
796 return fmt.Errorf("invalid type: optional_type expects 1 parameter, got %d", len(td.Params))
797 }
798 return td.Params[0].Validate()
799 default:
800 }
801 return nil
802 }
803
804 // AsCELType converts the serializable object to a *types.Type value.
805 func (td *TypeDesc) AsCELType(tp types.Provider) (*types.Type, error) {
806 err := td.Validate()
807 if err != nil {
808 return nil, err
809 }
810 switch td.TypeName {
811 case "dyn":
812 return types.DynType, nil
813 case "map":
814 kt, err := td.Params[0].AsCELType(tp)
815 if err != nil {
816 return nil, err
817 }
818 vt, err := td.Params[1].AsCELType(tp)
819 if err != nil {
820 return nil, err
821 }
822 return types.NewMapType(kt, vt), nil
823 case "list":
824 et, err := td.Params[0].AsCELType(tp)
825 if err != nil {
826 return nil, err
827 }
828 return types.NewListType(et), nil
829 case "optional_type":
830 et, err := td.Params[0].AsCELType(tp)
831 if err != nil {
832 return nil, err
833 }
834 return types.NewOptionalType(et), nil
835 default:
836 if td.IsTypeParam {
837 return types.NewTypeParamType(td.TypeName), nil
838 }
839 if msgType, found := tp.FindStructType(td.TypeName); found {
840 // First parameter is the type name.
841 return msgType.Parameters()[0], nil
842 }
843 t, found := tp.FindIdent(td.TypeName)
844 if !found {
845 return nil, fmt.Errorf("undefined type name: %q", td.TypeName)
846 }
847 _, ok := t.(*types.Type)
848 if ok && len(td.Params) == 0 {
849 return t.(*types.Type), nil
850 }
851 params := make([]*types.Type, len(td.Params))
852 for i, p := range td.Params {
853 params[i], err = p.AsCELType(tp)
854 if err != nil {
855 return nil, err
856 }
857 }
858 return types.NewOpaqueType(td.TypeName, params...), nil
859 }
860 }
861
862 // SerializeTypeDesc converts a CEL native *types.Type to a serializable TypeDesc.
863 func SerializeTypeDesc(t *types.Type) *TypeDesc {
864 typeName := t.TypeName()
865 if t.Kind() == types.TypeParamKind {
866 return NewTypeParam(typeName)
867 }
868 if t != types.NullType && t.IsAssignableType(types.NullType) {
869 if wrapperTypeName, found := wrapperTypes[t.Kind()]; found {
870 return NewTypeDesc(wrapperTypeName)
871 }
872 }
873 var params []*TypeDesc
874 for _, p := range t.Parameters() {
875 params = append(params, SerializeTypeDesc(p))
876 }
877 return NewTypeDesc(typeName, params...)
878 }
879
880 var wrapperTypes = map[types.Kind]string{
881 types.BoolKind: "google.protobuf.BoolValue",
882 types.BytesKind: "google.protobuf.BytesValue",
883 types.DoubleKind: "google.protobuf.DoubleValue",
884 types.IntKind: "google.protobuf.Int64Value",
885 types.StringKind: "google.protobuf.StringValue",
886 types.UintKind: "google.protobuf.UInt64Value",
887 }