Debian Codegraph @

pkg/admission/plugin/policy/mutating/patch/json_patch.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 gojson "encoding/json"
22 "errors"
23 "fmt"
24 celgo "github.com/google/cel-go/cel"
25 "reflect"
26 "strconv"
27
28 "github.com/google/cel-go/common/types"
29 "github.com/google/cel-go/common/types/traits"
30 "google.golang.org/protobuf/types/known/structpb"
31 jsonpatch "gopkg.in/evanphx/json-patch.v4"
32
33 admissionv1 "k8s.io/api/admission/v1"
34 apierrors "k8s.io/apimachinery/pkg/api/errors"
35 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
36 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
37 "k8s.io/apimachinery/pkg/runtime"
38 "k8s.io/apimachinery/pkg/runtime/serializer/json"
39 plugincel "k8s.io/apiserver/pkg/admission/plugin/cel"
40 "k8s.io/apiserver/pkg/cel/mutation"
41 "k8s.io/apiserver/pkg/cel/mutation/dynamic"
42 pointer "k8s.io/utils/ptr"
43 )
44
45 // JSONPatchCondition contains the inputs needed to compile and evaluate a cel expression
46 // that returns a JSON patch value.
47 type JSONPatchCondition struct {
48 Expression string
49 }
50
51 var _ plugincel.ExpressionAccessor = &JSONPatchCondition{}
52
53 func (v *JSONPatchCondition) GetExpression() string {
54 return v.Expression
55 }
56
57 func (v *JSONPatchCondition) ReturnTypes() []*celgo.Type {
58 return []*celgo.Type{celgo.ListType(jsonPatchType)}
59 }
60
61 var jsonPatchType = types.NewObjectType("JSONPatch")
62
63 // NewJSONPatcher creates a patcher that performs a JSON Patch mutation.
64 func NewJSONPatcher(patchEvaluator plugincel.MutatingEvaluator) Patcher {
65 return &jsonPatcher{patchEvaluator}
66 }
67
68 type jsonPatcher struct {
69 PatchEvaluator plugincel.MutatingEvaluator
70 }
71
72 func (e *jsonPatcher) Patch(ctx context.Context, r Request, runtimeCELCostBudget int64) (runtime.Object, error) {
73 admissionRequest := plugincel.CreateAdmissionRequest(
74 r.VersionedAttributes.Attributes,
75 metav1.GroupVersionResource(r.MatchedResource),
76 metav1.GroupVersionKind(r.VersionedAttributes.VersionedKind))
77
78 compileErrors := e.PatchEvaluator.CompilationErrors()
79 if len(compileErrors) > 0 {
80 return nil, errors.Join(compileErrors...)
81 }
82 patchObj, _, err := e.evaluatePatchExpression(ctx, e.PatchEvaluator, runtimeCELCostBudget, r, admissionRequest)
83 if err != nil {
84 return nil, err
85 }
86 o := r.ObjectInterfaces
87 jsonSerializer := json.NewSerializerWithOptions(json.DefaultMetaFactory, o.GetObjectCreater(), o.GetObjectTyper(), json.SerializerOptions{Pretty: false, Strict: true})
88 objJS, err := runtime.Encode(jsonSerializer, r.VersionedAttributes.VersionedObject)
89 if err != nil {
90 return nil, fmt.Errorf("failed to create JSON patch: %w", err)
91 }
92 patchedJS, err := patchObj.Apply(objJS)
93 if err != nil {
94 if errors.Is(err, jsonpatch.ErrTestFailed) {
95 // If a json patch fails a test operation, the patch must not be applied
96 return r.VersionedAttributes.VersionedObject, nil
97 }
98 return nil, fmt.Errorf("JSON Patch: %w", err)
99 }
100
101 var newVersionedObject runtime.Object
102 if _, ok := r.VersionedAttributes.VersionedObject.(*unstructured.Unstructured); ok {
103 newVersionedObject = &unstructured.Unstructured{}
104 } else {
105 newVersionedObject, err = o.GetObjectCreater().New(r.VersionedAttributes.VersionedKind)
106 if err != nil {
107 return nil, apierrors.NewInternalError(err)
108 }
109 }
110
111 if newVersionedObject, _, err = jsonSerializer.Decode(patchedJS, nil, newVersionedObject); err != nil {
112 return nil, apierrors.NewInternalError(err)
113 }
114
115 return newVersionedObject, nil
116 }
117
118 func (e *jsonPatcher) evaluatePatchExpression(ctx context.Context, patchEvaluator plugincel.MutatingEvaluator, remainingBudget int64, r Request, admissionRequest *admissionv1.AdmissionRequest) (jsonpatch.Patch, int64, error) {
119 var err error
120 var eval plugincel.EvaluationResult
121 eval, remainingBudget, err = patchEvaluator.ForInput(ctx, r.VersionedAttributes, admissionRequest, r.OptionalVariables, r.Namespace, remainingBudget)
122 if err != nil {
123 return nil, -1, err
124 }
125 if eval.Error != nil {
126 return nil, -1, eval.Error
127 }
128 refVal := eval.EvalResult
129
130 // the return type can be any valid CEL value.
131 // Scalars, maps and lists are used to set the value when the path points to a field of that type.
132 // ObjectVal is used when the path points to a struct. A map like "{"field1": 1, "fieldX": bool}" is not
133 // possible in Kubernetes CEL because maps and lists may not have mixed types.
134
135 iter, ok := refVal.(traits.Lister)
136 if !ok {
137 // Should never happen since compiler checks return type.
138 return nil, -1, fmt.Errorf("type mismatch: JSONPatchType.expression should evaluate to array")
139 }
140 result := jsonpatch.Patch{}
141 for it := iter.Iterator(); it.HasNext() == types.True; {
142 v := it.Next()
143 patchObj, err := v.ConvertToNative(reflect.TypeOf(&mutation.JSONPatchVal{}))
144 if err != nil {
145 // Should never happen since return type is checked by compiler.
146 return nil, -1, fmt.Errorf("type mismatch: JSONPatchType.expression should evaluate to array of JSONPatch: %w", err)
147 }
148 op, ok := patchObj.(*mutation.JSONPatchVal)
149 if !ok {
150 // Should never happen since return type is checked by compiler.
151 return nil, -1, fmt.Errorf("type mismatch: JSONPatchType.expression should evaluate to array of JSONPatch, got element of %T", patchObj)
152 }
153
154 // Construct a JSON Patch from the evaluated CEL expression
155 resultOp := jsonpatch.Operation{}
156 resultOp["op"] = pointer.To(gojson.RawMessage(strconv.Quote(op.Op)))
157 resultOp["path"] = pointer.To(gojson.RawMessage(strconv.Quote(op.Path)))
158 if len(op.From) > 0 {
159 resultOp["from"] = pointer.To(gojson.RawMessage(strconv.Quote(op.From)))
160 }
161 if op.Val != nil {
162 if objVal, ok := op.Val.(*dynamic.ObjectVal); ok {
163 // TODO: Object initializers are insufficiently type checked.
164 // In the interim, we use this sanity check to detect type mismatches
165 // between field names and Object initializers. For example,
166 // "Object.spec{ selector: Object.spec.wrong{}}" is detected as a mismatch.
167 // Before beta, attaching full type information both to Object initializers and
168 // the "object" and "oldObject" variables is needed. This will allow CEL to
169 // perform comprehensive runtime type checking.
170 err := objVal.CheckTypeNamesMatchFieldPathNames()
171 if err != nil {
172 return nil, -1, fmt.Errorf("type mismatch: %w", err)
173 }
174 }
175 // CEL data literals representing arbitrary JSON values can be serialized to JSON for use in
176 // JSON Patch if first converted to pb.Value.
177 v, err := op.Val.ConvertToNative(reflect.TypeOf(&structpb.Value{}))
178 if err != nil {
179 return nil, -1, fmt.Errorf("JSONPath valueExpression evaluated to a type that could not marshal to JSON: %w", err)
180 }
181 b, err := gojson.Marshal(v)
182 if err != nil {
183 return nil, -1, fmt.Errorf("JSONPath valueExpression evaluated to a type that could not marshal to JSON: %w", err)
184 }
185 resultOp["value"] = pointer.To[gojson.RawMessage](b)
186 }
187
188 result = append(result, resultOp)
189 }
190
191 return result, remainingBudget, nil
192 }