Debian Codegraph @

pkg/admission/plugin/policy/mutating/plugin_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_test
18
19 import (
20 "context"
21 "testing"
22
23 "github.com/stretchr/testify/require"
24
25 "k8s.io/api/admissionregistration/v1alpha1"
26 corev1 "k8s.io/api/core/v1"
27 "k8s.io/apimachinery/pkg/api/meta"
28 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
29 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
30 "k8s.io/apimachinery/pkg/runtime"
31 "k8s.io/apimachinery/pkg/runtime/schema"
32 "k8s.io/apiserver/pkg/admission"
33 "k8s.io/apiserver/pkg/admission/plugin/policy/generic"
34 "k8s.io/apiserver/pkg/admission/plugin/policy/matching"
35 "k8s.io/apiserver/pkg/admission/plugin/policy/mutating"
36 "k8s.io/apiserver/pkg/admission/plugin/policy/mutating/patch"
37 "k8s.io/apiserver/pkg/authorization/authorizer"
38 "k8s.io/client-go/kubernetes"
39 "k8s.io/client-go/openapi/openapitest"
40 "k8s.io/utils/ptr"
41 )
42
43 func setupTest(
44 t *testing.T,
45 compiler func(*mutating.Policy) mutating.PolicyEvaluator,
46 ) *generic.PolicyTestContext[*mutating.Policy, *mutating.PolicyBinding, mutating.PolicyEvaluator] {
47
48 testContext, testCancel, err := generic.NewPolicyTestContext[*mutating.Policy, *mutating.PolicyBinding, mutating.PolicyEvaluator](
49 mutating.NewMutatingAdmissionPolicyAccessor,
50 mutating.NewMutatingAdmissionPolicyBindingAccessor,
51 compiler,
52 func(a authorizer.Authorizer, m *matching.Matcher, i kubernetes.Interface) generic.Dispatcher[mutating.PolicyHook] {
53 // Use embedded schemas rather than discovery schemas
54 return mutating.NewDispatcher(a, m, patch.NewTypeConverterManager(nil, openapitest.NewEmbeddedFileClient()))
55 },
56 nil,
57 []meta.RESTMapping{
58 {
59 Resource: schema.GroupVersionResource{
60 Group: "",
61 Version: "v1",
62 Resource: "pods",
63 },
64 GroupVersionKind: schema.GroupVersionKind{
65 Group: "",
66 Version: "v1",
67 Kind: "Pod",
68 },
69 Scope: meta.RESTScopeNamespace,
70 },
71 })
72 require.NoError(t, err)
73 t.Cleanup(testCancel)
74 require.NoError(t, testContext.Start())
75 return testContext
76 }
77
78 // Show that a compiler that always sets an annotation on the object works
79 func TestBasicPatch(t *testing.T) {
80 expectedAnnotations := map[string]string{"foo": "bar"}
81
82 // Treat all policies as setting foo annotation to bar
83 testContext := setupTest(t, func(p *mutating.Policy) mutating.PolicyEvaluator {
84 return mutating.PolicyEvaluator{Mutators: []patch.Patcher{annotationPatcher{expectedAnnotations}}}
85 })
86
87 // Set up a policy and binding that match, no params
88 require.NoError(t, testContext.UpdateAndWait(
89 &mutating.Policy{
90 ObjectMeta: metav1.ObjectMeta{Name: "policy"},
91 Spec: v1alpha1.MutatingAdmissionPolicySpec{
92 MatchConstraints: &v1alpha1.MatchResources{
93 MatchPolicy: ptr.To(v1alpha1.Equivalent),
94 NamespaceSelector: &metav1.LabelSelector{},
95 ObjectSelector: &metav1.LabelSelector{},
96 },
97 Mutations: []v1alpha1.Mutation{
98 {
99 ApplyConfiguration: &v1alpha1.ApplyConfiguration{
100 Expression: "ignored, but required",
101 },
102 PatchType: v1alpha1.PatchTypeApplyConfiguration,
103 },
104 },
105 },
106 },
107 &mutating.PolicyBinding{
108 ObjectMeta: metav1.ObjectMeta{Name: "binding"},
109 Spec: v1alpha1.MutatingAdmissionPolicyBindingSpec{
110 PolicyName: "policy",
111 },
112 },
113 ))
114
115 // Show that if we run an object through the policy, it gets the annotation
116 testObject := &corev1.ConfigMap{}
117 err := testContext.Dispatch(testObject, nil, admission.Create)
118 require.NoError(t, err)
119 require.Equal(t, expectedAnnotations, testObject.Annotations)
120 }
121
122 func TestJSONPatch(t *testing.T) {
123 patchObj := &unstructured.Unstructured{
124 Object: map[string]interface{}{
125 "apiVersion": "v1",
126 "kind": "ConfigMap",
127 "metadata": map[string]interface{}{
128 "annotations": map[string]interface{}{
129 "foo": "bar",
130 },
131 },
132 "data": map[string]interface{}{
133 "myfield": "myvalue",
134 },
135 },
136 }
137
138 testContext := setupTest(t, func(p *mutating.Policy) mutating.PolicyEvaluator {
139 return mutating.PolicyEvaluator{
140 Mutators: []patch.Patcher{smdPatcher{patch: patchObj}},
141 }
142 })
143
144 // Set up a policy and binding that match, no params
145 require.NoError(t, testContext.UpdateAndWait(
146 &mutating.Policy{
147 ObjectMeta: metav1.ObjectMeta{Name: "policy"},
148 Spec: v1alpha1.MutatingAdmissionPolicySpec{
149 MatchConstraints: &v1alpha1.MatchResources{
150 MatchPolicy: ptr.To(v1alpha1.Equivalent),
151 NamespaceSelector: &metav1.LabelSelector{},
152 ObjectSelector: &metav1.LabelSelector{},
153 },
154 Mutations: []v1alpha1.Mutation{
155 {
156 JSONPatch: &v1alpha1.JSONPatch{
157 Expression: "ignored, but required",
158 },
159 PatchType: v1alpha1.PatchTypeApplyConfiguration,
160 },
161 },
162 },
163 },
164 &mutating.PolicyBinding{
165 ObjectMeta: metav1.ObjectMeta{Name: "binding"},
166 Spec: v1alpha1.MutatingAdmissionPolicyBindingSpec{
167 PolicyName: "policy",
168 },
169 },
170 ))
171
172 // Show that if we run an object through the policy, it gets the annotation
173 testObject := &corev1.ConfigMap{}
174 err := testContext.Dispatch(testObject, nil, admission.Create)
175 require.NoError(t, err)
176 require.Equal(t, &corev1.ConfigMap{
177 ObjectMeta: metav1.ObjectMeta{
178 Annotations: map[string]string{"foo": "bar"},
179 },
180 Data: map[string]string{"myfield": "myvalue"},
181 }, testObject)
182 }
183
184 func TestSSAPatch(t *testing.T) {
185 patchObj := &unstructured.Unstructured{
186 Object: map[string]interface{}{
187 "apiVersion": "v1",
188 "kind": "ConfigMap",
189 "metadata": map[string]interface{}{
190 "annotations": map[string]interface{}{
191 "foo": "bar",
192 },
193 },
194 "data": map[string]interface{}{
195 "myfield": "myvalue",
196 },
197 },
198 }
199
200 testContext := setupTest(t, func(p *mutating.Policy) mutating.PolicyEvaluator {
201 return mutating.PolicyEvaluator{
202 Mutators: []patch.Patcher{smdPatcher{patch: patchObj}},
203 }
204 })
205
206 // Set up a policy and binding that match, no params
207 require.NoError(t, testContext.UpdateAndWait(
208 &mutating.Policy{
209 ObjectMeta: metav1.ObjectMeta{Name: "policy"},
210 Spec: v1alpha1.MutatingAdmissionPolicySpec{
211 MatchConstraints: &v1alpha1.MatchResources{
212 MatchPolicy: ptr.To(v1alpha1.Equivalent),
213 NamespaceSelector: &metav1.LabelSelector{},
214 ObjectSelector: &metav1.LabelSelector{},
215 },
216 Mutations: []v1alpha1.Mutation{
217 {
218 ApplyConfiguration: &v1alpha1.ApplyConfiguration{
219 Expression: "ignored, but required",
220 },
221 PatchType: v1alpha1.PatchTypeApplyConfiguration,
222 },
223 },
224 },
225 },
226 &mutating.PolicyBinding{
227 ObjectMeta: metav1.ObjectMeta{Name: "binding"},
228 Spec: v1alpha1.MutatingAdmissionPolicyBindingSpec{
229 PolicyName: "policy",
230 },
231 },
232 ))
233
234 // Show that if we run an object through the policy, it gets the annotation
235 testObject := &corev1.ConfigMap{}
236 err := testContext.Dispatch(testObject, nil, admission.Create)
237 require.NoError(t, err)
238 require.Equal(t, &corev1.ConfigMap{
239 ObjectMeta: metav1.ObjectMeta{
240 Annotations: map[string]string{"foo": "bar"},
241 },
242 Data: map[string]string{"myfield": "myvalue"},
243 }, testObject)
244 }
245
246 func TestSSAMapList(t *testing.T) {
247 patchObj := &unstructured.Unstructured{
248 Object: map[string]interface{}{
249 "apiVersion": "v1",
250 "kind": "Pod",
251 "metadata": map[string]interface{}{
252 "annotations": map[string]interface{}{
253 "foo": "bar",
254 },
255 },
256 "spec": map[string]interface{}{
257 "initContainers": []interface{}{
258 map[string]interface{}{
259 "name": "injected-init-container",
260 "image": "injected-image",
261 },
262 },
263 },
264 },
265 }
266
267 testContext := setupTest(t, func(p *mutating.Policy) mutating.PolicyEvaluator {
268 return mutating.PolicyEvaluator{
269 Mutators: []patch.Patcher{smdPatcher{patch: patchObj}},
270 }
271 })
272
273 // Set up a policy and binding that match, no params
274 require.NoError(t, testContext.UpdateAndWait(
275 &mutating.Policy{
276 ObjectMeta: metav1.ObjectMeta{Name: "policy"},
277 Spec: v1alpha1.MutatingAdmissionPolicySpec{
278 MatchConstraints: &v1alpha1.MatchResources{
279 MatchPolicy: ptr.To(v1alpha1.Equivalent),
280 NamespaceSelector: &metav1.LabelSelector{},
281 ObjectSelector: &metav1.LabelSelector{},
282 },
283 Mutations: []v1alpha1.Mutation{
284 {
285 ApplyConfiguration: &v1alpha1.ApplyConfiguration{
286 Expression: "ignored, but required",
287 },
288 PatchType: v1alpha1.PatchTypeApplyConfiguration,
289 },
290 },
291 },
292 },
293 &mutating.PolicyBinding{
294 ObjectMeta: metav1.ObjectMeta{Name: "binding"},
295 Spec: v1alpha1.MutatingAdmissionPolicyBindingSpec{
296 PolicyName: "policy",
297 },
298 },
299 ))
300
301 // Show that if we run an object through the policy, it gets the annotation
302 testObject := &corev1.Pod{
303 ObjectMeta: metav1.ObjectMeta{},
304 Spec: corev1.PodSpec{
305 InitContainers: []corev1.Container{
306 {
307 Name: "init-container",
308 Image: "image",
309 },
310 },
311 },
312 }
313 err := testContext.Dispatch(testObject, nil, admission.Create)
314 require.NoError(t, err)
315 require.Equal(t, &corev1.Pod{
316 ObjectMeta: metav1.ObjectMeta{
317 Annotations: map[string]string{"foo": "bar"},
318 },
319 Spec: corev1.PodSpec{
320 InitContainers: []corev1.Container{
321 {
322 Name: "init-container",
323 Image: "image",
324 },
325 {
326 Name: "injected-init-container",
327 Image: "injected-image",
328 },
329 },
330 },
331 }, testObject)
332 }
333
334 type annotationPatcher struct {
335 annotations map[string]string
336 }
337
338 func (ap annotationPatcher) Patch(ctx context.Context, request patch.Request, runtimeCELCostBudget int64) (runtime.Object, error) {
339 obj := request.VersionedAttributes.VersionedObject.DeepCopyObject()
340 accessor, err := meta.Accessor(obj)
341 if err != nil {
342 return nil, err
343 }
344 accessor.SetAnnotations(ap.annotations)
345 return obj, nil
346 }
347
348 type smdPatcher struct {
349 patch *unstructured.Unstructured
350 }
351
352 func (sp smdPatcher) Patch(ctx context.Context, request patch.Request, runtimeCELCostBudget int64) (runtime.Object, error) {
353 return patch.ApplyStructuredMergeDiff(request.TypeConverter, request.VersionedAttributes.VersionedObject, sp.patch)
354 }