Debian Codegraph @

pkg/admission/plugin/cel/condition_test.go

raw
1 /*
2 Copyright 2019 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 cel
18
19 import (
20 "context"
21 "errors"
22 "fmt"
23 "reflect"
24 "strings"
25 "testing"
26
27 celgo "github.com/google/cel-go/cel"
28 celtypes "github.com/google/cel-go/common/types"
29 "github.com/stretchr/testify/require"
30
31 corev1 "k8s.io/api/core/v1"
32 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
33 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
34 "k8s.io/apimachinery/pkg/fields"
35 "k8s.io/apimachinery/pkg/labels"
36 "k8s.io/apimachinery/pkg/runtime"
37 "k8s.io/apimachinery/pkg/runtime/schema"
38 "k8s.io/apimachinery/pkg/selection"
39 "k8s.io/apimachinery/pkg/util/version"
40 "k8s.io/apiserver/pkg/admission"
41 celconfig "k8s.io/apiserver/pkg/apis/cel"
42 "k8s.io/apiserver/pkg/authentication/user"
43 "k8s.io/apiserver/pkg/authorization/authorizer"
44 apiservercel "k8s.io/apiserver/pkg/cel"
45 "k8s.io/apiserver/pkg/cel/environment"
46 genericfeatures "k8s.io/apiserver/pkg/features"
47 utilfeature "k8s.io/apiserver/pkg/util/feature"
48 featuregatetesting "k8s.io/component-base/featuregate/testing"
49 pointer "k8s.io/utils/ptr"
50 )
51
52 type testCondition struct {
53 Expression string
54 }
55
56 func (tc *testCondition) GetExpression() string {
57 return tc.Expression
58 }
59
60 func (tc *testCondition) ReturnTypes() []*celgo.Type {
61 return []*celgo.Type{celgo.BoolType}
62 }
63
64 func TestCompile(t *testing.T) {
65 cases := []struct {
66 name string
67 validation []ExpressionAccessor
68 errorExpressions map[string]string
69 }{
70 {
71 name: "invalid syntax",
72 validation: []ExpressionAccessor{
73 &testCondition{
74 Expression: "1 < 'asdf'",
75 },
76 &testCondition{
77 Expression: "1 < 2",
78 },
79 },
80 errorExpressions: map[string]string{
81 "1 < 'asdf'": "found no matching overload for '_<_' applied to '(int, string)",
82 },
83 },
84 {
85 name: "valid syntax",
86 validation: []ExpressionAccessor{
87 &testCondition{
88 Expression: "1 < 2",
89 },
90 &testCondition{
91 Expression: "object.spec.string.matches('[0-9]+')",
92 },
93 &testCondition{
94 Expression: "request.kind.group == 'example.com' && request.kind.version == 'v1' && request.kind.kind == 'Fake'",
95 },
96 },
97 },
98 }
99
100 for _, tc := range cases {
101 t.Run(tc.name, func(t *testing.T) {
102 c := conditionCompiler{compiler: NewCompiler(environment.MustBaseEnvSet(environment.DefaultCompatibilityVersion(), true))}
103 e := c.CompileCondition(tc.validation, OptionalVariableDeclarations{HasParams: false, HasAuthorizer: false, StrictCost: true}, environment.NewExpressions)
104 if e == nil {
105 t.Fatalf("unexpected nil validator")
106 }
107 validations := tc.validation
108 CompilationResults := e.(*condition).compilationResults
109 require.Equal(t, len(validations), len(CompilationResults))
110
111 meets := make([]bool, len(validations))
112 for expr, expectErr := range tc.errorExpressions {
113 for i, result := range CompilationResults {
114 if validations[i].GetExpression() == expr {
115 if result.Error == nil {
116 t.Errorf("Expect expression '%s' to contain error '%v' but got no error", expr, expectErr)
117 } else if !strings.Contains(result.Error.Error(), expectErr) {
118 t.Errorf("Expected validations '%s' error to contain '%v' but got: %v", expr, expectErr, result.Error)
119 }
120 meets[i] = true
121 }
122 }
123 }
124 for i, meet := range meets {
125 if !meet && CompilationResults[i].Error != nil {
126 t.Errorf("Unexpected err '%v' for expression '%s'", CompilationResults[i].Error, validations[i].GetExpression())
127 }
128 }
129 })
130 }
131 }
132
133 func TestCondition(t *testing.T) {
134 simpleLabelSelector, err := labels.NewRequirement("apple", selection.Equals, []string{"banana"})
135 if err != nil {
136 panic(err)
137 }
138
139 configMapParams := &corev1.ConfigMap{
140 ObjectMeta: metav1.ObjectMeta{
141 Name: "foo",
142 },
143 Data: map[string]string{
144 "fakeString": "fake",
145 },
146 }
147 crdParams := &unstructured.Unstructured{
148 Object: map[string]interface{}{
149 "spec": map[string]interface{}{
150 "testSize": 10,
151 },
152 },
153 }
154 podObject := corev1.Pod{
155 ObjectMeta: metav1.ObjectMeta{
156 Name: "foo",
157 },
158 Spec: corev1.PodSpec{
159 NodeName: "testnode",
160 },
161 }
162
163 nsObject := &corev1.Namespace{
164 ObjectMeta: metav1.ObjectMeta{
165 Name: "test",
166 Labels: map[string]string{
167 "env": "test",
168 "foo": "demo",
169 },
170 Annotations: map[string]string{
171 "annotation1": "testAnnotation1",
172 },
173 Finalizers: []string{"f1"},
174 },
175 Spec: corev1.NamespaceSpec{
176 Finalizers: []corev1.FinalizerName{
177 corev1.FinalizerKubernetes,
178 },
179 },
180 Status: corev1.NamespaceStatus{
181 Phase: corev1.NamespaceActive,
182 },
183 }
184
185 v130 := version.MajorMinor(1, 30)
186 v131 := version.MajorMinor(1, 31)
187 v127 := version.MajorMinor(1, 27)
188
189 var nilUnstructured *unstructured.Unstructured
190 cases := []struct {
191 name string
192 attributes admission.Attributes
193 params runtime.Object
194 validations []ExpressionAccessor
195 results []EvaluationResult
196 hasParamKind bool
197 authorizer authorizer.Authorizer
198 testPerCallLimit uint64
199 namespaceObject *corev1.Namespace
200 strictCost bool
201 enableSelectors bool
202
203 compatibilityVersion *version.Version
204 envType environment.Type
205 }{
206 {
207 name: "valid syntax for object",
208 validations: []ExpressionAccessor{
209 &testCondition{
210 Expression: "has(object.subsets) && object.subsets.size() < 2",
211 },
212 },
213 attributes: newValidAttribute(nil, false),
214 results: []EvaluationResult{
215 {
216 EvalResult: celtypes.True,
217 },
218 },
219 hasParamKind: false,
220 },
221 {
222 name: "valid syntax for metadata",
223 validations: []ExpressionAccessor{
224 &testCondition{
225 Expression: "object.metadata.name == 'endpoints1'",
226 },
227 },
228 attributes: newValidAttribute(nil, false),
229 results: []EvaluationResult{
230 {
231 EvalResult: celtypes.True,
232 },
233 },
234 hasParamKind: false,
235 },
236 {
237 name: "valid syntax for oldObject",
238 validations: []ExpressionAccessor{
239 &testCondition{
240 Expression: "oldObject == null",
241 },
242 &testCondition{
243 Expression: "object != null",
244 },
245 },
246 attributes: newValidAttribute(nil, false),
247 results: []EvaluationResult{
248 {
249 EvalResult: celtypes.True,
250 },
251 {
252 EvalResult: celtypes.True,
253 },
254 },
255 hasParamKind: false,
256 },
257 {
258 name: "valid syntax for request",
259 validations: []ExpressionAccessor{
260 &testCondition{
261 Expression: "request.operation == 'CREATE'",
262 },
263 },
264 attributes: newValidAttribute(nil, false),
265 results: []EvaluationResult{
266 {
267 EvalResult: celtypes.True,
268 },
269 },
270 hasParamKind: false,
271 },
272 {
273 name: "valid syntax for configMap",
274 validations: []ExpressionAccessor{
275 &testCondition{
276 Expression: "request.namespace != params.data.fakeString",
277 },
278 },
279 attributes: newValidAttribute(nil, false),
280 results: []EvaluationResult{
281 {
282 EvalResult: celtypes.True,
283 },
284 },
285 hasParamKind: true,
286 params: configMapParams,
287 },
288 {
289 name: "test failure",
290 validations: []ExpressionAccessor{
291 &testCondition{
292 Expression: "object.subsets.size() > 2",
293 },
294 },
295 attributes: newValidAttribute(nil, false),
296 results: []EvaluationResult{
297 {
298 EvalResult: celtypes.False,
299 },
300 },
301 hasParamKind: true,
302 params: &corev1.ConfigMap{
303 ObjectMeta: metav1.ObjectMeta{
304 Name: "foo",
305 },
306 Data: map[string]string{
307 "fakeString": "fake",
308 },
309 },
310 },
311 {
312 name: "test failure with multiple validations",
313 validations: []ExpressionAccessor{
314 &testCondition{
315 Expression: "has(object.subsets)",
316 },
317 &testCondition{
318 Expression: "object.subsets.size() > 2",
319 },
320 },
321 attributes: newValidAttribute(nil, false),
322 results: []EvaluationResult{
323 {
324 EvalResult: celtypes.True,
325 },
326 {
327 EvalResult: celtypes.False,
328 },
329 },
330 hasParamKind: true,
331 params: configMapParams,
332 },
333 {
334 name: "test failure policy with multiple failed validations",
335 validations: []ExpressionAccessor{
336 &testCondition{
337 Expression: "oldObject != null",
338 },
339 &testCondition{
340 Expression: "object.subsets.size() > 2",
341 },
342 },
343 attributes: newValidAttribute(nil, false),
344 results: []EvaluationResult{
345 {
346 EvalResult: celtypes.False,
347 },
348 {
349 EvalResult: celtypes.False,
350 },
351 },
352 hasParamKind: true,
353 params: configMapParams,
354 },
355 {
356 name: "test Object null in delete",
357 validations: []ExpressionAccessor{
358 &testCondition{
359 Expression: "oldObject != null",
360 },
361 &testCondition{
362 Expression: "object == null",
363 },
364 },
365 attributes: newValidAttribute(nil, true),
366 results: []EvaluationResult{
367 {
368 EvalResult: celtypes.True,
369 },
370 {
371 EvalResult: celtypes.True,
372 },
373 },
374 hasParamKind: true,
375 params: configMapParams,
376 },
377 {
378 name: "test runtime error",
379 validations: []ExpressionAccessor{
380 &testCondition{
381 Expression: "oldObject.x == 100",
382 },
383 },
384 attributes: newValidAttribute(nil, true),
385 results: []EvaluationResult{
386 {
387 Error: errors.New("expression 'oldObject.x == 100' resulted in error"),
388 },
389 },
390 hasParamKind: true,
391 params: configMapParams,
392 },
393 {
394 name: "test against crd param",
395 validations: []ExpressionAccessor{
396 &testCondition{
397 Expression: "object.subsets.size() < params.spec.testSize",
398 },
399 },
400 attributes: newValidAttribute(nil, false),
401 results: []EvaluationResult{
402 {
403 EvalResult: celtypes.True,
404 },
405 },
406 hasParamKind: true,
407 params: crdParams,
408 },
409 {
410 name: "test compile failure",
411 validations: []ExpressionAccessor{
412 &testCondition{
413 Expression: "fail to compile test",
414 },
415 &testCondition{
416 Expression: "object.subsets.size() > params.spec.testSize",
417 },
418 },
419 attributes: newValidAttribute(nil, false),
420 results: []EvaluationResult{
421 {
422 Error: errors.New("compilation error"),
423 },
424 {
425 EvalResult: celtypes.False,
426 },
427 },
428 hasParamKind: true,
429 params: crdParams,
430 },
431 {
432 name: "test pod",
433 validations: []ExpressionAccessor{
434 &testCondition{
435 Expression: "object.spec.nodeName == 'testnode'",
436 },
437 },
438 attributes: newValidAttribute(&podObject, false),
439 results: []EvaluationResult{
440 {
441 EvalResult: celtypes.True,
442 },
443 },
444 hasParamKind: true,
445 params: crdParams,
446 },
447 {
448 name: "test deny paramKind without paramRef",
449 validations: []ExpressionAccessor{
450 &testCondition{
451 Expression: "params != null",
452 },
453 },
454 attributes: newValidAttribute(&podObject, false),
455 results: []EvaluationResult{
456 {
457 EvalResult: celtypes.False,
458 },
459 },
460 hasParamKind: true,
461 },
462 {
463 name: "test allow paramKind without paramRef",
464 validations: []ExpressionAccessor{
465 &testCondition{
466 Expression: "params == null",
467 },
468 },
469 attributes: newValidAttribute(&podObject, false),
470 results: []EvaluationResult{
471 {
472 EvalResult: celtypes.True,
473 },
474 },
475 hasParamKind: true,
476 params: runtime.Object(nilUnstructured),
477 },
478 {
479 name: "test authorizer allow resource check",
480 validations: []ExpressionAccessor{
481 &testCondition{
482 Expression: "authorizer.group('').resource('endpoints').check('create').allowed()",
483 },
484 &testCondition{
485 Expression: "authorizer.group('').resource('endpoints').check('create').errored()",
486 },
487 },
488 attributes: newValidAttribute(&podObject, false),
489 results: []EvaluationResult{
490 {
491 EvalResult: celtypes.True,
492 },
493 {
494 EvalResult: celtypes.False,
495 },
496 },
497 authorizer: newAuthzAllowMatch(authorizer.AttributesRecord{
498 ResourceRequest: true,
499 Resource: "endpoints",
500 Verb: "create",
501 APIVersion: "*",
502 }),
503 },
504 {
505 name: "test authorizer error using fieldSelector with 1.30 compatibility",
506 validations: []ExpressionAccessor{
507 &testCondition{
508 Expression: "authorizer.group('apps').resource('deployments').fieldSelector('foo=bar').labelSelector('apple=banana').subresource('status').namespace('test').name('backend').check('create').allowed()",
509 },
510 },
511 attributes: newValidAttribute(&podObject, false),
512 results: []EvaluationResult{
513 {
514 Error: fmt.Errorf("fieldSelector"),
515 },
516 },
517 authorizer: newAuthzAllowMatch(authorizer.AttributesRecord{
518 ResourceRequest: true,
519 APIGroup: "apps",
520 Resource: "deployments",
521 Subresource: "status",
522 Namespace: "test",
523 Name: "backend",
524 Verb: "create",
525 APIVersion: "*",
526 FieldSelectorRequirements: fields.Requirements{
527 {Operator: "=", Field: "foo", Value: "bar"},
528 },
529 LabelSelectorRequirements: labels.Requirements{
530 *simpleLabelSelector,
531 },
532 }),
533 enableSelectors: false,
534 compatibilityVersion: v130,
535 },
536 {
537 name: "test authorizer allow resource check with all fields",
538 validations: []ExpressionAccessor{
539 &testCondition{
540 Expression: "authorizer.group('apps').resource('deployments').fieldSelector('foo=bar').labelSelector('apple=banana').subresource('status').namespace('test').name('backend').check('create').allowed()",
541 },
542 },
543 attributes: newValidAttribute(&podObject, false),
544 results: []EvaluationResult{
545 {
546 EvalResult: celtypes.True,
547 },
548 },
549 authorizer: newAuthzAllowMatch(authorizer.AttributesRecord{
550 ResourceRequest: true,
551 APIGroup: "apps",
552 Resource: "deployments",
553 Subresource: "status",
554 Namespace: "test",
555 Name: "backend",
556 Verb: "create",
557 APIVersion: "*",
558 FieldSelectorRequirements: fields.Requirements{
559 {Operator: "=", Field: "foo", Value: "bar"},
560 },
561 LabelSelectorRequirements: labels.Requirements{
562 *simpleLabelSelector,
563 },
564 }),
565 enableSelectors: true,
566 compatibilityVersion: v131,
567 },
568 {
569 name: "test authorizer allow resource check with parse failures",
570 validations: []ExpressionAccessor{
571 &testCondition{
572 Expression: "authorizer.group('apps').resource('deployments').fieldSelector('foo badoperator bar').labelSelector('apple badoperator banana').subresource('status').namespace('test').name('backend').check('create').allowed()",
573 },
574 },
575 attributes: newValidAttribute(&podObject, false),
576 results: []EvaluationResult{
577 {
578 EvalResult: celtypes.True,
579 },
580 },
581 authorizer: newAuthzAllowMatch(authorizer.AttributesRecord{
582 ResourceRequest: true,
583 APIGroup: "apps",
584 Resource: "deployments",
585 Subresource: "status",
586 Namespace: "test",
587 Name: "backend",
588 Verb: "create",
589 APIVersion: "*",
590 FieldSelectorParsingErr: errors.New("invalid selector: 'foo badoperator bar'; can't understand 'foo badoperator bar'"),
591 LabelSelectorParsingErr: errors.New("unable to parse requirement: found 'badoperator', expected: in, notin, =, ==, !=, gt, lt"),
592 }),
593 enableSelectors: true,
594 compatibilityVersion: v131,
595 },
596 {
597 name: "test authorizer allow resource check with all fields, without gate",
598 validations: []ExpressionAccessor{
599 &testCondition{
600 Expression: "authorizer.group('apps').resource('deployments').fieldSelector('foo=bar').labelSelector('apple=banana').subresource('status').namespace('test').name('backend').check('create').allowed()",
601 },
602 },
603 attributes: newValidAttribute(&podObject, false),
604 results: []EvaluationResult{
605 {
606 Error: fmt.Errorf("fieldSelector"),
607 },
608 },
609 authorizer: newAuthzAllowMatch(authorizer.AttributesRecord{
610 ResourceRequest: true,
611 APIGroup: "apps",
612 Resource: "deployments",
613 Subresource: "status",
614 Namespace: "test",
615 Name: "backend",
616 Verb: "create",
617 APIVersion: "*",
618 }),
619 enableSelectors: false,
620 compatibilityVersion: v131,
621 },
622 {
623 name: "test authorizer not allowed resource check one incorrect field",
624 validations: []ExpressionAccessor{
625 &testCondition{
626
627 Expression: "authorizer.group('apps').resource('deployments').subresource('status').namespace('test').name('backend').check('create').allowed()",
628 },
629 },
630 attributes: newValidAttribute(&podObject, false),
631 results: []EvaluationResult{
632 {
633 EvalResult: celtypes.False,
634 },
635 },
636 authorizer: newAuthzAllowMatch(authorizer.AttributesRecord{
637 ResourceRequest: true,
638 APIGroup: "apps",
639 Resource: "deployments-xxxx",
640 Subresource: "status",
641 Namespace: "test",
642 Name: "backend",
643 Verb: "create",
644 APIVersion: "*",
645 }),
646 },
647 {
648 name: "test authorizer reason",
649 validations: []ExpressionAccessor{
650 &testCondition{
651 Expression: "authorizer.group('').resource('endpoints').check('create').reason() == 'fake reason'",
652 },
653 },
654 attributes: newValidAttribute(&podObject, false),
655 results: []EvaluationResult{
656 {
657 EvalResult: celtypes.True,
658 },
659 },
660 authorizer: denyAll,
661 },
662 {
663 name: "test authorizer error",
664 validations: []ExpressionAccessor{
665 &testCondition{
666 Expression: "authorizer.group('').resource('endpoints').check('create').errored()",
667 },
668 &testCondition{
669 Expression: "authorizer.group('').resource('endpoints').check('create').error() == 'fake authz error'",
670 },
671 &testCondition{
672 Expression: "authorizer.group('').resource('endpoints').check('create').allowed()",
673 },
674 },
675 attributes: newValidAttribute(&podObject, false),
676 results: []EvaluationResult{
677 {
678 EvalResult: celtypes.True,
679 },
680 {
681 EvalResult: celtypes.True,
682 },
683 {
684 EvalResult: celtypes.False,
685 },
686 },
687 authorizer: errorAll,
688 },
689 {
690 name: "test authorizer allow path check",
691 validations: []ExpressionAccessor{
692 &testCondition{
693 Expression: "authorizer.path('/healthz').check('get').allowed()",
694 },
695 },
696 attributes: newValidAttribute(&podObject, false),
697 results: []EvaluationResult{
698 {
699 EvalResult: celtypes.True,
700 },
701 },
702 authorizer: newAuthzAllowMatch(authorizer.AttributesRecord{
703 Path: "/healthz",
704 Verb: "get",
705 }),
706 },
707 {
708 name: "test authorizer decision is denied path check",
709 validations: []ExpressionAccessor{
710 &testCondition{
711 Expression: "authorizer.path('/healthz').check('get').allowed() == false",
712 },
713 },
714 attributes: newValidAttribute(&podObject, false),
715 results: []EvaluationResult{
716 {
717 EvalResult: celtypes.True,
718 },
719 },
720 authorizer: denyAll,
721 },
722 {
723 name: "test request resource authorizer allow check",
724 validations: []ExpressionAccessor{
725 &testCondition{
726 Expression: "authorizer.requestResource.check('custom-verb').allowed()",
727 },
728 },
729 attributes: endpointCreateAttributes(),
730 results: []EvaluationResult{
731 {
732 EvalResult: celtypes.True,
733 },
734 },
735 authorizer: newAuthzAllowMatch(authorizer.AttributesRecord{
736 ResourceRequest: true,
737 APIGroup: "",
738 Resource: "endpoints",
739 Subresource: "",
740 Namespace: "default",
741 Name: "endpoints1",
742 Verb: "custom-verb",
743 APIVersion: "*",
744 }),
745 },
746 {
747 name: "test subresource request resource authorizer allow check",
748 validations: []ExpressionAccessor{
749 &testCondition{
750 Expression: "authorizer.requestResource.check('custom-verb').allowed()",
751 },
752 },
753 attributes: endpointStatusUpdateAttributes(),
754 results: []EvaluationResult{
755 {
756 EvalResult: celtypes.True,
757 },
758 },
759 authorizer: newAuthzAllowMatch(authorizer.AttributesRecord{
760 ResourceRequest: true,
761 APIGroup: "",
762 Resource: "endpoints",
763 Subresource: "status",
764 Namespace: "default",
765 Name: "endpoints1",
766 Verb: "custom-verb",
767 APIVersion: "*",
768 }),
769 },
770 {
771 name: "test serviceAccount authorizer allow check",
772 validations: []ExpressionAccessor{
773 &testCondition{
774 Expression: "authorizer.serviceAccount('default', 'test-serviceaccount').group('').resource('endpoints').namespace('default').name('endpoints1').check('custom-verb').allowed()",
775 },
776 },
777 attributes: endpointCreateAttributes(),
778 results: []EvaluationResult{
779 {
780 EvalResult: celtypes.True,
781 },
782 },
783 authorizer: newAuthzAllowMatch(authorizer.AttributesRecord{
784 User: &user.DefaultInfo{
785 Name: "system:serviceaccount:default:test-serviceaccount",
786 Groups: []string{"system:serviceaccounts", "system:serviceaccounts:default"},
787 },
788 ResourceRequest: true,
789 APIGroup: "",
790 Resource: "endpoints",
791 Namespace: "default",
792 Name: "endpoints1",
793 Verb: "custom-verb",
794 APIVersion: "*",
795 }),
796 },
797 {
798 name: "test perCallLimit exceed",
799 validations: []ExpressionAccessor{
800 &testCondition{
801 Expression: "object.subsets.size() < params.spec.testSize",
802 },
803 },
804 attributes: newValidAttribute(nil, false),
805 results: []EvaluationResult{
806 {
807 Error: errors.New(fmt.Sprintf("operation cancelled: actual cost limit exceeded")),
808 },
809 },
810 hasParamKind: true,
811 params: crdParams,
812 testPerCallLimit: 1,
813 },
814 {
815 name: "test namespaceObject",
816 validations: []ExpressionAccessor{
817 &testCondition{
818 Expression: "namespaceObject.metadata.name == 'test'",
819 },
820 &testCondition{
821 Expression: "'env' in namespaceObject.metadata.labels && namespaceObject.metadata.labels.env == 'test'",
822 },
823 &testCondition{
824 Expression: "('fake' in namespaceObject.metadata.labels) && namespaceObject.metadata.labels.fake == 'test'",
825 },
826 &testCondition{
827 Expression: "namespaceObject.spec.finalizers[0] == 'kubernetes'",
828 },
829 &testCondition{
830 Expression: "namespaceObject.status.phase == 'Active'",
831 },
832 &testCondition{
833 Expression: "size(namespaceObject.metadata.managedFields) == 1",
834 },
835 &testCondition{
836 Expression: "size(namespaceObject.metadata.ownerReferences) == 1",
837 },
838 &testCondition{
839 Expression: "'env' in namespaceObject.metadata.annotations",
840 },
841 },
842 attributes: newValidAttribute(&podObject, false),
843 results: []EvaluationResult{
844 {
845 EvalResult: celtypes.True,
846 },
847 {
848 EvalResult: celtypes.True,
849 },
850 {
851 EvalResult: celtypes.False,
852 },
853 {
854 EvalResult: celtypes.True,
855 },
856 {
857 EvalResult: celtypes.True,
858 },
859 {
860 Error: errors.New("undefined field 'managedFields'"),
861 },
862 {
863 Error: errors.New("undefined field 'ownerReferences'"),
864 },
865 {
866 EvalResult: celtypes.False,
867 },
868 },
869 hasParamKind: false,
870 namespaceObject: nsObject,
871 },
872 {
873 name: "cel lib not recognized in version earlier than introduced version",
874 validations: []ExpressionAccessor{
875 &testCondition{
876 Expression: "isQuantity(\"20M\")",
877 },
878 },
879 attributes: newValidAttribute(&podObject, false),
880 results: []EvaluationResult{
881 {
882 Error: fmt.Errorf("isQuantity"),
883 },
884 },
885 compatibilityVersion: v127,
886 },
887 {
888 name: "cel lib recognized in version later than introduced version",
889 validations: []ExpressionAccessor{
890 &testCondition{
891 Expression: "isQuantity(\"20M\")",
892 },
893 },
894 results: []EvaluationResult{
895 {
896 EvalResult: celtypes.True,
897 },
898 },
899 attributes: newValidAttribute(&podObject, false),
900 compatibilityVersion: v130,
901 },
902 {
903 name: "cel lib always recognized in stored expression",
904 validations: []ExpressionAccessor{
905 &testCondition{
906 Expression: "isQuantity(\"20M\")",
907 },
908 },
909 attributes: newValidAttribute(&podObject, false),
910 results: []EvaluationResult{
911 {
912 EvalResult: celtypes.True,
913 },
914 },
915 envType: environment.StoredExpressions,
916 compatibilityVersion: version.MajorMinor(1, 2),
917 },
918 }
919
920 for _, tc := range cases {
921 t.Run(tc.name, func(t *testing.T) {
922 environment.DisableBaseEnvSetCachingForTests()
923 featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, genericfeatures.AuthorizeWithSelectors, tc.enableSelectors)
924
925 if tc.testPerCallLimit == 0 {
926 tc.testPerCallLimit = celconfig.PerCallLimit
927 }
928 compatibilityVersion := tc.compatibilityVersion
929 if compatibilityVersion == nil {
930 compatibilityVersion = environment.DefaultCompatibilityVersion()
931 }
932 env, err := environment.MustBaseEnvSet(compatibilityVersion, tc.strictCost).Extend(
933 environment.VersionedOptions{
934 IntroducedVersion: compatibilityVersion,
935 ProgramOptions: []celgo.ProgramOption{celgo.CostLimit(tc.testPerCallLimit)},
936 },
937 )
938 if err != nil {
939 t.Fatal(err)
940 }
941 c := NewConditionCompiler(env)
942 envType := tc.envType
943 if envType == "" {
944 envType = environment.NewExpressions
945 }
946 f := c.CompileCondition(tc.validations, OptionalVariableDeclarations{HasParams: tc.hasParamKind, HasAuthorizer: tc.authorizer != nil, StrictCost: tc.strictCost}, envType)
947 if f == nil {
948 t.Fatalf("unexpected nil validator")
949 }
950
951 validations := tc.validations
952 CompilationResults := f.(*condition).compilationResults
953 require.Equal(t, len(validations), len(CompilationResults))
954
955 versionedAttr, err := admission.NewVersionedAttributes(tc.attributes, tc.attributes.GetKind(), newObjectInterfacesForTest())
956 if err != nil {
957 t.Fatalf("unexpected error on conversion: %v", err)
958 }
959
960 optionalVars := OptionalVariableBindings{VersionedParams: tc.params, Authorizer: tc.authorizer}
961 ctx := context.TODO()
962 evalResults, _, err := f.ForInput(ctx, versionedAttr, CreateAdmissionRequest(versionedAttr.Attributes, metav1.GroupVersionResource(versionedAttr.GetResource()), metav1.GroupVersionKind(versionedAttr.VersionedKind)), optionalVars, CreateNamespaceObject(tc.namespaceObject), celconfig.RuntimeCELCostBudget)
963 if err != nil {
964 t.Fatalf("unexpected error: %v", err)
965 }
966 require.Equal(t, len(evalResults), len(tc.results))
967 for i, result := range tc.results {
968 if result.Error != nil && evalResults[i].Error == nil {
969 t.Errorf("Expected error result containing '%v' but got non-error", result.Error)
970 continue
971 }
972 if result.Error != nil && !strings.Contains(evalResults[i].Error.Error(), result.Error.Error()) {
973 t.Errorf("Expected result '%v' but got '%v'", result.Error, evalResults[i].Error)
974 continue
975 }
976 if result.Error == nil && evalResults[i].Error != nil {
977 t.Errorf("Expected result '%v' but got error '%v'", result.EvalResult, evalResults[i].Error)
978 continue
979 }
980 if result.EvalResult != evalResults[i].EvalResult {
981 t.Errorf("Expected result '%v' but got '%v'", result.EvalResult, evalResults[i].EvalResult)
982 }
983 }
984 })
985 }
986 }
987
988 func TestRuntimeCELCostBudget(t *testing.T) {
989 configMapParams := &corev1.ConfigMap{
990 ObjectMeta: metav1.ObjectMeta{
991 Name: "foo",
992 },
993 Data: map[string]string{
994 "fakeString": "fake",
995 },
996 }
997
998 cases := []struct {
999 name string
1000 attributes admission.Attributes
1001 params runtime.Object
1002 validations []ExpressionAccessor
1003 hasParamKind bool
1004 authorizer authorizer.Authorizer
1005 testRuntimeCELCostBudget int64
1006 exceedBudget bool
1007 expectRemainingBudget *int64
1008 enableStrictCostEnforcement bool
1009 exceedPerCallLimit bool
1010 }{
1011 {
1012 name: "expression exceed RuntimeCELCostBudget at fist expression",
1013 validations: []ExpressionAccessor{
1014 &testCondition{
1015 Expression: "has(object.subsets) && object.subsets.size() < 2",
1016 },
1017 &testCondition{
1018 Expression: "has(object.subsets)",
1019 },
1020 },
1021 attributes: newValidAttribute(nil, false),
1022 hasParamKind: false,
1023 testRuntimeCELCostBudget: 1,
1024 exceedBudget: true,
1025 },
1026 {
1027 name: "expression exceed RuntimeCELCostBudget at last expression",
1028 validations: []ExpressionAccessor{
1029 &testCondition{
1030 Expression: "has(object.subsets) && object.subsets.size() < 2",
1031 },
1032 &testCondition{
1033 Expression: "object.subsets.size() > 2",
1034 },
1035 },
1036 attributes: newValidAttribute(nil, false),
1037 hasParamKind: true,
1038 params: configMapParams,
1039 testRuntimeCELCostBudget: 5,
1040 exceedBudget: true,
1041 },
1042 {
1043 name: "test RuntimeCELCostBudge is not exceed",
1044 validations: []ExpressionAccessor{
1045 &testCondition{
1046 Expression: "oldObject != null",
1047 },
1048 &testCondition{
1049 Expression: "object.subsets.size() > 2",
1050 },
1051 },
1052 attributes: newValidAttribute(nil, false),
1053 hasParamKind: true,
1054 params: configMapParams,
1055 exceedBudget: false,
1056 testRuntimeCELCostBudget: 10,
1057 expectRemainingBudget: pointer.To(int64(4)), // 10 - 6
1058 },
1059 {
1060 name: "test RuntimeCELCostBudge exactly covers",
1061 validations: []ExpressionAccessor{
1062 &testCondition{
1063 Expression: "oldObject != null",
1064 },
1065 &testCondition{
1066 Expression: "object.subsets.size() > 2",
1067 },
1068 },
1069 attributes: newValidAttribute(nil, false),
1070 hasParamKind: true,
1071 params: configMapParams,
1072 exceedBudget: false,
1073 testRuntimeCELCostBudget: 6,
1074 expectRemainingBudget: pointer.To(int64(0)),
1075 },
1076 {
1077 name: "test RuntimeCELCostBudge exactly covers then constant",
1078 validations: []ExpressionAccessor{
1079 &testCondition{
1080 Expression: "oldObject != null",
1081 },
1082 &testCondition{
1083 Expression: "object.subsets.size() > 2",
1084 },
1085 &testCondition{
1086 Expression: "true", // zero cost
1087 },
1088 },
1089 attributes: newValidAttribute(nil, false),
1090 hasParamKind: true,
1091 params: configMapParams,
1092 exceedBudget: false,
1093 testRuntimeCELCostBudget: 6,
1094 expectRemainingBudget: pointer.To(int64(0)),
1095 },
1096 {
1097 name: "Extended library cost: authz check",
1098 validations: []ExpressionAccessor{
1099 &testCondition{
1100 Expression: "!authorizer.group('').resource('endpoints').check('create').allowed()",
1101 },
1102 },
1103 attributes: newValidAttribute(nil, false),
1104 hasParamKind: false,
1105 exceedBudget: false,
1106 testRuntimeCELCostBudget: 6,
1107 expectRemainingBudget: pointer.To(int64(0)),
1108 authorizer: denyAll,
1109 },
1110 {
1111 name: "Extended library cost: isSorted()",
1112 validations: []ExpressionAccessor{
1113 &testCondition{
1114 Expression: "[1,2,3,4].isSorted()",
1115 },
1116 },
1117 attributes: newValidAttribute(nil, false),
1118 hasParamKind: false,
1119 exceedBudget: false,
1120 testRuntimeCELCostBudget: 1,
1121 expectRemainingBudget: pointer.To(int64(0)),
1122 },
1123 {
1124 name: "Extended library cost: url",
1125 validations: []ExpressionAccessor{
1126 &testCondition{
1127 Expression: "url('https:://kubernetes.io/').getHostname() == 'kubernetes.io'",
1128 },
1129 },
1130 attributes: newValidAttribute(nil, false),
1131 hasParamKind: false,
1132 exceedBudget: false,
1133 testRuntimeCELCostBudget: 2,
1134 expectRemainingBudget: pointer.To(int64(0)),
1135 },
1136 {
1137 name: "Extended library cost: split",
1138 validations: []ExpressionAccessor{
1139 &testCondition{
1140 Expression: "size('abc 123 def 123'.split(' ')) > 0",
1141 },
1142 },
1143 attributes: newValidAttribute(nil, false),
1144 hasParamKind: false,
1145 exceedBudget: false,
1146 testRuntimeCELCostBudget: 3,
1147 expectRemainingBudget: pointer.To(int64(0)),
1148 },
1149 {
1150 name: "Extended library cost: join",
1151 validations: []ExpressionAccessor{
1152 &testCondition{
1153 Expression: "size(['aa', 'bb', 'cc', 'd', 'e', 'f', 'g', 'h', 'i', 'j'].join(' ')) > 0",
1154 },
1155 },
1156 attributes: newValidAttribute(nil, false),
1157 hasParamKind: false,
1158 exceedBudget: false,
1159 testRuntimeCELCostBudget: 3,
1160 expectRemainingBudget: pointer.To(int64(0)),
1161 },
1162 {
1163 name: "Extended library cost: find",
1164 validations: []ExpressionAccessor{
1165 &testCondition{
1166 Expression: "size('abc 123 def 123'.find('123')) > 0",
1167 },
1168 },
1169 attributes: newValidAttribute(nil, false),
1170 hasParamKind: false,
1171 exceedBudget: false,
1172 testRuntimeCELCostBudget: 3,
1173 expectRemainingBudget: pointer.To(int64(0)),
1174 },
1175 {
1176 name: "Extended library cost: quantity",
1177 validations: []ExpressionAccessor{
1178 &testCondition{
1179 Expression: "quantity(\"200M\") == quantity(\"0.2G\") && quantity(\"0.2G\") == quantity(\"200M\")",
1180 },
1181 },
1182 attributes: newValidAttribute(nil, false),
1183 hasParamKind: false,
1184 exceedBudget: false,
1185 testRuntimeCELCostBudget: 6,
1186 expectRemainingBudget: pointer.To(int64(0)),
1187 },
1188 {
1189 name: "With StrictCostEnforcementForVAP enabled: expression exceed RuntimeCELCostBudget at fist expression",
1190 validations: []ExpressionAccessor{
1191 &testCondition{
1192 Expression: "!authorizer.group('').resource('endpoints').check('create').allowed()",
1193 },
1194 &testCondition{
1195 Expression: "has(object.subsets)",
1196 },
1197 },
1198 attributes: newValidAttribute(nil, false),
1199 hasParamKind: false,
1200 testRuntimeCELCostBudget: 35000,
1201 exceedBudget: true,
1202 authorizer: denyAll,
1203 enableStrictCostEnforcement: true,
1204 },
1205 {
1206 name: "With StrictCostEnforcementForVAP enabled: expression exceed RuntimeCELCostBudget at last expression",
1207 validations: []ExpressionAccessor{
1208 &testCondition{
1209 Expression: "!authorizer.group('').resource('endpoints').check('create').allowed()",
1210 },
1211 &testCondition{
1212 Expression: "!authorizer.group('').resource('endpoints').check('create').allowed()",
1213 },
1214 },
1215 attributes: newValidAttribute(nil, false),
1216 hasParamKind: false,
1217 testRuntimeCELCostBudget: 700000,
1218 exceedBudget: true,
1219 authorizer: denyAll,
1220 enableStrictCostEnforcement: true,
1221 },
1222 {
1223 name: "With StrictCostEnforcementForVAP enabled: test RuntimeCELCostBudge is not exceed",
1224 validations: []ExpressionAccessor{
1225 &testCondition{
1226 Expression: "!authorizer.group('').resource('endpoints').check('create').allowed()",
1227 },
1228 &testCondition{
1229 Expression: "!authorizer.group('').resource('endpoints').check('create').allowed()",
1230 },
1231 },
1232 attributes: newValidAttribute(nil, false),
1233 hasParamKind: true,
1234 params: configMapParams,
1235 exceedBudget: false,
1236 testRuntimeCELCostBudget: 700011,
1237 expectRemainingBudget: pointer.To(int64(1)), // 700011 - 700010
1238 authorizer: denyAll,
1239 enableStrictCostEnforcement: true,
1240 },
1241 {
1242 name: "With StrictCostEnforcementForVAP enabled: test RuntimeCELCostBudge exactly covers",
1243 validations: []ExpressionAccessor{
1244 &testCondition{
1245 Expression: "!authorizer.group('').resource('endpoints').check('create').allowed()",
1246 },
1247 &testCondition{
1248 Expression: "!authorizer.group('').resource('endpoints').check('create').allowed()",
1249 },
1250 },
1251 attributes: newValidAttribute(nil, false),
1252 hasParamKind: true,
1253 params: configMapParams,
1254 exceedBudget: false,
1255 testRuntimeCELCostBudget: 700010,
1256 expectRemainingBudget: pointer.To(int64(0)),
1257 authorizer: denyAll,
1258 enableStrictCostEnforcement: true,
1259 },
1260 {
1261 name: "With StrictCostEnforcementForVAP enabled: per call limit exceeds",
1262 validations: []ExpressionAccessor{
1263 &testCondition{
1264 Expression: "!authorizer.group('').resource('endpoints').check('create').allowed() && !authorizer.group('').resource('endpoints').check('create').allowed() && !authorizer.group('').resource('endpoints').check('create').allowed()",
1265 },
1266 },
1267 attributes: newValidAttribute(nil, false),
1268 hasParamKind: true,
1269 params: configMapParams,
1270 authorizer: denyAll,
1271 exceedPerCallLimit: true,
1272 testRuntimeCELCostBudget: -1,
1273 enableStrictCostEnforcement: true,
1274 },
1275 {
1276 name: "With StrictCostEnforcementForVAP enabled: Extended library cost: isSorted()",
1277 validations: []ExpressionAccessor{
1278 &testCondition{
1279 Expression: "[1,2,3,4].isSorted()",
1280 },
1281 },
1282 attributes: newValidAttribute(nil, false),
1283 hasParamKind: false,
1284 exceedBudget: false,
1285 testRuntimeCELCostBudget: 4,
1286 expectRemainingBudget: pointer.To(int64(0)),
1287 enableStrictCostEnforcement: true,
1288 },
1289 {
1290 name: "With StrictCostEnforcementForVAP enabled: Extended library cost: url",
1291 validations: []ExpressionAccessor{
1292 &testCondition{
1293 Expression: "url('https:://kubernetes.io/').getHostname() == 'kubernetes.io'",
1294 },
1295 },
1296 attributes: newValidAttribute(nil, false),
1297 hasParamKind: false,
1298 exceedBudget: false,
1299 testRuntimeCELCostBudget: 4,
1300 expectRemainingBudget: pointer.To(int64(0)),
1301 enableStrictCostEnforcement: true,
1302 },
1303 {
1304 name: "With StrictCostEnforcementForVAP enabled: Extended library cost: split",
1305 validations: []ExpressionAccessor{
1306 &testCondition{
1307 Expression: "size('abc 123 def 123'.split(' ')) > 0",
1308 },
1309 },
1310 attributes: newValidAttribute(nil, false),
1311 hasParamKind: false,
1312 exceedBudget: false,
1313 testRuntimeCELCostBudget: 5,
1314 expectRemainingBudget: pointer.To(int64(0)),
1315 enableStrictCostEnforcement: true,
1316 },
1317 {
1318 name: "With StrictCostEnforcementForVAP enabled: Extended library cost: join",
1319 validations: []ExpressionAccessor{
1320 &testCondition{
1321 Expression: "size(['aa', 'bb', 'cc', 'd', 'e', 'f', 'g', 'h', 'i', 'j'].join(' ')) > 0",
1322 },
1323 },
1324 attributes: newValidAttribute(nil, false),
1325 hasParamKind: false,
1326 exceedBudget: false,
1327 testRuntimeCELCostBudget: 7,
1328 expectRemainingBudget: pointer.To(int64(0)),
1329 enableStrictCostEnforcement: true,
1330 },
1331 {
1332 name: "With StrictCostEnforcementForVAP enabled: Extended library cost: find",
1333 validations: []ExpressionAccessor{
1334 &testCondition{
1335 Expression: "size('abc 123 def 123'.find('123')) > 0",
1336 },
1337 },
1338 attributes: newValidAttribute(nil, false),
1339 hasParamKind: false,
1340 exceedBudget: false,
1341 testRuntimeCELCostBudget: 4,
1342 expectRemainingBudget: pointer.To(int64(0)),
1343 enableStrictCostEnforcement: true,
1344 },
1345 {
1346 name: "With StrictCostEnforcementForVAP enabled: Extended library cost: quantity",
1347 validations: []ExpressionAccessor{
1348 &testCondition{
1349 Expression: "quantity(\"200M\") == quantity(\"0.2G\") && quantity(\"0.2G\") == quantity(\"200M\")",
1350 },
1351 },
1352 attributes: newValidAttribute(nil, false),
1353 hasParamKind: false,
1354 exceedBudget: false,
1355 testRuntimeCELCostBudget: 6,
1356 expectRemainingBudget: pointer.To(int64(0)),
1357 enableStrictCostEnforcement: true,
1358 },
1359 }
1360
1361 for _, tc := range cases {
1362 t.Run(tc.name, func(t *testing.T) {
1363 c := conditionCompiler{compiler: NewCompiler(environment.MustBaseEnvSet(environment.DefaultCompatibilityVersion(), tc.enableStrictCostEnforcement))}
1364 f := c.CompileCondition(tc.validations, OptionalVariableDeclarations{HasParams: tc.hasParamKind, HasAuthorizer: true, StrictCost: tc.enableStrictCostEnforcement}, environment.NewExpressions)
1365 if f == nil {
1366 t.Fatalf("unexpected nil validator")
1367 }
1368 validations := tc.validations
1369 CompilationResults := f.(*condition).compilationResults
1370 require.Equal(t, len(validations), len(CompilationResults))
1371
1372 versionedAttr, err := admission.NewVersionedAttributes(tc.attributes, tc.attributes.GetKind(), newObjectInterfacesForTest())
1373 if err != nil {
1374 t.Fatalf("unexpected error on conversion: %v", err)
1375 }
1376
1377 if tc.testRuntimeCELCostBudget < 0 {
1378 tc.testRuntimeCELCostBudget = celconfig.RuntimeCELCostBudget
1379 }
1380 optionalVars := OptionalVariableBindings{VersionedParams: tc.params, Authorizer: tc.authorizer}
1381 ctx := context.TODO()
1382 evalResults, remaining, err := f.ForInput(ctx, versionedAttr, CreateAdmissionRequest(versionedAttr.Attributes, metav1.GroupVersionResource(versionedAttr.GetResource()), metav1.GroupVersionKind(versionedAttr.VersionedKind)), optionalVars, nil, tc.testRuntimeCELCostBudget)
1383 if tc.exceedPerCallLimit {
1384 hasCostErr := false
1385 for _, evalResult := range evalResults {
1386 if evalResult.Error != nil && strings.Contains(evalResult.Error.Error(), "operation cancelled: actual cost limit exceeded") {
1387 hasCostErr = true
1388 break
1389 }
1390 }
1391 if !hasCostErr {
1392 t.Errorf("Expected per call limit exceeded error but didn't get one")
1393 }
1394 }
1395 if tc.exceedBudget && err == nil {
1396 t.Errorf("Expected RuntimeCELCostBudge to be exceeded but got nil")
1397 }
1398 if tc.exceedBudget && err != nil && !strings.Contains(err.Error(), "validation failed due to running out of cost budget, no further validation rules will be run") {
1399 t.Errorf("Expected RuntimeCELCostBudge exceeded error but got: %v", err)
1400 }
1401 if err != nil && remaining != -1 {
1402 t.Errorf("expected -1 remaining when error, but got %d", remaining)
1403 }
1404 if err != nil && !tc.exceedBudget {
1405 t.Fatalf("unexpected error: %v", err)
1406 }
1407 if tc.exceedBudget && len(evalResults) != 0 {
1408 t.Fatalf("unexpected result returned: %v", evalResults)
1409 }
1410 if tc.expectRemainingBudget != nil && *tc.expectRemainingBudget != remaining {
1411 t.Errorf("wrong remaining budget, expect %d, but got %d", *tc.expectRemainingBudget, remaining)
1412 }
1413 })
1414 }
1415 }
1416
1417 // newObjectInterfacesForTest returns an ObjectInterfaces appropriate for test cases in this file.
1418 func newObjectInterfacesForTest() admission.ObjectInterfaces {
1419 scheme := runtime.NewScheme()
1420 corev1.AddToScheme(scheme)
1421 return admission.NewObjectInterfacesFromScheme(scheme)
1422 }
1423
1424 func newValidAttribute(object runtime.Object, isDelete bool) admission.Attributes {
1425 var oldObject runtime.Object
1426 if !isDelete {
1427 if object == nil {
1428 object = &corev1.Endpoints{
1429 ObjectMeta: metav1.ObjectMeta{
1430 Name: "endpoints1",
1431 },
1432 Subsets: []corev1.EndpointSubset{
1433 {
1434 Addresses: []corev1.EndpointAddress{{IP: "127.0.0.0"}},
1435 },
1436 },
1437 }
1438 }
1439 } else {
1440 object = nil
1441 oldObject = &corev1.Endpoints{
1442 Subsets: []corev1.EndpointSubset{
1443 {
1444 Addresses: []corev1.EndpointAddress{{IP: "127.0.0.0"}},
1445 },
1446 },
1447 }
1448 }
1449 return admission.NewAttributesRecord(object, oldObject, schema.GroupVersionKind{}, "default", "foo", schema.GroupVersionResource{}, "", admission.Create, &metav1.CreateOptions{}, false, nil)
1450
1451 }
1452
1453 func TestCompilationErrors(t *testing.T) {
1454 cases := []struct {
1455 name string
1456 results []CompilationResult
1457 expected []error
1458 }{
1459 {
1460 name: "no errors, empty list",
1461 results: []CompilationResult{},
1462 expected: []error{},
1463 },
1464 {
1465 name: "no errors, several results",
1466 results: []CompilationResult{
1467 {}, {}, {},
1468 },
1469 expected: []error{},
1470 },
1471 {
1472 name: "all errors",
1473 results: []CompilationResult{
1474 {
1475 Error: &apiservercel.Error{
1476 Detail: "error1",
1477 },
1478 },
1479 {
1480 Error: &apiservercel.Error{
1481 Detail: "error2",
1482 },
1483 },
1484 {
1485 Error: &apiservercel.Error{
1486 Detail: "error3",
1487 },
1488 },
1489 },
1490 expected: []error{
1491 errors.New("error1"),
1492 errors.New("error2"),
1493 errors.New("error3"),
1494 },
1495 },
1496 {
1497 name: "mixed errors and non errors",
1498 results: []CompilationResult{
1499 {},
1500 {
1501 Error: &apiservercel.Error{
1502 Detail: "error1",
1503 },
1504 },
1505 {},
1506 {
1507 Error: &apiservercel.Error{
1508 Detail: "error2",
1509 },
1510 },
1511 {},
1512 {},
1513 {
1514 Error: &apiservercel.Error{
1515 Detail: "error3",
1516 },
1517 },
1518 {},
1519 },
1520 expected: []error{
1521 errors.New("error1"),
1522 errors.New("error2"),
1523 errors.New("error3"),
1524 },
1525 },
1526 }
1527
1528 for _, tc := range cases {
1529 t.Run(tc.name, func(t *testing.T) {
1530 e := condition{
1531 compilationResults: tc.results,
1532 }
1533 compilationErrors := e.CompilationErrors()
1534 if compilationErrors == nil {
1535 t.Fatalf("unexpected nil value returned")
1536 }
1537 require.Equal(t, len(compilationErrors), len(tc.expected))
1538
1539 for i, expectedError := range tc.expected {
1540 if expectedError.Error() != compilationErrors[i].Error() {
1541 t.Errorf("Expected error '%v' but got '%v'", expectedError.Error(), compilationErrors[i].Error())
1542 }
1543 }
1544 })
1545 }
1546 }
1547
1548 var denyAll = fakeAuthorizer{defaultResult: authorizerResult{decision: authorizer.DecisionDeny, reason: "fake reason", err: nil}}
1549 var errorAll = fakeAuthorizer{defaultResult: authorizerResult{decision: authorizer.DecisionNoOpinion, reason: "", err: fmt.Errorf("fake authz error")}}
1550
1551 func newAuthzAllowMatch(match authorizer.AttributesRecord) fakeAuthorizer {
1552 return fakeAuthorizer{
1553 match: &authorizerMatch{
1554 match: match,
1555 authorizerResult: authorizerResult{decision: authorizer.DecisionAllow, reason: "", err: nil},
1556 },
1557 defaultResult: authorizerResult{decision: authorizer.DecisionDeny, reason: "", err: nil},
1558 }
1559 }
1560
1561 type fakeAuthorizer struct {
1562 match *authorizerMatch
1563 defaultResult authorizerResult
1564 }
1565
1566 type authorizerResult struct {
1567 decision authorizer.Decision
1568 reason string
1569 err error
1570 }
1571
1572 type authorizerMatch struct {
1573 authorizerResult
1574 match authorizer.AttributesRecord
1575 }
1576
1577 func (f fakeAuthorizer) Authorize(ctx context.Context, a authorizer.Attributes) (authorizer.Decision, string, error) {
1578 if f.match != nil {
1579 other, ok := a.(*authorizer.AttributesRecord)
1580 if !ok {
1581 panic(fmt.Sprintf("unsupported type: %T", a))
1582 }
1583
1584 if reflect.DeepEqual(f.match.match, *other) {
1585 return f.match.decision, f.match.reason, f.match.err
1586 }
1587 }
1588 return f.defaultResult.decision, f.defaultResult.reason, f.defaultResult.err
1589 }
1590
1591 func endpointCreateAttributes() admission.Attributes {
1592 name := "endpoints1"
1593 namespace := "default"
1594 var object, oldObject runtime.Object
1595 object = &corev1.Endpoints{
1596 TypeMeta: metav1.TypeMeta{
1597 Kind: "Endpoints",
1598 APIVersion: "v1",
1599 },
1600 ObjectMeta: metav1.ObjectMeta{
1601 Name: name,
1602 },
1603 Subsets: []corev1.EndpointSubset{
1604 {
1605 Addresses: []corev1.EndpointAddress{{IP: "127.0.0.0"}},
1606 },
1607 },
1608 }
1609 gvk := schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Endpoints"}
1610 gvr := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "endpoints"}
1611 return admission.NewAttributesRecord(object, oldObject, gvk, namespace, name, gvr, "", admission.Create, &metav1.CreateOptions{}, false, nil)
1612 }
1613
1614 func endpointStatusUpdateAttributes() admission.Attributes {
1615 attrs := endpointCreateAttributes()
1616 return admission.NewAttributesRecord(
1617 attrs.GetObject(), attrs.GetObject(), attrs.GetKind(), attrs.GetNamespace(), attrs.GetName(),
1618 attrs.GetResource(), "status", admission.Update, &metav1.UpdateOptions{}, false, nil)
1619 }