Debian Codegraph @

pkg/admission/plugin/policy/mutating/patch/smd.go

raw
1 /*
2 Copyright 2024 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package patch
18
19 import (
20 "context"
21 "errors"
22 "fmt"
23 celgo "github.com/google/cel-go/cel"
24 celtypes "github.com/google/cel-go/common/types"
25 "strings"
26
27 "sigs.k8s.io/structured-merge-diff/v4/fieldpath"
28 "sigs.k8s.io/structured-merge-diff/v4/schema"
29 "sigs.k8s.io/structured-merge-diff/v4/typed"
30 "sigs.k8s.io/structured-merge-diff/v4/value"
31
32 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
33 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
34 "k8s.io/apimachinery/pkg/runtime"
35 "k8s.io/apimachinery/pkg/util/managedfields"
36 plugincel "k8s.io/apiserver/pkg/admission/plugin/cel"
37 "k8s.io/apiserver/pkg/cel/mutation/dynamic"
38 )
39
40 // ApplyConfigurationCondition contains the inputs needed to compile and evaluate a cel expression
41 // that returns an apply configuration
42 type ApplyConfigurationCondition struct {
43 Expression string
44 }
45
46 var _ plugincel.ExpressionAccessor = &ApplyConfigurationCondition{}
47
48 func (v *ApplyConfigurationCondition) GetExpression() string {
49 return v.Expression
50 }
51
52 func (v *ApplyConfigurationCondition) ReturnTypes() []*celgo.Type {
53 return []*celgo.Type{applyConfigObjectType}
54 }
55
56 var applyConfigObjectType = celtypes.NewObjectType("Object")
57
58 // NewApplyConfigurationPatcher creates a patcher that performs an applyConfiguration mutation.
59 func NewApplyConfigurationPatcher(expressionEvaluator plugincel.MutatingEvaluator) Patcher {
60 return &applyConfigPatcher{expressionEvaluator: expressionEvaluator}
61 }
62
63 type applyConfigPatcher struct {
64 expressionEvaluator plugincel.MutatingEvaluator
65 }
66
67 func (e *applyConfigPatcher) Patch(ctx context.Context, r Request, runtimeCELCostBudget int64) (runtime.Object, error) {
68 admissionRequest := plugincel.CreateAdmissionRequest(
69 r.VersionedAttributes.Attributes,
70 metav1.GroupVersionResource(r.MatchedResource),
71 metav1.GroupVersionKind(r.VersionedAttributes.VersionedKind))
72
73 compileErrors := e.expressionEvaluator.CompilationErrors()
74 if len(compileErrors) > 0 {
75 return nil, errors.Join(compileErrors...)
76 }
77 eval, _, err := e.expressionEvaluator.ForInput(ctx, r.VersionedAttributes, admissionRequest, r.OptionalVariables, r.Namespace, runtimeCELCostBudget)
78 if err != nil {
79 return nil, err
80 }
81 if eval.Error != nil {
82 return nil, eval.Error
83 }
84 v := eval.EvalResult
85
86 // The compiler ensures that the return type is an ObjectVal with type name of "Object".
87 objVal, ok := v.(*dynamic.ObjectVal)
88 if !ok {
89 // Should not happen since the compiler type checks the return type.
90 return nil, fmt.Errorf("unsupported return type from ApplyConfiguration expression: %v", v.Type())
91 }
92 // TODO: Object initializers are insufficiently type checked.
93 // In the interim, we use this sanity check to detect type mismatches
94 // between field names and Object initializers. For example,
95 // "Object.spec{ selector: Object.spec.wrong{}}" is detected as a mismatch.
96 // Before beta, attaching full type information both to Object initializers and
97 // the "object" and "oldObject" variables is needed. This will allow CEL to
98 // perform comprehensive runtime type checking.
99 err = objVal.CheckTypeNamesMatchFieldPathNames()
100 if err != nil {
101 return nil, fmt.Errorf("type mismatch: %w", err)
102 }
103
104 value, ok := objVal.Value().(map[string]any)
105 if !ok {
106 return nil, fmt.Errorf("invalid return type: %T", v)
107 }
108
109 patchObject := unstructured.Unstructured{Object: value}
110 patchObject.SetGroupVersionKind(r.VersionedAttributes.VersionedObject.GetObjectKind().GroupVersionKind())
111 patched, err := ApplyStructuredMergeDiff(r.TypeConverter, r.VersionedAttributes.VersionedObject, &patchObject)
112 if err != nil {
113 return nil, fmt.Errorf("error applying patch: %w", err)
114 }
115 return patched, nil
116 }
117
118 // ApplyStructuredMergeDiff applies a structured merge diff to an object and returns a copy of the object
119 // with the patch applied.
120 func ApplyStructuredMergeDiff(
121 typeConverter managedfields.TypeConverter,
122 originalObject runtime.Object,
123 patch *unstructured.Unstructured,
124 ) (runtime.Object, error) {
125 if patch.GroupVersionKind() != originalObject.GetObjectKind().GroupVersionKind() {
126 return nil, fmt.Errorf("patch (%v) and original object (%v) are not of the same gvk", patch.GroupVersionKind().String(), originalObject.GetObjectKind().GroupVersionKind().String())
127 } else if typeConverter == nil {
128 return nil, fmt.Errorf("type converter must not be nil")
129 }
130
131 patchObjTyped, err := typeConverter.ObjectToTyped(patch)
132 if err != nil {
133 return nil, fmt.Errorf("failed to convert patch object to typed object: %w", err)
134 }
135
136 err = validatePatch(patchObjTyped)
137 if err != nil {
138 return nil, fmt.Errorf("invalid ApplyConfiguration: %w", err)
139 }
140
141 liveObjTyped, err := typeConverter.ObjectToTyped(originalObject)
142 if err != nil {
143 return nil, fmt.Errorf("failed to convert original object to typed object: %w", err)
144 }
145
146 newObjTyped, err := liveObjTyped.Merge(patchObjTyped)
147 if err != nil {
148 return nil, fmt.Errorf("failed to merge patch: %w", err)
149 }
150
151 // Our mutating admission policy sets the fields but does not track ownership.
152 // Newly introduced fields in the patch won't be tracked by a field manager
153 // (so if the original object is updated again but the mutating policy is
154 // not active, the fields will be dropped).
155 //
156 // This necessarily means that changes to an object by a mutating policy
157 // are only preserved if the policy was active at the time of the change.
158 // (If the policy is not active, the changes may be dropped.)
159
160 newObj, err := typeConverter.TypedToObject(newObjTyped)
161 if err != nil {
162 return nil, fmt.Errorf("failed to convert typed object to object: %w", err)
163 }
164
165 return newObj, nil
166 }
167
168 // validatePatch searches an apply configuration for any arrays, maps or structs elements that are atomic and returns
169 // an error if any are found.
170 // This prevents accidental removal of fields that can occur when the user intends to modify some
171 // fields in an atomic type, not realizing that all fields not explicitly set in the new value
172 // of the atomic will be removed.
173 func validatePatch(v *typed.TypedValue) error {
174 atomics := findAtomics(nil, v.Schema(), v.TypeRef(), v.AsValue())
175 if len(atomics) > 0 {
176 return fmt.Errorf("may not mutate atomic arrays, maps or structs: %v", strings.Join(atomics, ", "))
177 }
178 return nil
179 }
180
181 // findAtomics returns field paths for any atomic arrays, maps or structs found when traversing the given value.
182 func findAtomics(path []fieldpath.PathElement, s *schema.Schema, tr schema.TypeRef, v value.Value) (atomics []string) {
183 if a, ok := s.Resolve(tr); ok { // Validation pass happens before this and checks that all schemas can be resolved
184 if v.IsMap() && a.Map != nil {
185 if a.Map.ElementRelationship == schema.Atomic {
186 atomics = append(atomics, pathString(path))
187 }
188 v.AsMap().Iterate(func(key string, val value.Value) bool {
189 pe := fieldpath.PathElement{FieldName: &key}
190 if sf, ok := a.Map.FindField(key); ok {
191 tr = sf.Type
192 atomics = append(atomics, findAtomics(append(path, pe), s, tr, val)...)
193 }
194 return true
195 })
196 }
197 if v.IsList() && a.List != nil {
198 if a.List.ElementRelationship == schema.Atomic {
199 atomics = append(atomics, pathString(path))
200 }
201 list := v.AsList()
202 for i := 0; i < list.Length(); i++ {
203 pe := fieldpath.PathElement{Index: &i}
204 atomics = append(atomics, findAtomics(append(path, pe), s, a.List.ElementType, list.At(i))...)
205 }
206 }
207 }
208 return atomics
209 }
210
211 func pathString(path []fieldpath.PathElement) string {
212 sb := strings.Builder{}
213 for _, p := range path {
214 sb.WriteString(p.String())
215 }
216 return sb.String()
217 }