|
| 1 | +// Copyright 2026 The kpt and Nephio Authors |
| 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 fnruntime |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "fmt" |
| 20 | + |
| 21 | + "github.com/google/cel-go/cel" |
| 22 | + "github.com/google/cel-go/common/types" |
| 23 | + "github.com/google/cel-go/ext" |
| 24 | + k8scellib "k8s.io/apiserver/pkg/cel/library" |
| 25 | + "sigs.k8s.io/kustomize/kyaml/yaml" |
| 26 | +) |
| 27 | + |
| 28 | +const checkFrequency = 100 |
| 29 | + |
| 30 | +// This gives about .1 seconds of CPU time for the evaluation to run |
| 31 | +const costLimit = 1000000 |
| 32 | + |
| 33 | +// CELEvaluator evaluates CEL expressions against KRM resources |
| 34 | +type CELEvaluator struct { |
| 35 | + env *cel.Env |
| 36 | + prg cel.Program // Pre-compiled program for the condition |
| 37 | +} |
| 38 | + |
| 39 | +// NewCELEvaluator creates a new CEL evaluator with the standard environment |
| 40 | +// for the given condition string. |
| 41 | +func NewCELEvaluator(condition string) (*CELEvaluator, error) { |
| 42 | + env, err := cel.NewEnv( |
| 43 | + cel.Variable("resources", cel.ListType(cel.DynType)), |
| 44 | + // Below is a list of Env settings that is a selection of https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apiserver/pkg/cel/environment/base.go |
| 45 | + // General rules are for maintaining this list. |
| 46 | + // 1. utility functions should be available. This allows for more compatibility with k8s's own CEL conditions |
| 47 | + // 2. AST validation is not needed as kpt will recompile CEL expressions every time, there is no cost-saving in exiting early |
| 48 | + // 3. Compile time optimisations do not make sense, as each CEL expression will be evaluated once before being discarded. |
| 49 | + // 3. Things that are helping with authorization in k8s are not needed, as they're returning either ResourceCheck or Decision types, which are not needed for kpt |
| 50 | + cel.HomogeneousAggregateLiterals(), |
| 51 | + cel.DefaultUTCTimeZone(true), |
| 52 | + k8scellib.URLs(), |
| 53 | + k8scellib.Regex(), |
| 54 | + k8scellib.Lists(), |
| 55 | + cel.CrossTypeNumericComparisons(true), |
| 56 | + cel.OptionalTypes(), |
| 57 | + k8scellib.Quantity(), |
| 58 | + ext.Strings(ext.StringsVersion(2)), |
| 59 | + ext.Sets(), |
| 60 | + k8scellib.IP(), |
| 61 | + k8scellib.CIDR(), |
| 62 | + k8scellib.Format(), |
| 63 | + ext.TwoVarComprehensions(), |
| 64 | + k8scellib.SemverLib(k8scellib.SemverVersion(1)), |
| 65 | + ext.Lists(ext.ListsVersion(3)), |
| 66 | + ) |
| 67 | + if err != nil { |
| 68 | + return nil, fmt.Errorf("failed to create CEL environment: %w", err) |
| 69 | + } |
| 70 | + |
| 71 | + evaluator := &CELEvaluator{ |
| 72 | + env: env, |
| 73 | + } |
| 74 | + |
| 75 | + // Pre-compile the condition if provided |
| 76 | + if condition != "" { |
| 77 | + ast, issues := env.Compile(condition) |
| 78 | + if issues != nil && issues.Err() != nil { |
| 79 | + return nil, fmt.Errorf("failed to compile CEL expression: %w", issues.Err()) |
| 80 | + } |
| 81 | + |
| 82 | + // Validate that the expression returns a boolean |
| 83 | + if ast.OutputType() != cel.BoolType { |
| 84 | + return nil, fmt.Errorf("CEL expression must return a boolean, got %v", ast.OutputType()) |
| 85 | + } |
| 86 | + |
| 87 | + // Create the program with a hard cost limit and cost tracking enabled |
| 88 | + prg, err := env.Program(ast, |
| 89 | + cel.CostLimit(costLimit), |
| 90 | + cel.InterruptCheckFrequency(checkFrequency), |
| 91 | + cel.CostTracking(&k8scellib.CostEstimator{}), |
| 92 | + ) |
| 93 | + if err != nil { |
| 94 | + return nil, fmt.Errorf("failed to create CEL program: %w", err) |
| 95 | + } |
| 96 | + |
| 97 | + evaluator.prg = prg |
| 98 | + } |
| 99 | + |
| 100 | + return evaluator, nil |
| 101 | +} |
| 102 | + |
| 103 | +// EvaluateCondition evaluates a CEL condition expression against a list of resources |
| 104 | +// Returns true if the condition is met, false otherwise |
| 105 | +// The program is pre-compiled, so this just evaluates it with the given resources |
| 106 | +func (e *CELEvaluator) EvaluateCondition(ctx context.Context, resources []*yaml.RNode) (bool, error) { |
| 107 | + if e.prg == nil { |
| 108 | + return true, nil |
| 109 | + } |
| 110 | + |
| 111 | + // Convert resources to a format suitable for CEL |
| 112 | + resourceList, err := e.resourcesToList(resources) |
| 113 | + if err != nil { |
| 114 | + return false, fmt.Errorf("failed to convert resources: %w", err) |
| 115 | + } |
| 116 | + |
| 117 | + // Evaluate the expression |
| 118 | + out, _, err := e.prg.ContextEval(ctx, map[string]interface{}{ |
| 119 | + "resources": resourceList, |
| 120 | + }) |
| 121 | + if err != nil { |
| 122 | + return false, fmt.Errorf("failed to evaluate CEL expression: %w", err) |
| 123 | + } |
| 124 | + |
| 125 | + // Extract the boolean result |
| 126 | + result, ok := out.(types.Bool) |
| 127 | + if !ok { |
| 128 | + return false, fmt.Errorf("CEL expression must return a boolean, got %T", out) |
| 129 | + } |
| 130 | + |
| 131 | + return bool(result), nil |
| 132 | +} |
| 133 | + |
| 134 | +// resourcesToList converts RNodes to a list of maps for CEL evaluation |
| 135 | +func (e *CELEvaluator) resourcesToList(resources []*yaml.RNode) ([]interface{}, error) { |
| 136 | + result := make([]interface{}, 0, len(resources)) |
| 137 | + |
| 138 | + for _, resource := range resources { |
| 139 | + // Convert each resource to a map |
| 140 | + resourceMap, err := e.resourceToMap(resource) |
| 141 | + if err != nil { |
| 142 | + return nil, err |
| 143 | + } |
| 144 | + result = append(result, resourceMap) |
| 145 | + } |
| 146 | + |
| 147 | + return result, nil |
| 148 | +} |
| 149 | + |
| 150 | +// resourceToMap converts a single RNode to a map for CEL evaluation |
| 151 | +// Converts yaml.Node directly to avoid serialization overhead |
| 152 | +func (e *CELEvaluator) resourceToMap(resource *yaml.RNode) (map[string]interface{}, error) { |
| 153 | + // Get the underlying yaml.Node |
| 154 | + node := resource.YNode() |
| 155 | + if node == nil { |
| 156 | + return nil, fmt.Errorf("resource has nil yaml.Node") |
| 157 | + } |
| 158 | + |
| 159 | + // Convert yaml.Node to map[string]interface{} directly |
| 160 | + var result map[string]interface{} |
| 161 | + if err := node.Decode(&result); err != nil { |
| 162 | + return nil, fmt.Errorf("failed to decode resource: %w", err) |
| 163 | + } |
| 164 | + |
| 165 | + return result, nil |
| 166 | +} |
0 commit comments