Debian Codegraph @

pkg/admission/plugin/policy/mutating/compilation_test.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 mutating
18
19 import (
20 "context"
21 "github.com/google/go-cmp/cmp"
22 "strings"
23 "testing"
24 "time"
25
26 "k8s.io/api/admissionregistration/v1alpha1"
27 appsv1 "k8s.io/api/apps/v1"
28 corev1 "k8s.io/api/core/v1"
29 "k8s.io/apimachinery/pkg/api/equality"
30 "k8s.io/apimachinery/pkg/api/meta"
31 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
32 "k8s.io/apimachinery/pkg/runtime"
33 "k8s.io/apimachinery/pkg/runtime/schema"
34 "k8s.io/apimachinery/pkg/util/wait"
35 "k8s.io/apiserver/pkg/admission"
36 "k8s.io/apiserver/pkg/admission/plugin/cel"
37 "k8s.io/apiserver/pkg/admission/plugin/policy/mutating/patch"
38 celconfig "k8s.io/apiserver/pkg/apis/cel"
39 "k8s.io/apiserver/pkg/authorization/authorizer"
40 "k8s.io/client-go/openapi/openapitest"
41 "k8s.io/utils/ptr"
42 )
43
44 // TestCompilation is an open-box test of mutatingEvaluator.compile
45 // However, the result is a set of CEL programs, manually invoke them to assert
46 // on the results.
47 func TestCompilation(t *testing.T) {
48 deploymentGVR := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"}
49 deploymentGVK := schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"}
50 testCases := []struct {
51 name string
52 policy *Policy
53 gvr schema.GroupVersionResource
54 object runtime.Object
55 oldObject runtime.Object
56 params runtime.Object
57 namespace *corev1.Namespace
58 expectedErr string
59 expectedResult runtime.Object
60 }{
61 {
62 name: "applyConfiguration then jsonPatch",
63 policy: mutations(policy("d1"), v1alpha1.Mutation{
64 PatchType: v1alpha1.PatchTypeApplyConfiguration,
65 ApplyConfiguration: &v1alpha1.ApplyConfiguration{
66 Expression: `Object{
67 spec: Object.spec{
68 replicas: object.spec.replicas + 100
69 }
70 }`,
71 },
72 },
73 v1alpha1.Mutation{
74 PatchType: v1alpha1.PatchTypeJSONPatch,
75 JSONPatch: &v1alpha1.JSONPatch{
76 Expression: `[
77 JSONPatch{op: "replace", path: "/spec/replicas", value: object.spec.replicas + 10}
78 ]`,
79 },
80 }),
81 gvr: deploymentGVR,
82 object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](1)}},
83 expectedResult: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](111)}},
84 },
85 {
86 name: "jsonPatch then applyConfiguration",
87 policy: mutations(policy("d1"),
88 v1alpha1.Mutation{
89 PatchType: v1alpha1.PatchTypeJSONPatch,
90 JSONPatch: &v1alpha1.JSONPatch{
91 Expression: `[
92 JSONPatch{op: "replace", path: "/spec/replicas", value: object.spec.replicas + 10}
93 ]`,
94 },
95 },
96 v1alpha1.Mutation{
97 PatchType: v1alpha1.PatchTypeApplyConfiguration,
98 ApplyConfiguration: &v1alpha1.ApplyConfiguration{
99 Expression: `Object{
100 spec: Object.spec{
101 replicas: object.spec.replicas + 100
102 }
103 }`,
104 },
105 }),
106 gvr: deploymentGVR,
107 object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](1)}},
108 expectedResult: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](111)}},
109 },
110 {
111 name: "jsonPatch with variable",
112 policy: jsonPatches(variables(policy("d1"), v1alpha1.Variable{Name: "desired", Expression: "10"}), v1alpha1.JSONPatch{
113 Expression: `[
114 JSONPatch{op: "replace", path: "/spec/replicas", value: variables.desired + 1},
115 ]`,
116 }),
117 gvr: deploymentGVR,
118 object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](1)}},
119 expectedResult: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](11)}},
120 },
121 {
122 name: "apply configuration with variable",
123 policy: applyConfigurations(variables(policy("d1"), v1alpha1.Variable{Name: "desired", Expression: "10"}),
124 `Object{
125 spec: Object.spec{
126 replicas: variables.desired + 1
127 }
128 }`),
129 gvr: deploymentGVR,
130 object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](1)}},
131 expectedResult: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](11)}},
132 },
133 {
134 name: "apply configuration with params",
135 policy: paramKind(applyConfigurations(policy("d1"),
136 `Object{
137 spec: Object.spec{
138 replicas: int(params.data['k1'])
139 }
140 }`), &v1alpha1.ParamKind{Kind: "ConfigMap", APIVersion: "v1"}),
141 params: &corev1.ConfigMap{Data: map[string]string{"k1": "100"}},
142 gvr: deploymentGVR,
143 object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](1)}},
144 expectedResult: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](100)}},
145 },
146 {
147 name: "jsonPatch with excessive cost",
148 policy: jsonPatches(variables(policy("d1"), v1alpha1.Variable{Name: "list", Expression: "[0,1,2,3,4,5,6,7,8,9]"}), v1alpha1.JSONPatch{
149 Expression: `[
150 JSONPatch{op: "replace", path: "/spec/replicas",
151 value: variables.list.all(x1, variables.list.all(x2, variables.list.all(x3, variables.list.all(x4, variables.list.all(x5, variables.list.all(x5, "0123456789" == "0123456789"))))))? 1 : 0
152 }
153 ]`,
154 }),
155 gvr: deploymentGVR,
156 object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](1)}},
157 expectedErr: "operation cancelled: actual cost limit exceeded",
158 },
159 {
160 name: "applyConfiguration with excessive cost",
161 policy: variables(applyConfigurations(policy("d1"),
162 `Object{
163 spec: Object.spec{
164 replicas: variables.list.all(x1, variables.list.all(x2, variables.list.all(x3, variables.list.all(x4, variables.list.all(x5, variables.list.all(x5, "0123456789" == "0123456789"))))))? 1 : 0
165 }
166 }`), v1alpha1.Variable{Name: "list", Expression: "[0,1,2,3,4,5,6,7,8,9]"}),
167 gvr: deploymentGVR,
168 object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](1)}},
169 expectedErr: "operation cancelled: actual cost limit exceeded",
170 },
171 {
172 name: "request variable",
173 policy: jsonPatches(policy("d1"), v1alpha1.JSONPatch{
174 Expression: `[
175 JSONPatch{op: "replace", path: "/spec/replicas",
176 value: request.kind.group == 'apps' && request.kind.version == 'v1' && request.kind.kind == 'Deployment' ? 10 : 0
177 }
178 ]`}),
179 gvr: deploymentGVR,
180 object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](1)}},
181 expectedResult: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](10)}},
182 },
183 {
184 name: "namespace request variable",
185 policy: jsonPatches(policy("d1"), v1alpha1.JSONPatch{
186 Expression: `[
187 JSONPatch{op: "replace", path: "/spec/replicas",
188 value: namespaceObject.metadata.name == 'ns1' ? 10 : 0
189 }
190 ]`}),
191 namespace: &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "ns1"}},
192 gvr: deploymentGVR,
193 object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](1)}},
194 expectedResult: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](10)}},
195 },
196 {
197 name: "authorizer check",
198 policy: jsonPatches(policy("d1"), v1alpha1.JSONPatch{
199 Expression: `[
200 JSONPatch{op: "replace", path: "/spec/replicas",
201 value: authorizer.group('').resource('endpoints').check('create').allowed() ? 10 : 0
202 }
203 ]`,
204 }),
205 gvr: deploymentGVR,
206 object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](1)}},
207 expectedResult: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Replicas: ptr.To[int32](10)}},
208 },
209 {
210 name: "object type has field access",
211 policy: jsonPatches(policy("d1"), v1alpha1.JSONPatch{
212 Expression: `[
213 JSONPatch{
214 op: "add", path: "/metadata/labels",
215 value: {
216 "value": Object{field: "fieldValue"}.field,
217 }
218 }
219 ]`,
220 }),
221 gvr: deploymentGVR,
222 object: &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{}}},
223 expectedResult: &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{
224 "value": "fieldValue",
225 }}},
226 },
227 {
228 name: "object type has field testing",
229 policy: jsonPatches(policy("d1"), v1alpha1.JSONPatch{
230 Expression: `[
231 JSONPatch{
232 op: "add", path: "/metadata/labels",
233 value: {
234 "field": string(has(Object{field: "fieldValue"}.field)),
235 "field-unset": string(has(Object{}.field)),
236 }
237 }
238 ]`,
239 }),
240 gvr: deploymentGVR,
241 object: &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{}}},
242 expectedResult: &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{
243 "field": "true",
244 "field-unset": "false",
245 }}},
246 },
247 {
248 name: "object type equality",
249 policy: jsonPatches(policy("d1"), v1alpha1.JSONPatch{
250 Expression: `[
251 JSONPatch{
252 op: "add", path: "/metadata/labels",
253 value: {
254 "empty": string(Object{} == Object{}),
255 "same": string(Object{field: "x"} == Object{field: "x"}),
256 "different": string(Object{field: "x"} == Object{field: "y"}),
257 }
258 }
259 ]`,
260 }),
261 gvr: deploymentGVR,
262 object: &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{}}},
263 expectedResult: &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{
264 "empty": "true",
265 "same": "true",
266 "different": "false",
267 }}},
268 },
269 {
270 // TODO: This test documents existing behavior that we should be fixed before
271 // MutatingAdmissionPolicy graduates to beta.
272 // It is possible to initialize invalid Object types because we do not yet perform
273 // a full compilation pass with the types fully bound. Before beta, we should
274 // recompile all expressions with fully bound types before evaluation and report
275 // errors if invalid Object types like this are initialized.
276 name: "object types are not fully type checked",
277 policy: jsonPatches(policy("d1"), v1alpha1.JSONPatch{
278 Expression: `[
279 JSONPatch{
280 op: "add", path: "/spec",
281 value: Object.invalid{replicas: 1}
282 }
283 ]`,
284 }),
285 gvr: deploymentGVR,
286 object: &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{}}},
287 expectedResult: &appsv1.Deployment{
288 ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{}},
289 Spec: appsv1.DeploymentSpec{
290 Replicas: ptr.To[int32](1),
291 },
292 },
293 },
294 }
295
296 scheme := runtime.NewScheme()
297 err := appsv1.AddToScheme(scheme)
298 if err != nil {
299 t.Fatal(err)
300 }
301
302 ctx, cancel := context.WithCancel(context.Background())
303 t.Cleanup(cancel)
304 tcManager := patch.NewTypeConverterManager(nil, openapitest.NewEmbeddedFileClient())
305 go tcManager.Run(ctx)
306
307 err = wait.PollUntilContextTimeout(ctx, 100*time.Millisecond, time.Second, true, func(context.Context) (done bool, err error) {
308 converter := tcManager.GetTypeConverter(deploymentGVK)
309 return converter != nil, nil
310 })
311 if err != nil {
312 t.Fatal(err)
313 }
314
315 for _, tc := range testCases {
316 t.Run(tc.name, func(t *testing.T) {
317 var gvk schema.GroupVersionKind
318 gvks, _, err := scheme.ObjectKinds(tc.object)
319 if err != nil {
320 t.Fatal(err)
321 }
322 if len(gvks) == 1 {
323 gvk = gvks[0]
324 } else {
325 t.Fatalf("Failed to find gvk for type: %T", tc.object)
326 }
327
328 policyEvaluator := compilePolicy(tc.policy)
329 if policyEvaluator.CompositionEnv != nil {
330 ctx = policyEvaluator.CompositionEnv.CreateContext(ctx)
331 }
332 obj := tc.object
333
334 typeAccessor, err := meta.TypeAccessor(obj)
335 if err != nil {
336 t.Fatal(err)
337 }
338 typeAccessor.SetKind(gvk.Kind)
339 typeAccessor.SetAPIVersion(gvk.GroupVersion().String())
340 typeConverter := tcManager.GetTypeConverter(gvk)
341
342 metaAccessor, err := meta.Accessor(obj)
343 if err != nil {
344 t.Fatal(err)
345 }
346
347 for _, patcher := range policyEvaluator.Mutators {
348 attrs := admission.NewAttributesRecord(obj, tc.oldObject, gvk,
349 metaAccessor.GetNamespace(), metaAccessor.GetName(), tc.gvr,
350 "", admission.Create, &metav1.CreateOptions{}, false, nil)
351 vAttrs := &admission.VersionedAttributes{
352 Attributes: attrs,
353 VersionedKind: gvk,
354 VersionedObject: obj,
355 VersionedOldObject: tc.oldObject,
356 }
357 r := patch.Request{
358 MatchedResource: tc.gvr,
359 VersionedAttributes: vAttrs,
360 ObjectInterfaces: admission.NewObjectInterfacesFromScheme(scheme),
361 OptionalVariables: cel.OptionalVariableBindings{VersionedParams: tc.params, Authorizer: fakeAuthorizer{}},
362 Namespace: tc.namespace,
363 TypeConverter: typeConverter,
364 }
365 obj, err = patcher.Patch(ctx, r, celconfig.RuntimeCELCostBudget)
366 if len(tc.expectedErr) > 0 {
367 if err == nil {
368 t.Fatalf("expected error: %s", tc.expectedErr)
369 } else {
370 if !strings.Contains(err.Error(), tc.expectedErr) {
371 t.Fatalf("expected error: %s, got: %s", tc.expectedErr, err.Error())
372 }
373 return
374 }
375 }
376 if err != nil && len(tc.expectedErr) == 0 {
377 t.Fatalf("unexpected error: %v", err)
378 }
379 }
380 got, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)
381 if err != nil {
382 t.Fatal(err)
383 }
384
385 wantTypeAccessor, err := meta.TypeAccessor(tc.expectedResult)
386 if err != nil {
387 t.Fatal(err)
388 }
389 wantTypeAccessor.SetKind(gvk.Kind)
390 wantTypeAccessor.SetAPIVersion(gvk.GroupVersion().String())
391
392 want, err := runtime.DefaultUnstructuredConverter.ToUnstructured(tc.expectedResult)
393 if err != nil {
394 t.Fatal(err)
395 }
396 if !equality.Semantic.DeepEqual(want, got) {
397 t.Errorf("unexpected result, got diff:\n%s\n", cmp.Diff(want, got))
398 }
399 })
400 }
401 }
402
403 func policy(name string) *v1alpha1.MutatingAdmissionPolicy {
404 return &v1alpha1.MutatingAdmissionPolicy{
405 ObjectMeta: metav1.ObjectMeta{
406 Name: name,
407 },
408 Spec: v1alpha1.MutatingAdmissionPolicySpec{},
409 }
410 }
411
412 func variables(policy *v1alpha1.MutatingAdmissionPolicy, variables ...v1alpha1.Variable) *v1alpha1.MutatingAdmissionPolicy {
413 policy.Spec.Variables = append(policy.Spec.Variables, variables...)
414 return policy
415 }
416
417 func jsonPatches(policy *v1alpha1.MutatingAdmissionPolicy, jsonPatches ...v1alpha1.JSONPatch) *v1alpha1.MutatingAdmissionPolicy {
418 for _, jsonPatch := range jsonPatches {
419 policy.Spec.Mutations = append(policy.Spec.Mutations, v1alpha1.Mutation{
420 JSONPatch: &jsonPatch,
421 PatchType: v1alpha1.PatchTypeJSONPatch,
422 })
423 }
424
425 return policy
426 }
427
428 func applyConfigurations(policy *v1alpha1.MutatingAdmissionPolicy, expressions ...string) *v1alpha1.MutatingAdmissionPolicy {
429 for _, expression := range expressions {
430 policy.Spec.Mutations = append(policy.Spec.Mutations, v1alpha1.Mutation{
431 ApplyConfiguration: &v1alpha1.ApplyConfiguration{Expression: expression},
432 PatchType: v1alpha1.PatchTypeApplyConfiguration,
433 })
434 }
435 return policy
436 }
437
438 func paramKind(policy *v1alpha1.MutatingAdmissionPolicy, paramKind *v1alpha1.ParamKind) *v1alpha1.MutatingAdmissionPolicy {
439 policy.Spec.ParamKind = paramKind
440 return policy
441 }
442
443 func mutations(policy *v1alpha1.MutatingAdmissionPolicy, mutations ...v1alpha1.Mutation) *v1alpha1.MutatingAdmissionPolicy {
444 policy.Spec.Mutations = append(policy.Spec.Mutations, mutations...)
445 return policy
446 }
447
448 func matchConstraints(policy *v1alpha1.MutatingAdmissionPolicy, matchConstraints *v1alpha1.MatchResources) *v1alpha1.MutatingAdmissionPolicy {
449 policy.Spec.MatchConstraints = matchConstraints
450 return policy
451 }
452
453 type fakeAuthorizer struct{}
454
455 func (f fakeAuthorizer) Authorize(ctx context.Context, a authorizer.Attributes) (authorizer.Decision, string, error) {
456 return authorizer.DecisionAllow, "", nil
457 }