Debian Codegraph @

pkg/apis/apiserver/validation/validation_test.go

raw
1 /*
2 Copyright 2023 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 validation
18
19 import (
20 "crypto/ecdsa"
21 "crypto/elliptic"
22 "crypto/rand"
23 "encoding/pem"
24 "fmt"
25 "os"
26 "testing"
27 "time"
28
29 "github.com/google/go-cmp/cmp"
30
31 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
32 "k8s.io/apimachinery/pkg/util/errors"
33 "k8s.io/apimachinery/pkg/util/sets"
34 "k8s.io/apimachinery/pkg/util/validation/field"
35 api "k8s.io/apiserver/pkg/apis/apiserver"
36 authenticationcel "k8s.io/apiserver/pkg/authentication/cel"
37 authorizationcel "k8s.io/apiserver/pkg/authorization/cel"
38 "k8s.io/apiserver/pkg/features"
39 utilfeature "k8s.io/apiserver/pkg/util/feature"
40 certutil "k8s.io/client-go/util/cert"
41 featuregatetesting "k8s.io/component-base/featuregate/testing"
42 "k8s.io/utils/pointer"
43 )
44
45 func TestValidateAuthenticationConfiguration(t *testing.T) {
46 featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.StructuredAuthenticationConfiguration, true)
47
48 testCases := []struct {
49 name string
50 in *api.AuthenticationConfiguration
51 disallowedIssuers []string
52 want string
53 }{
54 {
55 name: "jwt authenticator is empty",
56 in: &api.AuthenticationConfiguration{},
57 want: "",
58 },
59 {
60 name: "duplicate issuer across jwt authenticators",
61 in: &api.AuthenticationConfiguration{
62 JWT: []api.JWTAuthenticator{
63 {
64 Issuer: api.Issuer{
65 URL: "https://issuer-url",
66 Audiences: []string{"audience"},
67 },
68 ClaimValidationRules: []api.ClaimValidationRule{
69 {
70 Claim: "foo",
71 RequiredValue: "bar",
72 },
73 },
74 ClaimMappings: api.ClaimMappings{
75 Username: api.PrefixedClaimOrExpression{
76 Claim: "sub",
77 Prefix: pointer.String("prefix"),
78 },
79 },
80 },
81 {
82 Issuer: api.Issuer{
83 URL: "https://issuer-url",
84 Audiences: []string{"audience"},
85 },
86 ClaimValidationRules: []api.ClaimValidationRule{
87 {
88 Claim: "foo",
89 RequiredValue: "bar",
90 },
91 },
92 ClaimMappings: api.ClaimMappings{
93 Username: api.PrefixedClaimOrExpression{
94 Claim: "sub",
95 Prefix: pointer.String("prefix"),
96 },
97 },
98 },
99 },
100 },
101 want: `jwt[1].issuer.url: Duplicate value: "https://issuer-url"`,
102 },
103 {
104 name: "duplicate discoveryURL across jwt authenticators",
105 in: &api.AuthenticationConfiguration{
106 JWT: []api.JWTAuthenticator{
107 {
108 Issuer: api.Issuer{
109 URL: "https://issuer-url",
110 DiscoveryURL: "https://discovery-url/.well-known/openid-configuration",
111 Audiences: []string{"audience"},
112 },
113 ClaimValidationRules: []api.ClaimValidationRule{
114 {
115 Claim: "foo",
116 RequiredValue: "bar",
117 },
118 },
119 ClaimMappings: api.ClaimMappings{
120 Username: api.PrefixedClaimOrExpression{
121 Claim: "sub",
122 Prefix: pointer.String("prefix"),
123 },
124 },
125 },
126 {
127 Issuer: api.Issuer{
128 URL: "https://different-issuer-url",
129 DiscoveryURL: "https://discovery-url/.well-known/openid-configuration",
130 Audiences: []string{"audience"},
131 },
132 ClaimValidationRules: []api.ClaimValidationRule{
133 {
134 Claim: "foo",
135 RequiredValue: "bar",
136 },
137 },
138 ClaimMappings: api.ClaimMappings{
139 Username: api.PrefixedClaimOrExpression{
140 Claim: "sub",
141 Prefix: pointer.String("prefix"),
142 },
143 },
144 },
145 },
146 },
147 want: `jwt[1].issuer.discoveryURL: Duplicate value: "https://discovery-url/.well-known/openid-configuration"`,
148 },
149 {
150 name: "failed issuer validation",
151 in: &api.AuthenticationConfiguration{
152 JWT: []api.JWTAuthenticator{
153 {
154 Issuer: api.Issuer{
155 URL: "invalid-url",
156 Audiences: []string{"audience"},
157 },
158 ClaimMappings: api.ClaimMappings{
159 Username: api.PrefixedClaimOrExpression{
160 Claim: "claim",
161 Prefix: pointer.String("prefix"),
162 },
163 },
164 },
165 },
166 },
167 want: `jwt[0].issuer.url: Invalid value: "invalid-url": URL scheme must be https`,
168 },
169 {
170 name: "failed claimValidationRule validation",
171 in: &api.AuthenticationConfiguration{
172 JWT: []api.JWTAuthenticator{
173 {
174 Issuer: api.Issuer{
175 URL: "https://issuer-url",
176 Audiences: []string{"audience"},
177 },
178 ClaimValidationRules: []api.ClaimValidationRule{
179 {
180 Claim: "foo",
181 RequiredValue: "bar",
182 },
183 {
184 Claim: "foo",
185 RequiredValue: "baz",
186 },
187 },
188 ClaimMappings: api.ClaimMappings{
189 Username: api.PrefixedClaimOrExpression{
190 Claim: "claim",
191 Prefix: pointer.String("prefix"),
192 },
193 },
194 },
195 },
196 },
197 want: `jwt[0].claimValidationRules[1].claim: Duplicate value: "foo"`,
198 },
199 {
200 name: "failed claimMapping validation",
201 in: &api.AuthenticationConfiguration{
202 JWT: []api.JWTAuthenticator{
203 {
204 Issuer: api.Issuer{
205 URL: "https://issuer-url",
206 Audiences: []string{"audience"},
207 },
208 ClaimValidationRules: []api.ClaimValidationRule{
209 {
210 Claim: "foo",
211 RequiredValue: "bar",
212 },
213 },
214 ClaimMappings: api.ClaimMappings{
215 Username: api.PrefixedClaimOrExpression{
216 Prefix: pointer.String("prefix"),
217 },
218 },
219 },
220 },
221 },
222 want: "jwt[0].claimMappings.username: Required value: claim or expression is required",
223 },
224 {
225 name: "failed userValidationRule validation",
226 in: &api.AuthenticationConfiguration{
227 JWT: []api.JWTAuthenticator{
228 {
229 Issuer: api.Issuer{
230 URL: "https://issuer-url",
231 Audiences: []string{"audience"},
232 },
233 ClaimValidationRules: []api.ClaimValidationRule{
234 {
235 Claim: "foo",
236 RequiredValue: "bar",
237 },
238 },
239 ClaimMappings: api.ClaimMappings{
240 Username: api.PrefixedClaimOrExpression{
241 Claim: "sub",
242 Prefix: pointer.String("prefix"),
243 },
244 },
245 UserValidationRules: []api.UserValidationRule{
246 {Expression: "user.username == 'foo'"},
247 {Expression: "user.username == 'foo'"},
248 },
249 },
250 },
251 },
252 want: `jwt[0].userValidationRules[1].expression: Duplicate value: "user.username == 'foo'"`,
253 },
254 {
255 name: "valid authentication configuration with disallowed issuer",
256 in: &api.AuthenticationConfiguration{
257 JWT: []api.JWTAuthenticator{
258 {
259 Issuer: api.Issuer{
260 URL: "https://issuer-url",
261 Audiences: []string{"audience"},
262 },
263 ClaimValidationRules: []api.ClaimValidationRule{
264 {
265 Claim: "foo",
266 RequiredValue: "bar",
267 },
268 },
269 ClaimMappings: api.ClaimMappings{
270 Username: api.PrefixedClaimOrExpression{
271 Claim: "sub",
272 Prefix: pointer.String("prefix"),
273 },
274 },
275 },
276 },
277 },
278 disallowedIssuers: []string{"a", "b", "https://issuer-url", "c"},
279 want: `jwt[0].issuer.url: Invalid value: "https://issuer-url": URL must not overlap with disallowed issuers: [a b c https://issuer-url]`,
280 },
281 {
282 name: "valid authentication configuration that uses unverified email",
283 in: &api.AuthenticationConfiguration{
284 JWT: []api.JWTAuthenticator{
285 {
286 Issuer: api.Issuer{
287 URL: "https://issuer-url",
288 Audiences: []string{"audience"},
289 },
290 ClaimValidationRules: []api.ClaimValidationRule{
291 {
292 Claim: "foo",
293 RequiredValue: "bar",
294 },
295 },
296 ClaimMappings: api.ClaimMappings{
297 Username: api.PrefixedClaimOrExpression{
298 Expression: "claims.email",
299 },
300 },
301 },
302 },
303 },
304 want: `jwt[0].claimMappings.username.expression: Invalid value: "claims.email": claims.email_verified must be used in claimMappings.username.expression or claimMappings.extra[*].valueExpression or claimValidationRules[*].expression when claims.email is used in claimMappings.username.expression`,
305 },
306 {
307 name: "valid authentication configuration that almost uses unverified email",
308 in: &api.AuthenticationConfiguration{
309 JWT: []api.JWTAuthenticator{
310 {
311 Issuer: api.Issuer{
312 URL: "https://issuer-url",
313 Audiences: []string{"audience"},
314 },
315 ClaimValidationRules: []api.ClaimValidationRule{
316 {
317 Claim: "foo",
318 RequiredValue: "bar",
319 },
320 },
321 ClaimMappings: api.ClaimMappings{
322 Username: api.PrefixedClaimOrExpression{
323 Expression: "claims.email_",
324 },
325 },
326 },
327 },
328 },
329 want: "",
330 },
331 {
332 name: "valid authentication configuration that uses unverified email join",
333 in: &api.AuthenticationConfiguration{
334 JWT: []api.JWTAuthenticator{
335 {
336 Issuer: api.Issuer{
337 URL: "https://issuer-url",
338 Audiences: []string{"audience"},
339 },
340 ClaimValidationRules: []api.ClaimValidationRule{
341 {
342 Claim: "foo",
343 RequiredValue: "bar",
344 },
345 },
346 ClaimMappings: api.ClaimMappings{
347 Username: api.PrefixedClaimOrExpression{
348 Expression: `['yay', string(claims.email), 'panda'].join(' ')`,
349 },
350 },
351 },
352 },
353 },
354 want: `jwt[0].claimMappings.username.expression: Invalid value: "['yay', string(claims.email), 'panda'].join(' ')": claims.email_verified must be used in claimMappings.username.expression or claimMappings.extra[*].valueExpression or claimValidationRules[*].expression when claims.email is used in claimMappings.username.expression`,
355 },
356 {
357 name: "valid authentication configuration that uses unverified optional email",
358 in: &api.AuthenticationConfiguration{
359 JWT: []api.JWTAuthenticator{
360 {
361 Issuer: api.Issuer{
362 URL: "https://issuer-url",
363 Audiences: []string{"audience"},
364 },
365 ClaimValidationRules: []api.ClaimValidationRule{
366 {
367 Claim: "foo",
368 RequiredValue: "bar",
369 },
370 },
371 ClaimMappings: api.ClaimMappings{
372 Username: api.PrefixedClaimOrExpression{
373 Expression: `claims.?email`,
374 },
375 },
376 },
377 },
378 },
379 want: `jwt[0].claimMappings.username.expression: Invalid value: "claims.?email": claims.email_verified must be used in claimMappings.username.expression or claimMappings.extra[*].valueExpression or claimValidationRules[*].expression when claims.email is used in claimMappings.username.expression`,
380 },
381 {
382 name: "valid authentication configuration that uses unverified optional map email key",
383 in: &api.AuthenticationConfiguration{
384 JWT: []api.JWTAuthenticator{
385 {
386 Issuer: api.Issuer{
387 URL: "https://issuer-url",
388 Audiences: []string{"audience"},
389 },
390 ClaimValidationRules: []api.ClaimValidationRule{
391 {
392 Claim: "foo",
393 RequiredValue: "bar",
394 },
395 },
396 ClaimMappings: api.ClaimMappings{
397 Username: api.PrefixedClaimOrExpression{
398 Expression: `{claims.?email: "panda"}`,
399 },
400 },
401 },
402 },
403 },
404 want: `jwt[0].claimMappings.username.expression: Invalid value: "{claims.?email: \"panda\"}": claims.email_verified must be used in claimMappings.username.expression or claimMappings.extra[*].valueExpression or claimValidationRules[*].expression when claims.email is used in claimMappings.username.expression`,
405 },
406 {
407 name: "valid authentication configuration that uses unverified optional map email value",
408 in: &api.AuthenticationConfiguration{
409 JWT: []api.JWTAuthenticator{
410 {
411 Issuer: api.Issuer{
412 URL: "https://issuer-url",
413 Audiences: []string{"audience"},
414 },
415 ClaimValidationRules: []api.ClaimValidationRule{
416 {
417 Claim: "foo",
418 RequiredValue: "bar",
419 },
420 },
421 ClaimMappings: api.ClaimMappings{
422 Username: api.PrefixedClaimOrExpression{
423 Expression: `{"fancy": claims.?email}`,
424 },
425 },
426 },
427 },
428 },
429 want: `jwt[0].claimMappings.username.expression: Invalid value: "{\"fancy\": claims.?email}": claims.email_verified must be used in claimMappings.username.expression or claimMappings.extra[*].valueExpression or claimValidationRules[*].expression when claims.email is used in claimMappings.username.expression`,
430 },
431 {
432 name: "valid authentication configuration that uses unverified email value in list iteration",
433 in: &api.AuthenticationConfiguration{
434 JWT: []api.JWTAuthenticator{
435 {
436 Issuer: api.Issuer{
437 URL: "https://issuer-url",
438 Audiences: []string{"audience"},
439 },
440 ClaimValidationRules: []api.ClaimValidationRule{
441 {
442 Claim: "foo",
443 RequiredValue: "bar",
444 },
445 },
446 ClaimMappings: api.ClaimMappings{
447 Username: api.PrefixedClaimOrExpression{
448 Expression: `["a"].map(i, i + claims.email)`,
449 },
450 },
451 },
452 },
453 },
454 want: `jwt[0].claimMappings.username.expression: Invalid value: "[\"a\"].map(i, i + claims.email)": claims.email_verified must be used in claimMappings.username.expression or claimMappings.extra[*].valueExpression or claimValidationRules[*].expression when claims.email is used in claimMappings.username.expression`,
455 },
456 {
457 name: "valid authentication configuration that uses verified email join via rule",
458 in: &api.AuthenticationConfiguration{
459 JWT: []api.JWTAuthenticator{
460 {
461 Issuer: api.Issuer{
462 URL: "https://issuer-url",
463 Audiences: []string{"audience"},
464 },
465 ClaimValidationRules: []api.ClaimValidationRule{
466 {
467 Expression: `string(claims.email_verified) == "panda"`,
468 },
469 },
470 ClaimMappings: api.ClaimMappings{
471 Username: api.PrefixedClaimOrExpression{
472 Expression: `['yay', string(claims.email), 'panda'].join(' ')`,
473 },
474 },
475 },
476 },
477 },
478 want: "",
479 },
480 {
481 name: "valid authentication configuration that uses verified email join via extra",
482 in: &api.AuthenticationConfiguration{
483 JWT: []api.JWTAuthenticator{
484 {
485 Issuer: api.Issuer{
486 URL: "https://issuer-url",
487 Audiences: []string{"audience"},
488 },
489 ClaimValidationRules: []api.ClaimValidationRule{
490 {
491 Claim: "foo",
492 RequiredValue: "bar",
493 },
494 },
495 ClaimMappings: api.ClaimMappings{
496 Username: api.PrefixedClaimOrExpression{
497 Expression: `['yay', string(claims.email), 'panda'].join(' ')`,
498 },
499 Extra: []api.ExtraMapping{
500 {Key: "panda.io/foo", ValueExpression: "claims.email_verified.upperAscii()"},
501 },
502 },
503 },
504 },
505 },
506 want: "",
507 },
508 {
509 name: "valid authentication configuration that uses verified email join via extra optional",
510 in: &api.AuthenticationConfiguration{
511 JWT: []api.JWTAuthenticator{
512 {
513 Issuer: api.Issuer{
514 URL: "https://issuer-url",
515 Audiences: []string{"audience"},
516 },
517 ClaimValidationRules: []api.ClaimValidationRule{
518 {
519 Claim: "foo",
520 RequiredValue: "bar",
521 },
522 },
523 ClaimMappings: api.ClaimMappings{
524 Username: api.PrefixedClaimOrExpression{
525 Expression: `['yay', string(claims.email), 'panda'].join(' ')`,
526 },
527 Extra: []api.ExtraMapping{
528 {Key: "panda.io/foo", ValueExpression: "claims.?email_verified"},
529 },
530 },
531 },
532 },
533 },
534 want: "",
535 },
536 {
537 name: "valid authentication configuration that uses email and email_verified || true via username",
538 in: &api.AuthenticationConfiguration{
539 JWT: []api.JWTAuthenticator{
540 {
541 Issuer: api.Issuer{
542 URL: "https://issuer-url",
543 Audiences: []string{"audience"},
544 },
545 ClaimValidationRules: []api.ClaimValidationRule{
546 {
547 Claim: "foo",
548 RequiredValue: "bar",
549 },
550 },
551 // allow email claim when email_verified is true or absent
552 ClaimMappings: api.ClaimMappings{
553 Username: api.PrefixedClaimOrExpression{
554 Expression: `claims.?email_verified.orValue(true) ? claims.email : claims.sub`,
555 },
556 },
557 },
558 },
559 },
560 want: "",
561 },
562 {
563 name: "valid authentication configuration that uses email and email_verified || false via username",
564 in: &api.AuthenticationConfiguration{
565 JWT: []api.JWTAuthenticator{
566 {
567 Issuer: api.Issuer{
568 URL: "https://issuer-url",
569 Audiences: []string{"audience"},
570 },
571 ClaimValidationRules: []api.ClaimValidationRule{
572 {
573 Claim: "foo",
574 RequiredValue: "bar",
575 },
576 },
577 // allow email claim only when email_verified is present and true
578 ClaimMappings: api.ClaimMappings{
579 Username: api.PrefixedClaimOrExpression{
580 Expression: `claims.?email_verified.orValue(false) ? claims.email : claims.sub`,
581 },
582 },
583 },
584 },
585 },
586 want: "",
587 },
588 {
589 name: "valid authentication configuration that uses verified email via claim validation rule",
590 in: &api.AuthenticationConfiguration{
591 JWT: []api.JWTAuthenticator{
592 {
593 Issuer: api.Issuer{
594 URL: "https://issuer-url",
595 Audiences: []string{"audience"},
596 },
597 ClaimValidationRules: []api.ClaimValidationRule{
598 {
599 // By explicitly comparing the value to true, we let type-checking see the result will be
600 // a boolean, and to make sure a non-boolean email_verified claim will be caught at runtime.
601 Expression: `claims.?email_verified.orValue(true) == true`,
602 },
603 },
604 // allow email claim only when email_verified is present and true
605 ClaimMappings: api.ClaimMappings{
606 Username: api.PrefixedClaimOrExpression{
607 Expression: `{claims.?email: "panda"}`,
608 },
609 },
610 },
611 },
612 },
613 want: "",
614 },
615 {
616 name: "valid authentication configuration that uses verified email via claim validation rule incorrectly",
617 in: &api.AuthenticationConfiguration{
618 JWT: []api.JWTAuthenticator{
619 {
620 Issuer: api.Issuer{
621 URL: "https://issuer-url",
622 Audiences: []string{"audience"},
623 },
624 ClaimValidationRules: []api.ClaimValidationRule{
625 {
626 // This expression was previously documented in the godoc for the JWT authenticator
627 // and was incorrect. It was changed to the above expression in the previous test case.
628 // Testing the old expression here to confirm it fails validation.
629 Expression: `claims.?email_verified.orValue(true)`,
630 },
631 },
632 // allow email claim only when email_verified is present and true
633 ClaimMappings: api.ClaimMappings{
634 Username: api.PrefixedClaimOrExpression{
635 Expression: `{claims.?email: "panda"}`,
636 },
637 },
638 },
639 },
640 },
641 want: `[jwt[0].claimValidationRules[0].expression: Invalid value: "claims.?email_verified.orValue(true)": must evaluate to bool, jwt[0].claimMappings.username.expression: Invalid value: "{claims.?email: \"panda\"}": claims.email_verified must be used in claimMappings.username.expression or claimMappings.extra[*].valueExpression or claimValidationRules[*].expression when claims.email is used in claimMappings.username.expression]`,
642 },
643 {
644 name: "valid authentication configuration",
645 in: &api.AuthenticationConfiguration{
646 JWT: []api.JWTAuthenticator{
647 {
648 Issuer: api.Issuer{
649 URL: "https://issuer-url",
650 Audiences: []string{"audience"},
651 },
652 ClaimValidationRules: []api.ClaimValidationRule{
653 {
654 Claim: "foo",
655 RequiredValue: "bar",
656 },
657 },
658 ClaimMappings: api.ClaimMappings{
659 Username: api.PrefixedClaimOrExpression{
660 Claim: "sub",
661 Prefix: pointer.String("prefix"),
662 },
663 },
664 },
665 },
666 },
667 want: "",
668 },
669 }
670
671 for _, tt := range testCases {
672 t.Run(tt.name, func(t *testing.T) {
673 got := ValidateAuthenticationConfiguration(authenticationcel.NewDefaultCompiler(), tt.in, tt.disallowedIssuers).ToAggregate()
674 if d := cmp.Diff(tt.want, errString(got)); d != "" {
675 t.Fatalf("AuthenticationConfiguration validation mismatch (-want +got):\n%s", d)
676 }
677 })
678 }
679 }
680
681 func TestValidateIssuerURL(t *testing.T) {
682 fldPath := field.NewPath("issuer", "url")
683
684 testCases := []struct {
685 name string
686 in string
687 disallowedIssuers sets.Set[string]
688 want string
689 }{
690 {
691 name: "url is empty",
692 in: "",
693 want: "issuer.url: Required value: URL is required",
694 },
695 {
696 name: "url parse error",
697 in: "https://issuer-url:invalid-port",
698 want: `issuer.url: Invalid value: "https://issuer-url:invalid-port": parse "https://issuer-url:invalid-port": invalid port ":invalid-port" after host`,
699 },
700 {
701 name: "url is not https",
702 in: "http://issuer-url",
703 want: `issuer.url: Invalid value: "http://issuer-url": URL scheme must be https`,
704 },
705 {
706 name: "url user info is not allowed",
707 in: "https://user:pass@issuer-url",
708 want: `issuer.url: Invalid value: "https://user:pass@issuer-url": URL must not contain a username or password`,
709 },
710 {
711 name: "url raw query is not allowed",
712 in: "https://issuer-url?query",
713 want: `issuer.url: Invalid value: "https://issuer-url?query": URL must not contain a query`,
714 },
715 {
716 name: "url fragment is not allowed",
717 in: "https://issuer-url#fragment",
718 want: `issuer.url: Invalid value: "https://issuer-url#fragment": URL must not contain a fragment`,
719 },
720 {
721 name: "valid url that is disallowed",
722 in: "https://issuer-url",
723 disallowedIssuers: sets.New("https://issuer-url"),
724 want: `issuer.url: Invalid value: "https://issuer-url": URL must not overlap with disallowed issuers: [https://issuer-url]`,
725 },
726 {
727 name: "valid url",
728 in: "https://issuer-url",
729 want: "",
730 },
731 }
732
733 for _, tt := range testCases {
734 t.Run(tt.name, func(t *testing.T) {
735 got := validateIssuerURL(tt.in, tt.disallowedIssuers, fldPath).ToAggregate()
736 if d := cmp.Diff(tt.want, errString(got)); d != "" {
737 t.Fatalf("URL validation mismatch (-want +got):\n%s", d)
738 }
739 })
740 }
741 }
742
743 func TestValidateIssuerDiscoveryURL(t *testing.T) {
744 fldPath := field.NewPath("issuer", "discoveryURL")
745
746 testCases := []struct {
747 name string
748 in string
749 issuerURL string
750 want string
751 structuredAuthnFeatureEnabled bool
752 }{
753 {
754 name: "url is empty",
755 in: "",
756 want: "",
757 structuredAuthnFeatureEnabled: true,
758 },
759 {
760 name: "url parse error",
761 in: "https://oidc.oidc-namespace.svc:invalid-port",
762 want: `issuer.discoveryURL: Invalid value: "https://oidc.oidc-namespace.svc:invalid-port": parse "https://oidc.oidc-namespace.svc:invalid-port": invalid port ":invalid-port" after host`,
763 structuredAuthnFeatureEnabled: true,
764 },
765 {
766 name: "url is not https",
767 in: "http://oidc.oidc-namespace.svc",
768 want: `issuer.discoveryURL: Invalid value: "http://oidc.oidc-namespace.svc": URL scheme must be https`,
769 structuredAuthnFeatureEnabled: true,
770 },
771 {
772 name: "url user info is not allowed",
773 in: "https://user:[email protected]",
774 want: `issuer.discoveryURL: Invalid value: "https://user:[email protected]": URL must not contain a username or password`,
775 structuredAuthnFeatureEnabled: true,
776 },
777 {
778 name: "url raw query is not allowed",
779 in: "https://oidc.oidc-namespace.svc?query",
780 want: `issuer.discoveryURL: Invalid value: "https://oidc.oidc-namespace.svc?query": URL must not contain a query`,
781 structuredAuthnFeatureEnabled: true,
782 },
783 {
784 name: "url fragment is not allowed",
785 in: "https://oidc.oidc-namespace.svc#fragment",
786 want: `issuer.discoveryURL: Invalid value: "https://oidc.oidc-namespace.svc#fragment": URL must not contain a fragment`,
787 structuredAuthnFeatureEnabled: true,
788 },
789 {
790 name: "valid url",
791 in: "https://oidc.oidc-namespace.svc",
792 want: "",
793 structuredAuthnFeatureEnabled: true,
794 },
795 {
796 name: "valid url with path",
797 in: "https://oidc.oidc-namespace.svc/path",
798 want: "",
799 structuredAuthnFeatureEnabled: true,
800 },
801 {
802 name: "discovery url same as issuer url",
803 issuerURL: "https://issuer-url",
804 in: "https://issuer-url",
805 want: `issuer.discoveryURL: Invalid value: "https://issuer-url": discoveryURL must be different from URL`,
806 structuredAuthnFeatureEnabled: true,
807 },
808 {
809 name: "discovery url same as issuer url, with trailing slash",
810 issuerURL: "https://issuer-url",
811 in: "https://issuer-url/",
812 want: `issuer.discoveryURL: Invalid value: "https://issuer-url/": discoveryURL must be different from URL`,
813 structuredAuthnFeatureEnabled: true,
814 },
815 {
816 name: "discovery url same as issuer url, with multiple trailing slashes",
817 issuerURL: "https://issuer-url",
818 in: "https://issuer-url///",
819 want: `issuer.discoveryURL: Invalid value: "https://issuer-url///": discoveryURL must be different from URL`,
820 structuredAuthnFeatureEnabled: true,
821 },
822 {
823 name: "discovery url same as issuer url, issuer url with trailing slash",
824 issuerURL: "https://issuer-url/",
825 in: "https://issuer-url",
826 want: `issuer.discoveryURL: Invalid value: "https://issuer-url": discoveryURL must be different from URL`,
827 structuredAuthnFeatureEnabled: true,
828 },
829 {
830 name: "discovery url set but structured authn feature disabled",
831 in: "https://oidc.oidc-namespace.svc",
832 want: `issuer.discoveryURL: Invalid value: "https://oidc.oidc-namespace.svc": discoveryURL is not supported when StructuredAuthenticationConfiguration feature gate is disabled`,
833 },
834 }
835
836 for _, tt := range testCases {
837 t.Run(tt.name, func(t *testing.T) {
838 got := validateIssuerDiscoveryURL(tt.issuerURL, tt.in, fldPath, tt.structuredAuthnFeatureEnabled).ToAggregate()
839 if d := cmp.Diff(tt.want, errString(got)); d != "" {
840 t.Fatalf("URL validation mismatch (-want +got):\n%s", d)
841 }
842 })
843 }
844 }
845
846 func TestValidateAudiences(t *testing.T) {
847 fldPath := field.NewPath("issuer", "audiences")
848 audienceMatchPolicyFldPath := field.NewPath("issuer", "audienceMatchPolicy")
849
850 testCases := []struct {
851 name string
852 in []string
853 matchPolicy string
854 want string
855 structuredAuthnFeatureEnabled bool
856 }{
857 {
858 name: "audiences is empty",
859 in: []string{},
860 want: "issuer.audiences: Required value: at least one issuer.audiences is required",
861 },
862 {
863 name: "audience is empty",
864 in: []string{""},
865 want: "issuer.audiences[0]: Required value: audience can't be empty",
866 },
867 {
868 name: "invalid match policy with single audience",
869 in: []string{"audience"},
870 matchPolicy: "MatchExact",
871 want: `issuer.audienceMatchPolicy: Invalid value: "MatchExact": audienceMatchPolicy must be empty or MatchAny for single audience`,
872 },
873 {
874 name: "valid audience",
875 in: []string{"audience"},
876 want: "",
877 },
878 {
879 name: "valid audience with MatchAny policy",
880 in: []string{"audience"},
881 matchPolicy: "MatchAny",
882 want: "",
883 },
884 {
885 name: "duplicate audience",
886 in: []string{"audience", "audience"},
887 matchPolicy: "MatchAny",
888 want: `issuer.audiences[1]: Duplicate value: "audience"`,
889 structuredAuthnFeatureEnabled: true,
890 },
891 {
892 name: "match policy not set with multiple audiences",
893 in: []string{"audience1", "audience2"},
894 want: `issuer.audienceMatchPolicy: Invalid value: "": audienceMatchPolicy must be MatchAny for multiple audiences`,
895 structuredAuthnFeatureEnabled: true,
896 },
897 {
898 name: "valid multiple audiences",
899 in: []string{"audience1", "audience2"},
900 matchPolicy: "MatchAny",
901 want: "",
902 structuredAuthnFeatureEnabled: true,
903 },
904 {
905 name: "multiple audiences set when structured authn feature is disabled",
906 in: []string{"audience1", "audience2"},
907 matchPolicy: "MatchAny",
908 want: `issuer.audiences: Invalid value: []string{"audience1", "audience2"}: multiple audiences are not supported when StructuredAuthenticationConfiguration feature gate is disabled`,
909 },
910 }
911
912 for _, tt := range testCases {
913 t.Run(tt.name, func(t *testing.T) {
914 got := validateAudiences(tt.in, api.AudienceMatchPolicyType(tt.matchPolicy), fldPath, audienceMatchPolicyFldPath, tt.structuredAuthnFeatureEnabled).ToAggregate()
915 if d := cmp.Diff(tt.want, errString(got)); d != "" {
916 t.Fatalf("Audiences validation mismatch (-want +got):\n%s", d)
917 }
918 })
919 }
920 }
921
922 func TestValidateCertificateAuthority(t *testing.T) {
923 fldPath := field.NewPath("issuer", "certificateAuthority")
924
925 testCases := []struct {
926 name string
927 in func() string
928 want string
929 }{
930 {
931 name: "invalid certificate authority",
932 in: func() string { return "invalid" },
933 want: `issuer.certificateAuthority: Invalid value: "<omitted>": data does not contain any valid RSA or ECDSA certificates`,
934 },
935 {
936 name: "certificate authority is empty",
937 in: func() string { return "" },
938 want: "",
939 },
940 {
941 name: "valid certificate authority",
942 in: func() string {
943 caPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
944 if err != nil {
945 t.Fatal(err)
946 }
947 caCert, err := certutil.NewSelfSignedCACert(certutil.Config{CommonName: "test-ca"}, caPrivateKey)
948 if err != nil {
949 t.Fatal(err)
950 }
951 return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caCert.Raw}))
952 },
953 want: "",
954 },
955 }
956
957 for _, tt := range testCases {
958 t.Run(tt.name, func(t *testing.T) {
959 got := validateCertificateAuthority(tt.in(), fldPath).ToAggregate()
960 if d := cmp.Diff(tt.want, errString(got)); d != "" {
961 t.Fatalf("CertificateAuthority validation mismatch (-want +got):\n%s", d)
962 }
963 })
964 }
965 }
966
967 func TestValidateClaimValidationRules(t *testing.T) {
968 fldPath := field.NewPath("issuer", "claimValidationRules")
969
970 testCases := []struct {
971 name string
972 in []api.ClaimValidationRule
973 structuredAuthnFeatureEnabled bool
974 want string
975 wantCELMapper bool
976 wantUsesEmailVerifiedClaim bool
977 }{
978 {
979 name: "claim and expression are empty, structured authn feature enabled",
980 in: []api.ClaimValidationRule{{}},
981 structuredAuthnFeatureEnabled: true,
982 want: "issuer.claimValidationRules[0]: Required value: claim or expression is required",
983 },
984 {
985 name: "claim and expression are set",
986 in: []api.ClaimValidationRule{
987 {Claim: "claim", Expression: "expression"},
988 },
989 structuredAuthnFeatureEnabled: true,
990 want: `issuer.claimValidationRules[0]: Invalid value: "claim": claim and expression can't both be set`,
991 },
992 {
993 name: "message set when claim is set",
994 in: []api.ClaimValidationRule{
995 {Claim: "claim", Message: "message"},
996 },
997 structuredAuthnFeatureEnabled: true,
998 want: `issuer.claimValidationRules[0].message: Invalid value: "message": message can't be set when claim is set`,
999 },
1000 {
1001 name: "requiredValue set when expression is set",
1002 in: []api.ClaimValidationRule{
1003 {Expression: "claims.foo == 'bar'", RequiredValue: "value"},
1004 },
1005 structuredAuthnFeatureEnabled: true,
1006 want: `issuer.claimValidationRules[0].requiredValue: Invalid value: "value": requiredValue can't be set when expression is set`,
1007 },
1008 {
1009 name: "duplicate claim",
1010 in: []api.ClaimValidationRule{
1011 {Claim: "claim"},
1012 {Claim: "claim"},
1013 },
1014 structuredAuthnFeatureEnabled: true,
1015 want: `issuer.claimValidationRules[1].claim: Duplicate value: "claim"`,
1016 },
1017 {
1018 name: "duplicate expression",
1019 in: []api.ClaimValidationRule{
1020 {Expression: "claims.foo == 'bar'"},
1021 {Expression: "claims.foo == 'bar'"},
1022 },
1023 structuredAuthnFeatureEnabled: true,
1024 want: `issuer.claimValidationRules[1].expression: Duplicate value: "claims.foo == 'bar'"`,
1025 },
1026 {
1027 name: "expression set when structured authn feature is disabled",
1028 in: []api.ClaimValidationRule{
1029 {Expression: "claims.foo == 'bar'"},
1030 },
1031 structuredAuthnFeatureEnabled: false,
1032 want: `issuer.claimValidationRules[0].expression: Invalid value: "claims.foo == 'bar'": expression is not supported when StructuredAuthenticationConfiguration feature gate is disabled`,
1033 },
1034 {
1035 name: "CEL expression compilation error",
1036 in: []api.ClaimValidationRule{
1037 {Expression: "foo.bar"},
1038 },
1039 structuredAuthnFeatureEnabled: true,
1040 want: `issuer.claimValidationRules[0].expression: Invalid value: "foo.bar": compilation failed: ERROR: <input>:1:1: undeclared reference to 'foo' (in container '')
1041 | foo.bar
1042 | ^`,
1043 },
1044 {
1045 name: "expression does not evaluate to bool",
1046 in: []api.ClaimValidationRule{
1047 {Expression: "claims.foo"},
1048 },
1049 structuredAuthnFeatureEnabled: true,
1050 want: `issuer.claimValidationRules[0].expression: Invalid value: "claims.foo": must evaluate to bool`,
1051 },
1052 {
1053 name: "valid claim validation rule with expression",
1054 in: []api.ClaimValidationRule{
1055 {Expression: "claims.foo == 'bar'"},
1056 },
1057 structuredAuthnFeatureEnabled: true,
1058 want: "",
1059 wantCELMapper: true,
1060 },
1061 {
1062 name: "valid claim validation rule with multiple rules and email_verified check",
1063 in: []api.ClaimValidationRule{
1064 {Claim: "claim1", RequiredValue: "value1"},
1065 {Claim: "claim2", RequiredValue: "value2"},
1066 {Expression: "has(claims.email_verified)"},
1067 },
1068 structuredAuthnFeatureEnabled: true,
1069 want: "",
1070 wantUsesEmailVerifiedClaim: true,
1071 },
1072 {
1073 name: "valid claim validation rule with multiple rules and almost email_verified check",
1074 in: []api.ClaimValidationRule{
1075 {Claim: "claim1", RequiredValue: "value1"},
1076 {Claim: "claim2", RequiredValue: "value2"},
1077 {Expression: "has(claims.email_verified_)"},
1078 },
1079 structuredAuthnFeatureEnabled: true,
1080 want: "",
1081 wantUsesEmailVerifiedClaim: false,
1082 },
1083 {
1084 name: "valid claim validation rule with multiple rules",
1085 in: []api.ClaimValidationRule{
1086 {Claim: "claim1", RequiredValue: "value1"},
1087 {Claim: "claim2", RequiredValue: "claims.email_verified"}, // not a CEL expression
1088 },
1089 structuredAuthnFeatureEnabled: true,
1090 want: "",
1091 wantUsesEmailVerifiedClaim: false,
1092 },
1093 }
1094
1095 for _, tt := range testCases {
1096 t.Run(tt.name, func(t *testing.T) {
1097 state := &validationState{}
1098 got := validateClaimValidationRules(authenticationcel.NewDefaultCompiler(), state, tt.in, fldPath, tt.structuredAuthnFeatureEnabled).ToAggregate()
1099 if d := cmp.Diff(tt.want, errString(got)); d != "" {
1100 t.Fatalf("ClaimValidationRules validation mismatch (-want +got):\n%s", d)
1101 }
1102 if tt.wantCELMapper && state.mapper.ClaimValidationRules == nil {
1103 t.Fatalf("ClaimValidationRules validation mismatch: CELMapper.ClaimValidationRules is nil")
1104 }
1105 if tt.wantUsesEmailVerifiedClaim != state.usesEmailVerifiedClaim {
1106 t.Fatalf("ClaimValidationRules state.usesEmailVerifiedClaim mismatch: want %v, got %v", tt.wantUsesEmailVerifiedClaim, state.usesEmailVerifiedClaim)
1107 }
1108 })
1109 }
1110 }
1111
1112 func TestValidateClaimMappings(t *testing.T) {
1113 fldPath := field.NewPath("issuer", "claimMappings")
1114
1115 testCases := []struct {
1116 name string
1117 in api.ClaimMappings
1118 usesEmailVerifiedClaim bool
1119 structuredAuthnFeatureEnabled bool
1120 want string
1121 wantCELMapper bool
1122 }{
1123 {
1124 name: "username expression and claim are set",
1125 in: api.ClaimMappings{
1126 Username: api.PrefixedClaimOrExpression{
1127 Claim: "claim",
1128 Expression: "claims.username",
1129 },
1130 },
1131 structuredAuthnFeatureEnabled: true,
1132 want: `issuer.claimMappings.username: Invalid value: "": claim and expression can't both be set`,
1133 },
1134 {
1135 name: "username expression and claim are empty",
1136 in: api.ClaimMappings{Username: api.PrefixedClaimOrExpression{}},
1137 structuredAuthnFeatureEnabled: true,
1138 want: "issuer.claimMappings.username: Required value: claim or expression is required",
1139 },
1140 {
1141 name: "username prefix set when expression is set",
1142 in: api.ClaimMappings{
1143 Username: api.PrefixedClaimOrExpression{
1144 Expression: "claims.username",
1145 Prefix: pointer.String("prefix"),
1146 },
1147 },
1148 structuredAuthnFeatureEnabled: true,
1149 want: `issuer.claimMappings.username.prefix: Invalid value: "prefix": prefix can't be set when expression is set`,
1150 },
1151 {
1152 name: "username prefix is nil when claim is set",
1153 in: api.ClaimMappings{
1154 Username: api.PrefixedClaimOrExpression{
1155 Claim: "claim",
1156 },
1157 },
1158 structuredAuthnFeatureEnabled: true,
1159 want: `issuer.claimMappings.username.prefix: Required value: prefix is required when claim is set. It can be set to an empty string to disable prefixing`,
1160 },
1161 {
1162 name: "username expression is invalid",
1163 in: api.ClaimMappings{
1164 Username: api.PrefixedClaimOrExpression{
1165 Expression: "foo.bar",
1166 },
1167 },
1168 structuredAuthnFeatureEnabled: true,
1169 want: `issuer.claimMappings.username.expression: Invalid value: "foo.bar": compilation failed: ERROR: <input>:1:1: undeclared reference to 'foo' (in container '')
1170 | foo.bar
1171 | ^`,
1172 },
1173 {
1174 name: "groups expression and claim are set",
1175 in: api.ClaimMappings{
1176 Username: api.PrefixedClaimOrExpression{
1177 Claim: "claim",
1178 Prefix: pointer.String("prefix"),
1179 },
1180 Groups: api.PrefixedClaimOrExpression{
1181 Claim: "claim",
1182 Expression: "claims.groups",
1183 },
1184 },
1185 structuredAuthnFeatureEnabled: true,
1186 want: `issuer.claimMappings.groups: Invalid value: "": claim and expression can't both be set`,
1187 },
1188 {
1189 name: "groups prefix set when expression is set",
1190 in: api.ClaimMappings{
1191 Username: api.PrefixedClaimOrExpression{
1192 Claim: "claim",
1193 Prefix: pointer.String("prefix"),
1194 },
1195 Groups: api.PrefixedClaimOrExpression{
1196 Expression: "claims.groups",
1197 Prefix: pointer.String("prefix"),
1198 },
1199 },
1200 structuredAuthnFeatureEnabled: true,
1201 want: `issuer.claimMappings.groups.prefix: Invalid value: "prefix": prefix can't be set when expression is set`,
1202 },
1203 {
1204 name: "groups prefix is nil when claim is set",
1205 in: api.ClaimMappings{
1206 Username: api.PrefixedClaimOrExpression{
1207 Claim: "claim",
1208 Prefix: pointer.String("prefix"),
1209 },
1210 Groups: api.PrefixedClaimOrExpression{
1211 Claim: "claim",
1212 },
1213 },
1214 structuredAuthnFeatureEnabled: true,
1215 want: `issuer.claimMappings.groups.prefix: Required value: prefix is required when claim is set. It can be set to an empty string to disable prefixing`,
1216 },
1217 {
1218 name: "groups expression is invalid",
1219 in: api.ClaimMappings{
1220 Username: api.PrefixedClaimOrExpression{
1221 Claim: "claim",
1222 Prefix: pointer.String("prefix"),
1223 },
1224 Groups: api.PrefixedClaimOrExpression{
1225 Expression: "foo.bar",
1226 },
1227 },
1228 structuredAuthnFeatureEnabled: true,
1229 want: `issuer.claimMappings.groups.expression: Invalid value: "foo.bar": compilation failed: ERROR: <input>:1:1: undeclared reference to 'foo' (in container '')
1230 | foo.bar
1231 | ^`,
1232 },
1233 {
1234 name: "uid claim and expression are set",
1235 in: api.ClaimMappings{
1236 Username: api.PrefixedClaimOrExpression{
1237 Claim: "claim",
1238 Prefix: pointer.String("prefix"),
1239 },
1240 UID: api.ClaimOrExpression{
1241 Claim: "claim",
1242 Expression: "claims.uid",
1243 },
1244 },
1245 structuredAuthnFeatureEnabled: true,
1246 want: `issuer.claimMappings.uid: Invalid value: "": claim and expression can't both be set`,
1247 },
1248 {
1249 name: "uid expression is invalid",
1250 in: api.ClaimMappings{
1251 Username: api.PrefixedClaimOrExpression{
1252 Claim: "claim",
1253 Prefix: pointer.String("prefix"),
1254 },
1255 UID: api.ClaimOrExpression{
1256 Expression: "foo.bar",
1257 },
1258 },
1259 structuredAuthnFeatureEnabled: true,
1260 want: `issuer.claimMappings.uid.expression: Invalid value: "foo.bar": compilation failed: ERROR: <input>:1:1: undeclared reference to 'foo' (in container '')
1261 | foo.bar
1262 | ^`,
1263 },
1264 {
1265 name: "extra mapping key is empty",
1266 in: api.ClaimMappings{
1267 Username: api.PrefixedClaimOrExpression{
1268 Claim: "claim",
1269 Prefix: pointer.String("prefix"),
1270 },
1271 Extra: []api.ExtraMapping{
1272 {Key: "", ValueExpression: "claims.extra"},
1273 },
1274 },
1275 structuredAuthnFeatureEnabled: true,
1276 want: `issuer.claimMappings.extra[0].key: Required value`,
1277 },
1278 {
1279 name: "extra mapping value expression is empty",
1280 in: api.ClaimMappings{
1281 Username: api.PrefixedClaimOrExpression{
1282 Claim: "claim",
1283 Prefix: pointer.String("prefix"),
1284 },
1285 Extra: []api.ExtraMapping{
1286 {Key: "example.org/foo", ValueExpression: ""},
1287 },
1288 },
1289 structuredAuthnFeatureEnabled: true,
1290 want: `issuer.claimMappings.extra[0].valueExpression: Required value: valueExpression is required`,
1291 },
1292 {
1293 name: "extra mapping value expression is invalid",
1294 in: api.ClaimMappings{
1295 Username: api.PrefixedClaimOrExpression{
1296 Claim: "claim",
1297 Prefix: pointer.String("prefix"),
1298 },
1299 Extra: []api.ExtraMapping{
1300 {Key: "example.org/foo", ValueExpression: "foo.bar"},
1301 },
1302 },
1303 structuredAuthnFeatureEnabled: true,
1304 want: `issuer.claimMappings.extra[0].valueExpression: Invalid value: "foo.bar": compilation failed: ERROR: <input>:1:1: undeclared reference to 'foo' (in container '')
1305 | foo.bar
1306 | ^`,
1307 },
1308 {
1309 name: "username expression is invalid when structured authn feature is disabled",
1310 in: api.ClaimMappings{
1311 Username: api.PrefixedClaimOrExpression{
1312 Expression: "foo.bar",
1313 },
1314 },
1315 structuredAuthnFeatureEnabled: false,
1316 want: `[issuer.claimMappings.username.expression: Invalid value: "foo.bar": expression is not supported when StructuredAuthenticationConfiguration feature gate is disabled, issuer.claimMappings.username.expression: Invalid value: "foo.bar": compilation failed: ERROR: <input>:1:1: undeclared reference to 'foo' (in container '')
1317 | foo.bar
1318 | ^]`,
1319 },
1320 {
1321 name: "groups expression is invalid when structured authn feature is disabled",
1322 in: api.ClaimMappings{
1323 Username: api.PrefixedClaimOrExpression{
1324 Claim: "claim",
1325 Prefix: pointer.String("prefix"),
1326 },
1327 Groups: api.PrefixedClaimOrExpression{
1328 Expression: "foo.bar",
1329 },
1330 },
1331 structuredAuthnFeatureEnabled: false,
1332 want: `[issuer.claimMappings.groups.expression: Invalid value: "foo.bar": expression is not supported when StructuredAuthenticationConfiguration feature gate is disabled, issuer.claimMappings.groups.expression: Invalid value: "foo.bar": compilation failed: ERROR: <input>:1:1: undeclared reference to 'foo' (in container '')
1333 | foo.bar
1334 | ^]`,
1335 },
1336 {
1337 name: "uid expression is invalid when structured authn feature is disabled",
1338 in: api.ClaimMappings{
1339 Username: api.PrefixedClaimOrExpression{
1340 Claim: "claim",
1341 Prefix: pointer.String("prefix"),
1342 },
1343 UID: api.ClaimOrExpression{
1344 Expression: "foo.bar",
1345 },
1346 },
1347 structuredAuthnFeatureEnabled: false,
1348 want: `[issuer.claimMappings.uid: Invalid value: "": uid claim mapping is not supported when StructuredAuthenticationConfiguration feature gate is disabled, issuer.claimMappings.uid.expression: Invalid value: "foo.bar": compilation failed: ERROR: <input>:1:1: undeclared reference to 'foo' (in container '')
1349 | foo.bar
1350 | ^]`,
1351 },
1352 {
1353 name: "uid claim is invalid when structured authn feature is disabled",
1354 in: api.ClaimMappings{
1355 Username: api.PrefixedClaimOrExpression{
1356 Claim: "claim",
1357 Prefix: pointer.String("prefix"),
1358 },
1359 UID: api.ClaimOrExpression{
1360 Claim: "claim",
1361 },
1362 },
1363 structuredAuthnFeatureEnabled: false,
1364 want: `issuer.claimMappings.uid: Invalid value: "": uid claim mapping is not supported when StructuredAuthenticationConfiguration feature gate is disabled`,
1365 },
1366 {
1367 name: "extra mapping is invalid when structured authn feature is disabled",
1368 in: api.ClaimMappings{
1369 Username: api.PrefixedClaimOrExpression{
1370 Claim: "claim",
1371 Prefix: pointer.String("prefix"),
1372 },
1373 Extra: []api.ExtraMapping{
1374 {Key: "example.org/foo", ValueExpression: "claims.extra"},
1375 },
1376 },
1377 structuredAuthnFeatureEnabled: false,
1378 want: `issuer.claimMappings.extra: Invalid value: "": extra claim mapping is not supported when StructuredAuthenticationConfiguration feature gate is disabled`,
1379 },
1380 {
1381 name: "duplicate extra mapping key",
1382 in: api.ClaimMappings{
1383 Username: api.PrefixedClaimOrExpression{Expression: "claims.username"},
1384 Groups: api.PrefixedClaimOrExpression{Expression: "claims.groups"},
1385 Extra: []api.ExtraMapping{
1386 {Key: "example.org/foo", ValueExpression: "claims.extra"},
1387 {Key: "example.org/foo", ValueExpression: "claims.extras"},
1388 },
1389 },
1390 structuredAuthnFeatureEnabled: true,
1391 want: `issuer.claimMappings.extra[1].key: Duplicate value: "example.org/foo"`,
1392 },
1393 {
1394 name: "extra mapping key is not domain prefix path",
1395 in: api.ClaimMappings{
1396 Username: api.PrefixedClaimOrExpression{Expression: "claims.username"},
1397 Groups: api.PrefixedClaimOrExpression{Expression: "claims.groups"},
1398 Extra: []api.ExtraMapping{
1399 {Key: "foo", ValueExpression: "claims.extra"},
1400 },
1401 },
1402 structuredAuthnFeatureEnabled: true,
1403 want: `issuer.claimMappings.extra[0].key: Invalid value: "foo": must be a domain-prefixed path (such as "acme.io/foo")`,
1404 },
1405 {
1406 name: "extra mapping key is not lower case",
1407 in: api.ClaimMappings{
1408 Username: api.PrefixedClaimOrExpression{Expression: "claims.username"},
1409 Groups: api.PrefixedClaimOrExpression{Expression: "claims.groups"},
1410 Extra: []api.ExtraMapping{
1411 {Key: "example.org/Foo", ValueExpression: "claims.extra"},
1412 },
1413 },
1414 structuredAuthnFeatureEnabled: true,
1415 want: `issuer.claimMappings.extra[0].key: Invalid value: "example.org/Foo": key must be lowercase`,
1416 },
1417 {
1418 name: "extra mapping key prefix is k8.io",
1419 in: api.ClaimMappings{
1420 Username: api.PrefixedClaimOrExpression{Expression: "claims.username"},
1421 Groups: api.PrefixedClaimOrExpression{Expression: "claims.groups"},
1422 Extra: []api.ExtraMapping{
1423 {Key: "k8s.io/foo", ValueExpression: "claims.extra"},
1424 },
1425 },
1426 structuredAuthnFeatureEnabled: true,
1427 want: `issuer.claimMappings.extra[0].key: Invalid value: "k8s.io/foo": k8s.io, kubernetes.io and their subdomains are reserved for Kubernetes use`,
1428 },
1429 {
1430 name: "extra mapping key prefix contains k8.io",
1431 in: api.ClaimMappings{
1432 Username: api.PrefixedClaimOrExpression{Expression: "claims.username"},
1433 Groups: api.PrefixedClaimOrExpression{Expression: "claims.groups"},
1434 Extra: []api.ExtraMapping{
1435 {Key: "example.k8s.io/foo", ValueExpression: "claims.extra"},
1436 },
1437 },
1438 structuredAuthnFeatureEnabled: true,
1439 want: `issuer.claimMappings.extra[0].key: Invalid value: "example.k8s.io/foo": k8s.io, kubernetes.io and their subdomains are reserved for Kubernetes use`,
1440 },
1441 {
1442 name: "extra mapping key prefix is kubernetes.io",
1443 in: api.ClaimMappings{
1444 Username: api.PrefixedClaimOrExpression{Expression: "claims.username"},
1445 Groups: api.PrefixedClaimOrExpression{Expression: "claims.groups"},
1446 Extra: []api.ExtraMapping{
1447 {Key: "kubernetes.io/foo", ValueExpression: "claims.extra"},
1448 },
1449 },
1450 structuredAuthnFeatureEnabled: true,
1451 want: `issuer.claimMappings.extra[0].key: Invalid value: "kubernetes.io/foo": k8s.io, kubernetes.io and their subdomains are reserved for Kubernetes use`,
1452 },
1453 {
1454 name: "extra mapping key prefix contains kubernetes.io",
1455 in: api.ClaimMappings{
1456 Username: api.PrefixedClaimOrExpression{Expression: "claims.username"},
1457 Groups: api.PrefixedClaimOrExpression{Expression: "claims.groups"},
1458 Extra: []api.ExtraMapping{
1459 {Key: "example.kubernetes.io/foo", ValueExpression: "claims.extra"},
1460 },
1461 },
1462 structuredAuthnFeatureEnabled: true,
1463 want: `issuer.claimMappings.extra[0].key: Invalid value: "example.kubernetes.io/foo": k8s.io, kubernetes.io and their subdomains are reserved for Kubernetes use`,
1464 },
1465 {
1466 name: "extra mapping key prefix with ak8s.io, *.ak8s.io, bkubernetes.io, *.bkubernetes.io are still valid",
1467 in: api.ClaimMappings{
1468 Username: api.PrefixedClaimOrExpression{Expression: "claims.username"},
1469 Groups: api.PrefixedClaimOrExpression{Expression: "claims.groups"},
1470 Extra: []api.ExtraMapping{
1471 {Key: "ak8s.io/foo", ValueExpression: "claims.extra"},
1472 {Key: "example.ak8s.io/foo", ValueExpression: "claims.extra"},
1473 {Key: "bkubernetes.io/foo", ValueExpression: "claims.extra"},
1474 {Key: "example.bkubernetes.io/foo", ValueExpression: "claims.extra"},
1475 },
1476 },
1477 structuredAuthnFeatureEnabled: true,
1478 want: "",
1479 },
1480 {
1481 name: "valid claim mappings but uses email without verification",
1482 in: api.ClaimMappings{
1483 Username: api.PrefixedClaimOrExpression{Expression: "claims.email"},
1484 Groups: api.PrefixedClaimOrExpression{Expression: "claims.groups"},
1485 UID: api.ClaimOrExpression{Expression: "claims.uid"},
1486 Extra: []api.ExtraMapping{
1487 {Key: "example.org/foo", ValueExpression: "claims.extra"},
1488 },
1489 },
1490 structuredAuthnFeatureEnabled: true,
1491 wantCELMapper: true,
1492 want: `issuer.claimMappings.username.expression: Invalid value: "claims.email": claims.email_verified must be used in claimMappings.username.expression or claimMappings.extra[*].valueExpression or claimValidationRules[*].expression when claims.email is used in claimMappings.username.expression`,
1493 },
1494 {
1495 name: "valid claim mappings but uses email in complex CEL expression without verification",
1496 in: api.ClaimMappings{
1497 Username: api.PrefixedClaimOrExpression{Expression: "has(claims.email) ? claims.email : claims.sub"},
1498 Groups: api.PrefixedClaimOrExpression{Expression: "claims.groups"},
1499 UID: api.ClaimOrExpression{Expression: "claims.uid"},
1500 Extra: []api.ExtraMapping{
1501 {Key: "example.org/foo", ValueExpression: "claims.extra"},
1502 },
1503 },
1504 structuredAuthnFeatureEnabled: true,
1505 wantCELMapper: true,
1506 want: `issuer.claimMappings.username.expression: Invalid value: "has(claims.email) ? claims.email : claims.sub": claims.email_verified must be used in claimMappings.username.expression or claimMappings.extra[*].valueExpression or claimValidationRules[*].expression when claims.email is used in claimMappings.username.expression`,
1507 },
1508 {
1509 name: "valid claim mappings but uses email in CEL expression function without verification",
1510 in: api.ClaimMappings{
1511 Username: api.PrefixedClaimOrExpression{Expression: "claims.email.trim()"},
1512 Groups: api.PrefixedClaimOrExpression{Expression: "claims.groups"},
1513 UID: api.ClaimOrExpression{Expression: "claims.uid"},
1514 Extra: []api.ExtraMapping{
1515 {Key: "example.org/foo", ValueExpression: "claims.extra"},
1516 },
1517 },
1518 structuredAuthnFeatureEnabled: true,
1519 wantCELMapper: true,
1520 want: `issuer.claimMappings.username.expression: Invalid value: "claims.email.trim()": claims.email_verified must be used in claimMappings.username.expression or claimMappings.extra[*].valueExpression or claimValidationRules[*].expression when claims.email is used in claimMappings.username.expression`,
1521 },
1522 {
1523 name: "valid claim mappings and uses email with verification via extra",
1524 in: api.ClaimMappings{
1525 Username: api.PrefixedClaimOrExpression{Expression: "claims.email"},
1526 Groups: api.PrefixedClaimOrExpression{Expression: "claims.groups"},
1527 UID: api.ClaimOrExpression{Expression: "claims.uid"},
1528 Extra: []api.ExtraMapping{
1529 {Key: "example.org/foo", ValueExpression: "claims.email_verified"},
1530 },
1531 },
1532 structuredAuthnFeatureEnabled: true,
1533 wantCELMapper: true,
1534 want: "",
1535 },
1536 {
1537 name: "valid claim mappings and uses email with verification via extra optional",
1538 in: api.ClaimMappings{
1539 Username: api.PrefixedClaimOrExpression{Expression: "claims.email"},
1540 Groups: api.PrefixedClaimOrExpression{Expression: "claims.groups"},
1541 UID: api.ClaimOrExpression{Expression: "claims.uid"},
1542 Extra: []api.ExtraMapping{
1543 {Key: "example.org/foo", ValueExpression: `has(claims.email_verified) ? string(claims.email_verified) : "false"`},
1544 },
1545 },
1546 structuredAuthnFeatureEnabled: true,
1547 wantCELMapper: true,
1548 want: "",
1549 },
1550 {
1551 name: "valid claim mappings and almost uses email with verification via extra optional",
1552 in: api.ClaimMappings{
1553 Username: api.PrefixedClaimOrExpression{Expression: "claims.email"},
1554 Groups: api.PrefixedClaimOrExpression{Expression: "claims.groups"},
1555 UID: api.ClaimOrExpression{Expression: "claims.uid"},
1556 Extra: []api.ExtraMapping{
1557 {Key: "example.org/foo", ValueExpression: `has(claims.email_verified_) ? string(claims.email_verified_) : "false"`},
1558 },
1559 },
1560 structuredAuthnFeatureEnabled: true,
1561 wantCELMapper: true,
1562 want: `issuer.claimMappings.username.expression: Invalid value: "claims.email": claims.email_verified must be used in claimMappings.username.expression or claimMappings.extra[*].valueExpression or claimValidationRules[*].expression when claims.email is used in claimMappings.username.expression`,
1563 },
1564 {
1565 name: "valid claim mappings and uses email with verification via hasVerifiedEmail",
1566 in: api.ClaimMappings{
1567 Username: api.PrefixedClaimOrExpression{Expression: "claims.email"},
1568 Groups: api.PrefixedClaimOrExpression{Expression: "claims.groups"},
1569 UID: api.ClaimOrExpression{Expression: "claims.uid"},
1570 Extra: []api.ExtraMapping{
1571 {Key: "example.org/foo", ValueExpression: "claims.extra"},
1572 },
1573 },
1574 usesEmailVerifiedClaim: true,
1575 structuredAuthnFeatureEnabled: true,
1576 wantCELMapper: true,
1577 want: "",
1578 },
1579 {
1580 name: "valid claim mappings that almost use claims.email",
1581 in: api.ClaimMappings{
1582 Username: api.PrefixedClaimOrExpression{Expression: "claims.email_"},
1583 Groups: api.PrefixedClaimOrExpression{Expression: "claims.groups"},
1584 UID: api.ClaimOrExpression{Expression: "claims.uid"},
1585 Extra: []api.ExtraMapping{
1586 {Key: "example.org/foo", ValueExpression: "claims.extra"},
1587 },
1588 },
1589 structuredAuthnFeatureEnabled: true,
1590 wantCELMapper: true,
1591 want: "",
1592 },
1593 {
1594 name: "valid claim mappings that almost use claims.email via nesting",
1595 in: api.ClaimMappings{
1596 Username: api.PrefixedClaimOrExpression{Expression: "claims.other.claims.email"},
1597 Groups: api.PrefixedClaimOrExpression{Expression: "claims.groups"},
1598 UID: api.ClaimOrExpression{Expression: "claims.uid"},
1599 Extra: []api.ExtraMapping{
1600 {Key: "example.org/foo", ValueExpression: "claims.extra"},
1601 },
1602 },
1603 structuredAuthnFeatureEnabled: true,
1604 wantCELMapper: true,
1605 want: "",
1606 },
1607 {
1608 name: "valid claim mappings",
1609 in: api.ClaimMappings{
1610 Username: api.PrefixedClaimOrExpression{Expression: "claims.username"},
1611 Groups: api.PrefixedClaimOrExpression{Expression: "claims.groups"},
1612 UID: api.ClaimOrExpression{Expression: "claims.uid"},
1613 Extra: []api.ExtraMapping{
1614 {Key: "example.org/foo", ValueExpression: "claims.extra"},
1615 },
1616 },
1617 structuredAuthnFeatureEnabled: true,
1618 wantCELMapper: true,
1619 want: "",
1620 },
1621 }
1622
1623 for _, tt := range testCases {
1624 t.Run(tt.name, func(t *testing.T) {
1625 state := &validationState{usesEmailVerifiedClaim: tt.usesEmailVerifiedClaim}
1626 got := validateClaimMappings(authenticationcel.NewDefaultCompiler(), state, tt.in, fldPath, tt.structuredAuthnFeatureEnabled).ToAggregate()
1627 if d := cmp.Diff(tt.want, errString(got)); d != "" {
1628 fmt.Println(errString(got))
1629 t.Fatalf("ClaimMappings validation mismatch (-want +got):\n%s", d)
1630 }
1631 if tt.wantCELMapper {
1632 if len(tt.in.Username.Expression) > 0 && state.mapper.Username == nil {
1633 t.Fatalf("ClaimMappings validation mismatch: CELMapper.Username is nil")
1634 }
1635 if len(tt.in.Groups.Expression) > 0 && state.mapper.Groups == nil {
1636 t.Fatalf("ClaimMappings validation mismatch: CELMapper.Groups is nil")
1637 }
1638 if len(tt.in.UID.Expression) > 0 && state.mapper.UID == nil {
1639 t.Fatalf("ClaimMappings validation mismatch: CELMapper.UID is nil")
1640 }
1641 if len(tt.in.Extra) > 0 && state.mapper.Extra == nil {
1642 t.Fatalf("ClaimMappings validation mismatch: CELMapper.Extra is nil")
1643 }
1644 }
1645 })
1646 }
1647 }
1648
1649 func TestValidateUserValidationRules(t *testing.T) {
1650 fldPath := field.NewPath("issuer", "userValidationRules")
1651
1652 testCases := []struct {
1653 name string
1654 in []api.UserValidationRule
1655 structuredAuthnFeatureEnabled bool
1656 want string
1657 wantCELMapper bool
1658 }{
1659 {
1660 name: "user info validation rule, expression is empty",
1661 in: []api.UserValidationRule{{}},
1662 structuredAuthnFeatureEnabled: true,
1663 want: "issuer.userValidationRules[0].expression: Required value: expression is required",
1664 },
1665 {
1666 name: "duplicate expression",
1667 in: []api.UserValidationRule{
1668 {Expression: "user.username == 'foo'"},
1669 {Expression: "user.username == 'foo'"},
1670 },
1671 structuredAuthnFeatureEnabled: true,
1672 want: `issuer.userValidationRules[1].expression: Duplicate value: "user.username == 'foo'"`,
1673 },
1674 {
1675 name: "user validation rule is invalid when structured authn feature is disabled",
1676 in: []api.UserValidationRule{
1677 {Expression: "user.username == 'foo'"},
1678 },
1679 structuredAuthnFeatureEnabled: false,
1680 want: `issuer.userValidationRules: Invalid value: "": user validation rules are not supported when StructuredAuthenticationConfiguration feature gate is disabled`,
1681 },
1682 {
1683 name: "expression is invalid",
1684 in: []api.UserValidationRule{
1685 {Expression: "foo.bar"},
1686 },
1687 structuredAuthnFeatureEnabled: true,
1688 want: `issuer.userValidationRules[0].expression: Invalid value: "foo.bar": compilation failed: ERROR: <input>:1:1: undeclared reference to 'foo' (in container '')
1689 | foo.bar
1690 | ^`,
1691 },
1692 {
1693 name: "expression does not return bool",
1694 in: []api.UserValidationRule{
1695 {Expression: "user.username"},
1696 },
1697 structuredAuthnFeatureEnabled: true,
1698 want: `issuer.userValidationRules[0].expression: Invalid value: "user.username": must evaluate to bool`,
1699 },
1700 {
1701 name: "valid user info validation rule",
1702 in: []api.UserValidationRule{
1703 {Expression: "user.username == 'foo'"},
1704 {Expression: "!user.username.startsWith('system:')", Message: "username cannot used reserved system: prefix"},
1705 },
1706 structuredAuthnFeatureEnabled: true,
1707 want: "",
1708 wantCELMapper: true,
1709 },
1710 }
1711
1712 for _, tt := range testCases {
1713 t.Run(tt.name, func(t *testing.T) {
1714 state := &validationState{}
1715 got := validateUserValidationRules(authenticationcel.NewDefaultCompiler(), state, tt.in, fldPath, tt.structuredAuthnFeatureEnabled).ToAggregate()
1716 if d := cmp.Diff(tt.want, errString(got)); d != "" {
1717 t.Fatalf("UserValidationRules validation mismatch (-want +got):\n%s", d)
1718 }
1719 if tt.wantCELMapper && state.mapper.UserValidationRules == nil {
1720 t.Fatalf("UserValidationRules validation mismatch: CELMapper.UserValidationRules is nil")
1721 }
1722 })
1723 }
1724 }
1725
1726 func errString(errs errors.Aggregate) string {
1727 if errs != nil {
1728 return errs.Error()
1729 }
1730 return ""
1731 }
1732
1733 type (
1734 test struct {
1735 name string
1736 configuration api.AuthorizationConfiguration
1737 expectedErrList field.ErrorList
1738 knownTypes sets.Set[string]
1739 repeatableTypes sets.Set[string]
1740 }
1741 )
1742
1743 func TestValidateAuthorizationConfiguration(t *testing.T) {
1744 badKubeConfigFile := "../some/relative/path/kubeconfig"
1745
1746 tempKubeConfigFile, err := os.CreateTemp("/tmp", "kubeconfig")
1747 if err != nil {
1748 t.Fatalf("failed to set up temp file: %v", err)
1749 }
1750 tempKubeConfigFilePath := tempKubeConfigFile.Name()
1751 defer os.Remove(tempKubeConfigFilePath)
1752
1753 tests := []test{
1754 {
1755 name: "atleast one authorizer should be defined",
1756 configuration: api.AuthorizationConfiguration{
1757 Authorizers: []api.AuthorizerConfiguration{},
1758 },
1759 expectedErrList: field.ErrorList{field.Required(field.NewPath("authorizers"), "at least one authorization mode must be defined")},
1760 knownTypes: sets.New[string](),
1761 repeatableTypes: sets.New[string](),
1762 },
1763 {
1764 name: "type and name are required if an authorizer is defined",
1765 configuration: api.AuthorizationConfiguration{
1766 Authorizers: []api.AuthorizerConfiguration{
1767 {},
1768 },
1769 },
1770 expectedErrList: field.ErrorList{field.Required(field.NewPath("type"), "")},
1771 knownTypes: sets.New("Webhook"),
1772 repeatableTypes: sets.New("Webhook"),
1773 },
1774 {
1775 name: "authorizer names should be of non-zero length",
1776 configuration: api.AuthorizationConfiguration{
1777 Authorizers: []api.AuthorizerConfiguration{
1778 {
1779 Type: "Foo",
1780 Name: "",
1781 },
1782 },
1783 },
1784 expectedErrList: field.ErrorList{field.Required(field.NewPath("name"), "")},
1785 knownTypes: sets.New("Foo"),
1786 repeatableTypes: sets.New("Webhook"),
1787 },
1788 {
1789 name: "authorizer names should be unique",
1790 configuration: api.AuthorizationConfiguration{
1791 Authorizers: []api.AuthorizerConfiguration{
1792 {
1793 Type: "Foo",
1794 Name: "foo",
1795 },
1796 {
1797 Type: "Bar",
1798 Name: "foo",
1799 },
1800 },
1801 },
1802 expectedErrList: field.ErrorList{field.Duplicate(field.NewPath("name"), "foo")},
1803 knownTypes: sets.New("Foo", "Bar"),
1804 repeatableTypes: sets.New("Webhook"),
1805 },
1806 {
1807 name: "authorizer names should be DNS1123 labels",
1808 configuration: api.AuthorizationConfiguration{
1809 Authorizers: []api.AuthorizerConfiguration{
1810 {
1811 Type: "Foo",
1812 Name: "myauthorizer",
1813 },
1814 },
1815 },
1816 expectedErrList: field.ErrorList{},
1817 knownTypes: sets.New("Foo"),
1818 repeatableTypes: sets.New("Webhook"),
1819 },
1820 {
1821 name: "authorizer names should be DNS1123 subdomains",
1822 configuration: api.AuthorizationConfiguration{
1823 Authorizers: []api.AuthorizerConfiguration{
1824 {
1825 Type: "Foo",
1826 Name: "foo.example.domain",
1827 },
1828 },
1829 },
1830 expectedErrList: field.ErrorList{},
1831 knownTypes: sets.New("Foo"),
1832 repeatableTypes: sets.New("Webhook"),
1833 },
1834 {
1835 name: "authorizer names should not be invalid DNS1123 labels or subdomains",
1836 configuration: api.AuthorizationConfiguration{
1837 Authorizers: []api.AuthorizerConfiguration{
1838 {
1839 Type: "Foo",
1840 Name: "FOO.example.domain",
1841 },
1842 },
1843 },
1844 expectedErrList: field.ErrorList{field.Invalid(field.NewPath("name"), "FOO.example.domain", "")},
1845 knownTypes: sets.New("Foo"),
1846 repeatableTypes: sets.New("Webhook"),
1847 },
1848 {
1849 name: "bare minimum configuration with Webhook",
1850 configuration: api.AuthorizationConfiguration{
1851 Authorizers: []api.AuthorizerConfiguration{
1852 {
1853 Type: "Webhook",
1854 Name: "default",
1855 Webhook: &api.WebhookConfiguration{
1856 Timeout: metav1.Duration{Duration: 5 * time.Second},
1857 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
1858 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
1859 FailurePolicy: "NoOpinion",
1860 SubjectAccessReviewVersion: "v1",
1861 MatchConditionSubjectAccessReviewVersion: "v1",
1862 ConnectionInfo: api.WebhookConnectionInfo{
1863 Type: "InClusterConfig",
1864 },
1865 },
1866 },
1867 },
1868 },
1869 expectedErrList: field.ErrorList{},
1870 knownTypes: sets.New("Webhook"),
1871 repeatableTypes: sets.New("Webhook"),
1872 },
1873 {
1874 name: "bare minimum configuration with Webhook and MatchConditions",
1875 configuration: api.AuthorizationConfiguration{
1876 Authorizers: []api.AuthorizerConfiguration{
1877 {
1878 Type: "Webhook",
1879 Name: "default",
1880 Webhook: &api.WebhookConfiguration{
1881 Timeout: metav1.Duration{Duration: 5 * time.Second},
1882 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
1883 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
1884 FailurePolicy: "NoOpinion",
1885 SubjectAccessReviewVersion: "v1",
1886 MatchConditionSubjectAccessReviewVersion: "v1",
1887 ConnectionInfo: api.WebhookConnectionInfo{
1888 Type: "InClusterConfig",
1889 },
1890 MatchConditions: []api.WebhookMatchCondition{
1891 {
1892 Expression: "has(request.resourceAttributes) && request.resourceAttributes.namespace == 'kube-system'",
1893 },
1894 {
1895 Expression: "request.user == 'admin'",
1896 },
1897 },
1898 },
1899 },
1900 },
1901 },
1902 expectedErrList: field.ErrorList{},
1903 knownTypes: sets.New("Webhook"),
1904 repeatableTypes: sets.New("Webhook"),
1905 },
1906 {
1907 name: "bare minimum configuration with multiple webhooks",
1908 configuration: api.AuthorizationConfiguration{
1909 Authorizers: []api.AuthorizerConfiguration{
1910 {
1911 Type: "Webhook",
1912 Name: "default",
1913 Webhook: &api.WebhookConfiguration{
1914 Timeout: metav1.Duration{Duration: 5 * time.Second},
1915 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
1916 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
1917 FailurePolicy: "NoOpinion",
1918 SubjectAccessReviewVersion: "v1",
1919 MatchConditionSubjectAccessReviewVersion: "v1",
1920 ConnectionInfo: api.WebhookConnectionInfo{
1921 Type: "InClusterConfig",
1922 },
1923 },
1924 },
1925 {
1926 Type: "Webhook",
1927 Name: "second-webhook",
1928 Webhook: &api.WebhookConfiguration{
1929 Timeout: metav1.Duration{Duration: 5 * time.Second},
1930 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
1931 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
1932 FailurePolicy: "NoOpinion",
1933 SubjectAccessReviewVersion: "v1",
1934 MatchConditionSubjectAccessReviewVersion: "v1",
1935 ConnectionInfo: api.WebhookConnectionInfo{
1936 Type: "InClusterConfig",
1937 },
1938 },
1939 },
1940 },
1941 },
1942 expectedErrList: field.ErrorList{},
1943 knownTypes: sets.New("Webhook"),
1944 repeatableTypes: sets.New("Webhook"),
1945 },
1946 {
1947 name: "configuration with unknown types",
1948 configuration: api.AuthorizationConfiguration{
1949 Authorizers: []api.AuthorizerConfiguration{
1950 {
1951 Type: "Foo",
1952 },
1953 },
1954 },
1955 expectedErrList: field.ErrorList{field.NotSupported(field.NewPath("type"), "Foo", []string{"..."})},
1956 knownTypes: sets.New("Webhook"),
1957 repeatableTypes: sets.New("Webhook"),
1958 },
1959 {
1960 name: "configuration with not repeatable types",
1961 configuration: api.AuthorizationConfiguration{
1962 Authorizers: []api.AuthorizerConfiguration{
1963 {
1964 Type: "Foo",
1965 Name: "foo-1",
1966 },
1967 {
1968 Type: "Foo",
1969 Name: "foo-2",
1970 },
1971 },
1972 },
1973 expectedErrList: field.ErrorList{field.Duplicate(field.NewPath("type"), "Foo")},
1974 knownTypes: sets.New("Foo"),
1975 repeatableTypes: sets.New("Webhook"),
1976 },
1977 {
1978 name: "when type=Webhook, webhook needs to be defined",
1979 configuration: api.AuthorizationConfiguration{
1980 Authorizers: []api.AuthorizerConfiguration{
1981 {
1982 Type: "Webhook",
1983 Name: "default",
1984 },
1985 },
1986 },
1987 expectedErrList: field.ErrorList{field.Required(field.NewPath("webhook"), "required when type=Webhook")},
1988 knownTypes: sets.New("Webhook"),
1989 repeatableTypes: sets.New("Webhook"),
1990 },
1991 {
1992 name: "when type!=Webhook, webhooks needs to be nil",
1993 configuration: api.AuthorizationConfiguration{
1994 Authorizers: []api.AuthorizerConfiguration{
1995 {
1996 Type: "Foo",
1997 Name: "foo",
1998 Webhook: &api.WebhookConfiguration{},
1999 },
2000 },
2001 },
2002 expectedErrList: field.ErrorList{field.Invalid(field.NewPath("webhook"), "non-null", "may only be specified when type=Webhook")},
2003 knownTypes: sets.New("Foo"),
2004 repeatableTypes: sets.New("Webhook"),
2005 },
2006 {
2007 name: "timeout should be specified",
2008 configuration: api.AuthorizationConfiguration{
2009 Authorizers: []api.AuthorizerConfiguration{
2010 {
2011 Type: "Webhook",
2012 Name: "default",
2013 Webhook: &api.WebhookConfiguration{
2014 FailurePolicy: "NoOpinion",
2015 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
2016 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
2017 SubjectAccessReviewVersion: "v1",
2018 MatchConditionSubjectAccessReviewVersion: "v1",
2019 ConnectionInfo: api.WebhookConnectionInfo{
2020 Type: "InClusterConfig",
2021 },
2022 },
2023 },
2024 },
2025 },
2026 expectedErrList: field.ErrorList{field.Required(field.NewPath("timeout"), "")},
2027 knownTypes: sets.New("Webhook"),
2028 repeatableTypes: sets.New("Webhook"),
2029 },
2030 //
2031 {
2032 name: "timeout shouldn't be zero",
2033 configuration: api.AuthorizationConfiguration{
2034 Authorizers: []api.AuthorizerConfiguration{
2035 {
2036 Type: "Webhook",
2037 Name: "default",
2038 Webhook: &api.WebhookConfiguration{
2039 FailurePolicy: "NoOpinion",
2040 Timeout: metav1.Duration{Duration: 0 * time.Second},
2041 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
2042 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
2043 SubjectAccessReviewVersion: "v1",
2044 MatchConditionSubjectAccessReviewVersion: "v1",
2045 ConnectionInfo: api.WebhookConnectionInfo{
2046 Type: "InClusterConfig",
2047 },
2048 },
2049 },
2050 },
2051 },
2052 expectedErrList: field.ErrorList{field.Required(field.NewPath("timeout"), "")},
2053 knownTypes: sets.New("Webhook"),
2054 repeatableTypes: sets.New("Webhook"),
2055 },
2056 {
2057 name: "timeout shouldn't be negative",
2058 configuration: api.AuthorizationConfiguration{
2059 Authorizers: []api.AuthorizerConfiguration{
2060 {
2061 Type: "Webhook",
2062 Name: "default",
2063 Webhook: &api.WebhookConfiguration{
2064 FailurePolicy: "NoOpinion",
2065 Timeout: metav1.Duration{Duration: -30 * time.Second},
2066 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
2067 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
2068 SubjectAccessReviewVersion: "v1",
2069 MatchConditionSubjectAccessReviewVersion: "v1",
2070 ConnectionInfo: api.WebhookConnectionInfo{
2071 Type: "InClusterConfig",
2072 },
2073 },
2074 },
2075 },
2076 },
2077 expectedErrList: field.ErrorList{field.Invalid(field.NewPath("timeout"), time.Duration(-30*time.Second).String(), "must be > 0s and <= 30s")},
2078 knownTypes: sets.New("Webhook"),
2079 repeatableTypes: sets.New("Webhook"),
2080 },
2081 {
2082 name: "timeout shouldn't be greater than 30seconds",
2083 configuration: api.AuthorizationConfiguration{
2084 Authorizers: []api.AuthorizerConfiguration{
2085 {
2086 Type: "Webhook",
2087 Name: "default",
2088 Webhook: &api.WebhookConfiguration{
2089 FailurePolicy: "NoOpinion",
2090 Timeout: metav1.Duration{Duration: 60 * time.Second},
2091 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
2092 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
2093 SubjectAccessReviewVersion: "v1",
2094 MatchConditionSubjectAccessReviewVersion: "v1",
2095 ConnectionInfo: api.WebhookConnectionInfo{
2096 Type: "InClusterConfig",
2097 },
2098 },
2099 },
2100 },
2101 },
2102 expectedErrList: field.ErrorList{field.Invalid(field.NewPath("timeout"), time.Duration(60*time.Second).String(), "must be > 0s and <= 30s")},
2103 knownTypes: sets.New("Webhook"),
2104 repeatableTypes: sets.New("Webhook"),
2105 },
2106 {
2107 name: "authorizedTTL should be defined ",
2108 configuration: api.AuthorizationConfiguration{
2109 Authorizers: []api.AuthorizerConfiguration{
2110 {
2111 Type: "Webhook",
2112 Name: "default",
2113 Webhook: &api.WebhookConfiguration{
2114 FailurePolicy: "NoOpinion",
2115 Timeout: metav1.Duration{Duration: 5 * time.Second},
2116 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
2117 SubjectAccessReviewVersion: "v1",
2118 MatchConditionSubjectAccessReviewVersion: "v1",
2119 ConnectionInfo: api.WebhookConnectionInfo{
2120 Type: "InClusterConfig",
2121 },
2122 },
2123 },
2124 },
2125 },
2126 expectedErrList: field.ErrorList{field.Required(field.NewPath("authorizedTTL"), "")},
2127 knownTypes: sets.New("Webhook"),
2128 repeatableTypes: sets.New("Webhook"),
2129 },
2130 {
2131 name: "authorizedTTL shouldn't be negative",
2132 configuration: api.AuthorizationConfiguration{
2133 Authorizers: []api.AuthorizerConfiguration{
2134 {
2135 Type: "Webhook",
2136 Name: "default",
2137 Webhook: &api.WebhookConfiguration{
2138 FailurePolicy: "NoOpinion",
2139 Timeout: metav1.Duration{Duration: 5 * time.Second},
2140 AuthorizedTTL: metav1.Duration{Duration: -30 * time.Second},
2141 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
2142 SubjectAccessReviewVersion: "v1",
2143 MatchConditionSubjectAccessReviewVersion: "v1",
2144 ConnectionInfo: api.WebhookConnectionInfo{
2145 Type: "InClusterConfig",
2146 },
2147 },
2148 },
2149 },
2150 },
2151 expectedErrList: field.ErrorList{field.Invalid(field.NewPath("authorizedTTL"), time.Duration(-30*time.Second).String(), "must be > 0s")},
2152 knownTypes: sets.New("Webhook"),
2153 repeatableTypes: sets.New("Webhook"),
2154 },
2155 {
2156 name: "unauthorizedTTL should be defined ",
2157 configuration: api.AuthorizationConfiguration{
2158 Authorizers: []api.AuthorizerConfiguration{
2159 {
2160 Type: "Webhook",
2161 Name: "default",
2162 Webhook: &api.WebhookConfiguration{
2163 FailurePolicy: "NoOpinion",
2164 Timeout: metav1.Duration{Duration: 5 * time.Second},
2165 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
2166 SubjectAccessReviewVersion: "v1",
2167 MatchConditionSubjectAccessReviewVersion: "v1",
2168 ConnectionInfo: api.WebhookConnectionInfo{
2169 Type: "InClusterConfig",
2170 },
2171 },
2172 },
2173 },
2174 },
2175 expectedErrList: field.ErrorList{field.Required(field.NewPath("unauthorizedTTL"), "")},
2176 knownTypes: sets.New("Webhook"),
2177 repeatableTypes: sets.New("Webhook"),
2178 },
2179 {
2180 name: "unauthorizedTTL shouldn't be negative",
2181 configuration: api.AuthorizationConfiguration{
2182 Authorizers: []api.AuthorizerConfiguration{
2183 {
2184 Type: "Webhook",
2185 Name: "default",
2186 Webhook: &api.WebhookConfiguration{
2187 FailurePolicy: "NoOpinion",
2188 Timeout: metav1.Duration{Duration: 5 * time.Second},
2189 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
2190 UnauthorizedTTL: metav1.Duration{Duration: -30 * time.Second},
2191 SubjectAccessReviewVersion: "v1",
2192 MatchConditionSubjectAccessReviewVersion: "v1",
2193 ConnectionInfo: api.WebhookConnectionInfo{
2194 Type: "InClusterConfig",
2195 },
2196 },
2197 },
2198 },
2199 },
2200 expectedErrList: field.ErrorList{field.Invalid(field.NewPath("unauthorizedTTL"), time.Duration(-30*time.Second).String(), "must be > 0s")},
2201 knownTypes: sets.New("Webhook"),
2202 repeatableTypes: sets.New("Webhook"),
2203 },
2204 {
2205 name: "SAR should be defined",
2206 configuration: api.AuthorizationConfiguration{
2207 Authorizers: []api.AuthorizerConfiguration{
2208 {
2209 Type: "Webhook",
2210 Name: "default",
2211 Webhook: &api.WebhookConfiguration{
2212 Timeout: metav1.Duration{Duration: 5 * time.Second},
2213 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
2214 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
2215 MatchConditionSubjectAccessReviewVersion: "v1",
2216 FailurePolicy: "NoOpinion",
2217 ConnectionInfo: api.WebhookConnectionInfo{
2218 Type: "InClusterConfig",
2219 },
2220 },
2221 },
2222 },
2223 },
2224 expectedErrList: field.ErrorList{field.Required(field.NewPath("subjectAccessReviewVersion"), "")},
2225 knownTypes: sets.New("Webhook"),
2226 repeatableTypes: sets.New("Webhook"),
2227 },
2228 {
2229 name: "SAR should be one of v1 and v1beta1",
2230 configuration: api.AuthorizationConfiguration{
2231 Authorizers: []api.AuthorizerConfiguration{
2232 {
2233 Type: "Webhook",
2234 Name: "default",
2235 Webhook: &api.WebhookConfiguration{
2236 Timeout: metav1.Duration{Duration: 5 * time.Second},
2237 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
2238 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
2239 FailurePolicy: "NoOpinion",
2240 SubjectAccessReviewVersion: "v2beta1",
2241 MatchConditionSubjectAccessReviewVersion: "v1",
2242 ConnectionInfo: api.WebhookConnectionInfo{
2243 Type: "InClusterConfig",
2244 },
2245 },
2246 },
2247 },
2248 },
2249 expectedErrList: field.ErrorList{field.NotSupported(field.NewPath("subjectAccessReviewVersion"), "v2beta1", []string{"v1", "v1beta1"})},
2250 knownTypes: sets.New("Webhook"),
2251 repeatableTypes: sets.New("Webhook"),
2252 },
2253 {
2254 name: "MatchConditionSAR should be defined",
2255 configuration: api.AuthorizationConfiguration{
2256 Authorizers: []api.AuthorizerConfiguration{
2257 {
2258 Type: "Webhook",
2259 Name: "default",
2260 Webhook: &api.WebhookConfiguration{
2261 Timeout: metav1.Duration{Duration: 5 * time.Second},
2262 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
2263 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
2264 FailurePolicy: "NoOpinion",
2265 SubjectAccessReviewVersion: "v1",
2266 ConnectionInfo: api.WebhookConnectionInfo{
2267 Type: "InClusterConfig",
2268 },
2269 MatchConditions: []api.WebhookMatchCondition{{Expression: "true"}},
2270 },
2271 },
2272 },
2273 },
2274 expectedErrList: field.ErrorList{field.Required(field.NewPath("matchConditionSubjectAccessReviewVersion"), "")},
2275 knownTypes: sets.New("Webhook"),
2276 repeatableTypes: sets.New("Webhook"),
2277 },
2278 {
2279 name: "MatchConditionSAR must not be anything other than v1",
2280 configuration: api.AuthorizationConfiguration{
2281 Authorizers: []api.AuthorizerConfiguration{
2282 {
2283 Type: "Webhook",
2284 Name: "default",
2285 Webhook: &api.WebhookConfiguration{
2286 Timeout: metav1.Duration{Duration: 5 * time.Second},
2287 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
2288 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
2289 FailurePolicy: "NoOpinion",
2290 SubjectAccessReviewVersion: "v1",
2291 MatchConditionSubjectAccessReviewVersion: "v1beta1",
2292 ConnectionInfo: api.WebhookConnectionInfo{
2293 Type: "InClusterConfig",
2294 },
2295 },
2296 },
2297 },
2298 },
2299 expectedErrList: field.ErrorList{field.NotSupported(field.NewPath("matchConditionSubjectAccessReviewVersion"), "v1beta1", []string{"v1"})},
2300 knownTypes: sets.New("Webhook"),
2301 repeatableTypes: sets.New("Webhook"),
2302 },
2303 {
2304 name: "failurePolicy should be defined",
2305 configuration: api.AuthorizationConfiguration{
2306 Authorizers: []api.AuthorizerConfiguration{
2307 {
2308 Type: "Webhook",
2309 Name: "default",
2310 Webhook: &api.WebhookConfiguration{
2311 Timeout: metav1.Duration{Duration: 5 * time.Second},
2312 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
2313 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
2314 SubjectAccessReviewVersion: "v1",
2315 MatchConditionSubjectAccessReviewVersion: "v1",
2316 ConnectionInfo: api.WebhookConnectionInfo{
2317 Type: "InClusterConfig",
2318 },
2319 },
2320 },
2321 },
2322 },
2323 expectedErrList: field.ErrorList{field.Required(field.NewPath("failurePolicy"), "")},
2324 knownTypes: sets.New("Webhook"),
2325 repeatableTypes: sets.New("Webhook"),
2326 },
2327 {
2328 name: "failurePolicy should be one of \"NoOpinion\" or \"Deny\"",
2329 configuration: api.AuthorizationConfiguration{
2330 Authorizers: []api.AuthorizerConfiguration{
2331 {
2332 Type: "Webhook",
2333 Name: "default",
2334 Webhook: &api.WebhookConfiguration{
2335 Timeout: metav1.Duration{Duration: 5 * time.Second},
2336 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
2337 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
2338 FailurePolicy: "AlwaysAllow",
2339 SubjectAccessReviewVersion: "v1",
2340 MatchConditionSubjectAccessReviewVersion: "v1",
2341 ConnectionInfo: api.WebhookConnectionInfo{
2342 Type: "InClusterConfig",
2343 },
2344 },
2345 },
2346 },
2347 },
2348 expectedErrList: field.ErrorList{field.NotSupported(field.NewPath("failurePolicy"), "AlwaysAllow", []string{"NoOpinion", "Deny"})},
2349 knownTypes: sets.New("Webhook"),
2350 repeatableTypes: sets.New("Webhook"),
2351 },
2352 {
2353 name: "connectionInfo should be defined",
2354 configuration: api.AuthorizationConfiguration{
2355 Authorizers: []api.AuthorizerConfiguration{
2356 {
2357 Type: "Webhook",
2358 Name: "default",
2359 Webhook: &api.WebhookConfiguration{
2360 Timeout: metav1.Duration{Duration: 5 * time.Second},
2361 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
2362 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
2363 FailurePolicy: "NoOpinion",
2364 SubjectAccessReviewVersion: "v1",
2365 MatchConditionSubjectAccessReviewVersion: "v1",
2366 },
2367 },
2368 },
2369 },
2370 expectedErrList: field.ErrorList{field.Required(field.NewPath("connectionInfo"), "")},
2371 knownTypes: sets.New("Webhook"),
2372 repeatableTypes: sets.New("Webhook"),
2373 },
2374 {
2375 name: "connectionInfo should be one of InClusterConfig or KubeConfigFile",
2376 configuration: api.AuthorizationConfiguration{
2377 Authorizers: []api.AuthorizerConfiguration{
2378 {
2379 Type: "Webhook",
2380 Name: "default",
2381 Webhook: &api.WebhookConfiguration{
2382 Timeout: metav1.Duration{Duration: 5 * time.Second},
2383 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
2384 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
2385 FailurePolicy: "NoOpinion",
2386 SubjectAccessReviewVersion: "v1",
2387 MatchConditionSubjectAccessReviewVersion: "v1",
2388 ConnectionInfo: api.WebhookConnectionInfo{
2389 Type: "ExternalClusterConfig",
2390 },
2391 },
2392 },
2393 },
2394 },
2395 expectedErrList: field.ErrorList{
2396 field.NotSupported(field.NewPath("connectionInfo"), api.WebhookConnectionInfo{Type: "ExternalClusterConfig"}, []string{"InClusterConfig", "KubeConfigFile"}),
2397 },
2398 knownTypes: sets.New("Webhook"),
2399 repeatableTypes: sets.New("Webhook"),
2400 },
2401 {
2402 name: "if connectionInfo=InClusterConfig, then kubeConfigFile should be nil",
2403 configuration: api.AuthorizationConfiguration{
2404 Authorizers: []api.AuthorizerConfiguration{
2405 {
2406 Type: "Webhook",
2407 Name: "default",
2408 Webhook: &api.WebhookConfiguration{
2409 Timeout: metav1.Duration{Duration: 5 * time.Second},
2410 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
2411 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
2412 FailurePolicy: "NoOpinion",
2413 SubjectAccessReviewVersion: "v1",
2414 MatchConditionSubjectAccessReviewVersion: "v1",
2415 ConnectionInfo: api.WebhookConnectionInfo{
2416 Type: "InClusterConfig",
2417 KubeConfigFile: new(string),
2418 },
2419 },
2420 },
2421 },
2422 },
2423 expectedErrList: field.ErrorList{
2424 field.Invalid(field.NewPath("connectionInfo", "kubeConfigFile"), "", "can only be set when type=KubeConfigFile"),
2425 },
2426 knownTypes: sets.New("Webhook"),
2427 repeatableTypes: sets.New("Webhook"),
2428 },
2429 {
2430 name: "if connectionInfo=KubeConfigFile, then KubeConfigFile should be defined",
2431 configuration: api.AuthorizationConfiguration{
2432 Authorizers: []api.AuthorizerConfiguration{
2433 {
2434 Type: "Webhook",
2435 Name: "default",
2436 Webhook: &api.WebhookConfiguration{
2437 Timeout: metav1.Duration{Duration: 5 * time.Second},
2438 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
2439 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
2440 FailurePolicy: "NoOpinion",
2441 SubjectAccessReviewVersion: "v1",
2442 MatchConditionSubjectAccessReviewVersion: "v1",
2443 ConnectionInfo: api.WebhookConnectionInfo{
2444 Type: "KubeConfigFile",
2445 },
2446 },
2447 },
2448 },
2449 },
2450 expectedErrList: field.ErrorList{field.Required(field.NewPath("kubeConfigFile"), "")},
2451 knownTypes: sets.New("Webhook"),
2452 repeatableTypes: sets.New("Webhook"),
2453 },
2454 {
2455 name: "if connectionInfo=KubeConfigFile, then KubeConfigFile should be defined, must be an absolute path, should exist, shouldn't be a symlink",
2456 configuration: api.AuthorizationConfiguration{
2457 Authorizers: []api.AuthorizerConfiguration{
2458 {
2459 Type: "Webhook",
2460 Name: "default",
2461 Webhook: &api.WebhookConfiguration{
2462 Timeout: metav1.Duration{Duration: 5 * time.Second},
2463 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
2464 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
2465 FailurePolicy: "NoOpinion",
2466 SubjectAccessReviewVersion: "v1",
2467 MatchConditionSubjectAccessReviewVersion: "v1",
2468 ConnectionInfo: api.WebhookConnectionInfo{
2469 Type: "KubeConfigFile",
2470 KubeConfigFile: &badKubeConfigFile,
2471 },
2472 },
2473 },
2474 },
2475 },
2476 expectedErrList: field.ErrorList{field.Invalid(field.NewPath("kubeConfigFile"), badKubeConfigFile, "must be an absolute path")},
2477 knownTypes: sets.New("Webhook"),
2478 repeatableTypes: sets.New("Webhook"),
2479 },
2480 {
2481 name: "if connectionInfo=KubeConfigFile, an existent file needs to be passed",
2482 configuration: api.AuthorizationConfiguration{
2483 Authorizers: []api.AuthorizerConfiguration{
2484 {
2485 Type: "Webhook",
2486 Name: "default",
2487 Webhook: &api.WebhookConfiguration{
2488 Timeout: metav1.Duration{Duration: 5 * time.Second},
2489 AuthorizedTTL: metav1.Duration{Duration: 5 * time.Minute},
2490 UnauthorizedTTL: metav1.Duration{Duration: 30 * time.Second},
2491 FailurePolicy: "NoOpinion",
2492 SubjectAccessReviewVersion: "v1",
2493 MatchConditionSubjectAccessReviewVersion: "v1",
2494 ConnectionInfo: api.WebhookConnectionInfo{
2495 Type: "KubeConfigFile",
2496 KubeConfigFile: &tempKubeConfigFilePath,
2497 },
2498 },
2499 },
2500 },
2501 },
2502 expectedErrList: field.ErrorList{},
2503 knownTypes: sets.New("Webhook"),
2504 repeatableTypes: sets.New("Webhook"),
2505 },
2506 }
2507
2508 for _, test := range tests {
2509 t.Run(test.name, func(t *testing.T) {
2510 errList := ValidateAuthorizationConfiguration(authorizationcel.NewDefaultCompiler(), nil, &test.configuration, test.knownTypes, test.repeatableTypes)
2511 if len(errList) != len(test.expectedErrList) {
2512 t.Errorf("expected %d errs, got %d, errors %v", len(test.expectedErrList), len(errList), errList)
2513 }
2514 if len(errList) == len(test.expectedErrList) {
2515 for i, expected := range test.expectedErrList {
2516 if expected.Type.String() != errList[i].Type.String() {
2517 t.Errorf("expected err type %s, got %s",
2518 expected.Type.String(),
2519 errList[i].Type.String())
2520 }
2521 if expected.BadValue != errList[i].BadValue {
2522 t.Errorf("expected bad value '%s', got '%s'",
2523 expected.BadValue,
2524 errList[i].BadValue)
2525 }
2526 }
2527 }
2528 })
2529
2530 }
2531 }
2532
2533 func TestValidateAndCompileMatchConditions(t *testing.T) {
2534 testCases := []struct {
2535 name string
2536 matchConditions []api.WebhookMatchCondition
2537 expectedErr string
2538 }{
2539 {
2540 name: "match conditions are used With feature enabled",
2541 matchConditions: []api.WebhookMatchCondition{
2542 {
2543 Expression: "has(request.resourceAttributes) && request.resourceAttributes.namespace == 'kube-system'",
2544 },
2545 {
2546 Expression: "request.user == 'admin'",
2547 },
2548 },
2549 expectedErr: "",
2550 },
2551 {
2552 name: "no matchConditions should not require feature enablement",
2553 matchConditions: []api.WebhookMatchCondition{},
2554 expectedErr: "",
2555 },
2556 {
2557 name: "match conditions with invalid expressions",
2558 matchConditions: []api.WebhookMatchCondition{
2559 {
2560 Expression: " ",
2561 },
2562 },
2563 expectedErr: "matchConditions[0].expression: Required value",
2564 },
2565 {
2566 name: "match conditions with duplicate expressions",
2567 matchConditions: []api.WebhookMatchCondition{
2568 {
2569 Expression: "request.user == 'admin'",
2570 },
2571 {
2572 Expression: "request.user == 'admin'",
2573 },
2574 },
2575 expectedErr: `matchConditions[1].expression: Duplicate value: "request.user == 'admin'"`,
2576 },
2577 {
2578 name: "match conditions with undeclared reference",
2579 matchConditions: []api.WebhookMatchCondition{
2580 {
2581 Expression: "test",
2582 },
2583 },
2584 expectedErr: "matchConditions[0].expression: Invalid value: \"test\": compilation failed: ERROR: <input>:1:1: undeclared reference to 'test' (in container '')\n | test\n | ^",
2585 },
2586 {
2587 name: "match conditions with bad return type",
2588 matchConditions: []api.WebhookMatchCondition{
2589 {
2590 Expression: "request.user = 'test'",
2591 },
2592 },
2593 expectedErr: "matchConditions[0].expression: Invalid value: \"request.user = 'test'\": compilation failed: ERROR: <input>:1:14: Syntax error: token recognition error at: '= '\n | request.user = 'test'\n | .............^\nERROR: <input>:1:16: Syntax error: extraneous input ''test'' expecting <EOF>\n | request.user = 'test'\n | ...............^",
2594 },
2595 }
2596
2597 for _, tt := range testCases {
2598 t.Run(tt.name, func(t *testing.T) {
2599 celMatcher, errList := ValidateAndCompileMatchConditions(authorizationcel.NewDefaultCompiler(), tt.matchConditions)
2600 if len(tt.expectedErr) == 0 && len(tt.matchConditions) > 0 && len(errList) == 0 && celMatcher == nil {
2601 t.Errorf("celMatcher should not be nil when there are matchCondition and no error returned")
2602 }
2603 got := errList.ToAggregate()
2604 if d := cmp.Diff(tt.expectedErr, errString(got)); d != "" {
2605 t.Fatalf("ValidateAndCompileMatchConditions validation mismatch (-want +got):\n%s", d)
2606 }
2607 })
2608 }
2609 }