/
authorization.go
1253 lines (1134 loc) · 52.7 KB
/
authorization.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package authorization
import (
"context"
"fmt"
"reflect"
"strings"
"time"
g "github.com/onsi/ginkgo"
o "github.com/onsi/gomega"
kubeauthorizationv1 "k8s.io/api/authorization/v1"
corev1 "k8s.io/api/core/v1"
kapierror "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/discovery"
"k8s.io/client-go/kubernetes"
kauthorizationv1client "k8s.io/client-go/kubernetes/typed/authorization/v1"
rbacv1client "k8s.io/client-go/kubernetes/typed/rbac/v1"
"k8s.io/client-go/rest"
"k8s.io/kubernetes/pkg/api/legacyscheme"
appsapi "k8s.io/kubernetes/pkg/apis/apps"
extensionsapi "k8s.io/kubernetes/pkg/apis/extensions"
e2e "k8s.io/kubernetes/test/e2e/framework"
oapps "github.com/openshift/api/apps"
authorizationv1 "github.com/openshift/api/authorization/v1"
"github.com/openshift/api/build"
"github.com/openshift/api/image"
"github.com/openshift/api/oauth"
authorizationv1client "github.com/openshift/client-go/authorization/clientset/versioned"
authorizationv1typedclient "github.com/openshift/client-go/authorization/clientset/versioned/typed/authorization/v1"
exutil "github.com/openshift/origin/test/extended/util"
"github.com/openshift/origin/test/extended/util/ibmcloud"
)
var _ = g.Describe("[sig-auth][Feature:OpenShiftAuthorization] authorization", func() {
defer g.GinkgoRecover()
oc := exutil.NewCLI("bootstrap-policy")
g.Context("", func() {
g.Describe("TestClusterReaderCoverage", func() {
g.It(fmt.Sprintf("should succeed"), func() {
g.Skip("this test was in integration and didn't cover a real configuration, so it's horribly, horribly wrong now")
t := g.GinkgoT()
clusterAdminClientConfig := oc.AdminConfig()
discoveryClient := discovery.NewDiscoveryClientForConfigOrDie(clusterAdminClientConfig)
// (map[string]*metav1.APIResourceList, error)
allResourceList, err := discoveryClient.ServerResources()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
allResources := map[schema.GroupResource]bool{}
for _, resources := range allResourceList {
version, err := schema.ParseGroupVersion(resources.GroupVersion)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
for _, resource := range resources.APIResources {
allResources[version.WithResource(resource.Name).GroupResource()] = true
}
}
escalatingResources := map[schema.GroupResource]bool{
oauth.Resource("oauthauthorizetokens"): true,
oauth.Resource("oauthaccesstokens"): true,
oauth.Resource("oauthclients"): true,
image.Resource("imagestreams/secrets"): true,
corev1.Resource("secrets"): true,
corev1.Resource("pods/exec"): true,
corev1.Resource("pods/proxy"): true,
corev1.Resource("pods/portforward"): true,
corev1.Resource("nodes/proxy"): true,
corev1.Resource("services/proxy"): true,
{Resource: "oauthauthorizetokens"}: true,
{Resource: "oauthaccesstokens"}: true,
{Resource: "oauthclients"}: true,
{Resource: "imagestreams/secrets"}: true,
}
readerRole, err := rbacv1client.NewForConfigOrDie(clusterAdminClientConfig).ClusterRoles().Get(context.Background(), "cluster-reader", metav1.GetOptions{})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
for _, rule := range readerRole.Rules {
for _, group := range rule.APIGroups {
for _, resource := range rule.Resources {
gr := schema.GroupResource{Group: group, Resource: resource}
if escalatingResources[gr] {
t.Errorf("cluster-reader role has escalating resource %v. Check pkg/cmd/server/bootstrappolicy/policy.go.", gr)
}
delete(allResources, gr)
}
}
}
// remove escalating resources that cluster-reader should not have access to
for resource := range escalatingResources {
delete(allResources, resource)
}
// remove resources without read APIs
nonreadingResources := []schema.GroupResource{
oapps.Resource("deploymentconfigrollbacks"),
oapps.Resource("generatedeploymentconfigs"),
oapps.Resource("deploymentconfigs/rollback"),
oapps.Resource("deploymentconfigs/instantiate"),
build.Resource("buildconfigs/instantiatebinary"),
build.Resource("buildconfigs/instantiate"),
build.Resource("builds/clone"),
image.Resource("imagestreamimports"),
image.Resource("imagestreammappings"),
extensionsapi.Resource("deployments/rollback"),
appsapi.Resource("deployments/rollback"),
corev1.Resource("pods/attach"),
corev1.Resource("namespaces/finalize"),
{Group: "", Resource: "buildconfigs/instantiatebinary"},
{Group: "", Resource: "buildconfigs/instantiate"},
{Group: "", Resource: "builds/clone"},
{Group: "", Resource: "deploymentconfigrollbacks"},
{Group: "", Resource: "generatedeploymentconfigs"},
{Group: "", Resource: "deploymentconfigs/rollback"},
{Group: "", Resource: "deploymentconfigs/instantiate"},
{Group: "", Resource: "imagestreamimports"},
{Group: "", Resource: "imagestreammappings"},
}
for _, resource := range nonreadingResources {
delete(allResources, resource)
}
// anything left in the map is missing from the permissions
if len(allResources) > 0 {
t.Errorf("cluster-reader role is missing %v. Check pkg/cmd/server/bootstrappolicy/policy.go.", allResources)
}
})
})
})
})
func prettyPrintAction(act *authorizationv1.Action, defaultNamespaceStr string) string {
nsStr := fmt.Sprintf("in namespace %q", act.Namespace)
if act.Namespace == "" {
nsStr = defaultNamespaceStr
}
var resourceStr string
if act.Group == "" && act.Version == "" {
resourceStr = act.Resource
} else {
groupVer := schema.GroupVersion{Group: act.Group, Version: act.Version}
resourceStr = fmt.Sprintf("%s/%s", act.Resource, groupVer.String())
}
var base string
if act.ResourceName == "" {
base = fmt.Sprintf("who can %s %s %s", act.Verb, resourceStr, nsStr)
} else {
base = fmt.Sprintf("who can %s the %s named %q %s", act.Verb, resourceStr, act.ResourceName, nsStr)
}
if len(act.Content.Raw) != 0 {
return fmt.Sprintf("%s with content %#v", base, act.Content)
}
return base
}
func prettyPrintReviewResponse(resp *authorizationv1.ResourceAccessReviewResponse) string {
nsStr := fmt.Sprintf("(in the namespace %q)\n", resp.Namespace)
if resp.Namespace == "" {
nsStr = "(in all namespaces)\n"
}
var usersStr string
if len(resp.UsersSlice) > 0 {
userStrList := make([]string, 0, len(resp.UsersSlice))
for _, userName := range resp.UsersSlice {
userStrList = append(userStrList, fmt.Sprintf(" - %s\n", userName))
}
usersStr = fmt.Sprintf(" users:\n%s", strings.Join(userStrList, ""))
}
var groupsStr string
if len(resp.GroupsSlice) > 0 {
groupStrList := make([]string, 0, len(resp.GroupsSlice))
for _, groupName := range resp.GroupsSlice {
groupStrList = append(groupStrList, fmt.Sprintf(" - %s\n", groupName))
}
groupsStr = fmt.Sprintf(" groups:\n%s", strings.Join(groupStrList, ""))
}
return fmt.Sprintf(nsStr + usersStr + groupsStr)
}
// This list includes the admins from above, plus users or groups known to have global view access
var globalClusterReaderUsers = sets.NewString("system:admin")
var globalClusterReaderGroups = sets.NewString("system:cluster-readers", "system:cluster-admins", "system:masters")
// this list includes any other users who can get DeploymentConfigs
var globalDeploymentConfigGetterUsers = sets.NewString(
"system:serviceaccount:kube-system:generic-garbage-collector",
"system:serviceaccount:kube-system:namespace-controller",
)
type resourceAccessReviewTest struct {
description string
clientInterface authorizationv1typedclient.ResourceAccessReviewInterface
review *authorizationv1.ResourceAccessReview
response authorizationv1.ResourceAccessReviewResponse
err string
}
func (test resourceAccessReviewTest) run() {
PolicyCachePollInterval := 100 * time.Millisecond
PolicyCachePollTimeout := 10 * time.Second
failMessage := ""
var err error
g.By("resourceAccessReviewTest - "+test.description, func() {
// keep trying the test until you get a success or you timeout. Every time you have a failure, set the fail message
// so that if you never have a success, we can call t.Errorf with a reasonable message
// exiting the poll with `failMessage=""` indicates success.
err = wait.Poll(PolicyCachePollInterval, PolicyCachePollTimeout, func() (bool, error) {
actualResponse, err := test.clientInterface.Create(context.Background(), test.review, metav1.CreateOptions{})
if len(test.err) > 0 {
if err == nil {
failMessage = fmt.Sprintf("%s: Expected error: %v", test.description, test.err)
return false, nil
} else if !strings.Contains(err.Error(), test.err) {
failMessage = fmt.Sprintf("%s: expected %v, got %v", test.description, test.err, err)
return false, nil
}
} else {
if err != nil {
failMessage = fmt.Sprintf("%s: unexpected error: %v", test.description, err)
return false, nil
}
}
// many operators installed in openshift- namespaces are allowed to read all namespaces. We simply suppress all those users from the user slice
// so we aren't sensitive to adding or removing them
actualUsersToCheck := sets.NewString()
for _, curr := range actualResponse.UsersSlice {
if strings.HasPrefix(curr, "system:serviceaccount:openshift-") {
continue
}
// ibmcloud openshift has an IAM user that needs to be ignored
if e2e.TestContext.Provider == ibmcloud.ProviderName {
if strings.HasPrefix(curr, "IAM#") {
continue
}
}
actualUsersToCheck.Insert(curr)
}
if actualResponse.Namespace != test.response.Namespace ||
!reflect.DeepEqual(actualUsersToCheck, sets.NewString(test.response.UsersSlice...)) ||
!reflect.DeepEqual(sets.NewString(actualResponse.GroupsSlice...), sets.NewString(test.response.GroupsSlice...)) ||
actualResponse.EvaluationError != test.response.EvaluationError {
failMessage = fmt.Sprintf("%s:\n %s:\n expected %s\n got %s", test.description, prettyPrintAction(&test.review.Action, "(in any namespace)"), prettyPrintReviewResponse(&test.response), prettyPrintReviewResponse(actualResponse))
return false, nil
}
failMessage = ""
return true, nil
})
})
if err != nil {
if len(failMessage) != 0 {
g.Fail(failMessage)
}
g.Fail(err.Error())
}
if len(failMessage) != 0 {
g.Fail(failMessage)
}
}
type localResourceAccessReviewTest struct {
description string
clientInterface authorizationv1typedclient.LocalResourceAccessReviewInterface
review *authorizationv1.LocalResourceAccessReview
response authorizationv1.ResourceAccessReviewResponse
err string
}
func (test localResourceAccessReviewTest) run() {
PolicyCachePollInterval := 100 * time.Millisecond
PolicyCachePollTimeout := 10 * time.Second
failMessage := ""
var err error
g.By("localResourceAccessReviewTest - "+test.description, func() {
// keep trying the test until you get a success or you timeout. Every time you have a failure, set the fail message
// so that if you never have a success, we can call t.Errorf with a reasonable message
// exiting the poll with `failMessage=""` indicates success.
err = wait.Poll(PolicyCachePollInterval, PolicyCachePollTimeout, func() (bool, error) {
actualResponse, err := test.clientInterface.Create(context.Background(), test.review, metav1.CreateOptions{})
if len(test.err) > 0 {
if err == nil {
failMessage = fmt.Sprintf("%s: Expected error: %v", test.description, test.err)
return false, nil
} else if !strings.Contains(err.Error(), test.err) {
failMessage = fmt.Sprintf("%s: expected %v, got %v", test.description, test.err, err)
return false, nil
}
} else {
if err != nil {
failMessage = fmt.Sprintf("%s: unexpected error: %v", test.description, err)
return false, nil
}
}
if actualResponse.Namespace != test.response.Namespace {
failMessage = fmt.Sprintf("%s\n: namespaces does not match (%s!=%s)", test.description, actualResponse.Namespace, test.response.Namespace)
return false, nil
}
if actualResponse.EvaluationError != test.response.EvaluationError {
failMessage = fmt.Sprintf("%s\n: evaluation errors does not match (%s!=%s)", test.description, actualResponse.EvaluationError, test.response.EvaluationError)
return false, nil
}
// many operators installed in openshift- namespaces are allowed to read all namespaces. We simply suppress all those users from the user slice
// so we aren't sensitive to adding or removing them
actualUsersToCheck := sets.NewString()
for _, curr := range actualResponse.UsersSlice {
if strings.HasPrefix(curr, "system:serviceaccount:openshift-") {
continue
}
// ibmcloud openshift has an IAM user that needs to be ignored
if e2e.TestContext.Provider == ibmcloud.ProviderName {
if strings.HasPrefix(curr, "IAM#") {
continue
}
}
// skip the ci provisioner to pass gcp: ci-provisioner@openshift-gce-devel-ci.iam.gserviceaccount.com
if strings.HasPrefix(curr, "ci-provisioner@") {
continue
}
actualUsersToCheck.Insert(curr)
}
if !reflect.DeepEqual(actualUsersToCheck, sets.NewString(test.response.UsersSlice...)) {
failMessage = fmt.Sprintf("%s:\n %s:\n expected %s\n got %s", test.description, prettyPrintAction(&test.review.Action, "(in the current namespace)"), prettyPrintReviewResponse(&test.response), prettyPrintReviewResponse(actualResponse))
return false, nil
}
if !reflect.DeepEqual(sets.NewString(actualResponse.GroupsSlice...), sets.NewString(test.response.GroupsSlice...)) {
failMessage = fmt.Sprintf("%s:\n %s:\n expected %s\n got %s", test.description, prettyPrintAction(&test.review.Action, "(in the current namespace)"), prettyPrintReviewResponse(&test.response), prettyPrintReviewResponse(actualResponse))
return false, nil
}
failMessage = ""
return true, nil
})
})
if err != nil {
if len(failMessage) != 0 {
g.Fail(failMessage)
}
g.Fail(err.Error())
}
if len(failMessage) != 0 {
g.Fail(failMessage)
}
}
// serial because it is vulnerable to access added by other tests
var _ = g.Describe("[sig-auth][Feature:OpenShiftAuthorization][Serial] authorization", func() {
defer g.GinkgoRecover()
oc := exutil.NewCLI("bootstrap-policy")
g.Context("", func() {
g.Describe("TestAuthorizationResourceAccessReview", func() {
g.It(fmt.Sprintf("should succeed"), func() {
clusterAdminAuthorizationClient := oc.AdminAuthorizationClient().AuthorizationV1()
hammerProjectName := oc.CreateProject()
haroldName := oc.CreateUser("harold-").Name
haroldConfig := oc.GetClientConfigForUser(haroldName)
haroldAuthorizationClient := authorizationv1client.NewForConfigOrDie(haroldConfig).AuthorizationV1()
AddUserAdminToProject(oc, hammerProjectName, haroldName)
malletProjectName := oc.CreateProject()
markName := oc.CreateUser("mark-").Name
markConfig := oc.GetClientConfigForUser(markName)
markAuthorizationClient := authorizationv1client.NewForConfigOrDie(markConfig).AuthorizationV1()
AddUserAdminToProject(oc, malletProjectName, markName)
valerieName := oc.CreateUser("valerie-").Name
AddUserViewToProject(oc, hammerProjectName, valerieName)
edgarName := oc.CreateUser("edgar-").Name
AddUserEditToProject(oc, malletProjectName, edgarName)
requestWhoCanViewDeploymentConfigs := &authorizationv1.ResourceAccessReview{
Action: authorizationv1.Action{Verb: "get", Resource: "deploymentconfigs", Group: ""},
}
localRequestWhoCanViewDeploymentConfigs := &authorizationv1.LocalResourceAccessReview{
Action: authorizationv1.Action{Verb: "get", Resource: "deploymentconfigs", Group: ""},
}
{
test := localResourceAccessReviewTest{
description: "who can view deploymentconfigs in hammer by harold",
clientInterface: haroldAuthorizationClient.LocalResourceAccessReviews(hammerProjectName),
review: localRequestWhoCanViewDeploymentConfigs,
response: authorizationv1.ResourceAccessReviewResponse{
UsersSlice: []string{oc.Username(), haroldName, valerieName},
GroupsSlice: []string{},
Namespace: hammerProjectName,
},
}
test.response.UsersSlice = append(test.response.UsersSlice, globalClusterReaderUsers.List()...)
test.response.UsersSlice = append(test.response.UsersSlice, globalDeploymentConfigGetterUsers.List()...)
test.response.GroupsSlice = append(test.response.GroupsSlice, globalClusterReaderGroups.List()...)
test.run()
}
{
test := localResourceAccessReviewTest{
description: "who can view deploymentconfigs in mallet by mark",
clientInterface: markAuthorizationClient.LocalResourceAccessReviews(malletProjectName),
review: localRequestWhoCanViewDeploymentConfigs,
response: authorizationv1.ResourceAccessReviewResponse{
UsersSlice: []string{oc.Username(), markName, edgarName},
GroupsSlice: []string{},
Namespace: malletProjectName,
},
}
test.response.UsersSlice = append(test.response.UsersSlice, globalClusterReaderUsers.List()...)
test.response.UsersSlice = append(test.response.UsersSlice, globalDeploymentConfigGetterUsers.List()...)
test.response.GroupsSlice = append(test.response.GroupsSlice, globalClusterReaderGroups.List()...)
test.run()
}
// mark should not be able to make global access review requests
{
test := resourceAccessReviewTest{
description: "who can view deploymentconfigs in all by mark",
clientInterface: markAuthorizationClient.ResourceAccessReviews(),
review: requestWhoCanViewDeploymentConfigs,
err: "cannot ",
}
test.run()
}
// a cluster-admin should be able to make global access review requests
{
test := resourceAccessReviewTest{
description: "who can view deploymentconfigs in all by cluster-admin",
clientInterface: clusterAdminAuthorizationClient.ResourceAccessReviews(),
review: requestWhoCanViewDeploymentConfigs,
response: authorizationv1.ResourceAccessReviewResponse{
UsersSlice: []string{},
GroupsSlice: []string{},
},
}
test.response.UsersSlice = append(test.response.UsersSlice, globalClusterReaderUsers.List()...)
test.response.UsersSlice = append(test.response.UsersSlice, globalDeploymentConfigGetterUsers.List()...)
test.response.GroupsSlice = append(test.response.GroupsSlice, globalClusterReaderGroups.List()...)
test.run()
}
})
})
})
})
var _ = g.Describe("[sig-auth][Feature:OpenShiftAuthorization] authorization", func() {
defer g.GinkgoRecover()
oc := exutil.NewCLI("bootstrap-policy")
g.Context("", func() {
g.Describe("TestAuthorizationSubjectAccessReview", func() {
g.It(fmt.Sprintf("should succeed"), func() {
t := g.GinkgoT()
clusterAdminLocalSARGetter := oc.AdminKubeClient().AuthorizationV1()
clusterAdminAuthorizationClient := oc.AdminAuthorizationClient().AuthorizationV1()
g.By("creating projects")
hammerProjectName := oc.CreateProject()
malletProjectName := oc.CreateProject()
haroldName := oc.CreateUser("harold-").Name
markName := oc.CreateUser("mark-").Name
dannyName := oc.CreateUser("danny-").Name
edgarName := oc.CreateUser("edgar-").Name
valerieName := oc.CreateUser("valerie-").Name
g.By("adding user permissions")
haroldAdminRoleBindingName := AddUserAdminToProject(oc, hammerProjectName, haroldName)
// TODO should be done by harold
valerieViewRoleBindingName := AddUserViewToProject(oc, hammerProjectName, valerieName)
AddUserAdminToProject(oc, malletProjectName, markName)
// TODO should be done by mark
edgarEditRoleBindingName := AddUserEditToProject(oc, malletProjectName, edgarName)
anonEditRoleBindingName := AddUserEditToProject(oc, hammerProjectName, "system:anonymous")
dannyViewRoleBindingName := AddUserViewToProject(oc, "default", dannyName)
g.By("creating clients")
haroldConfig := oc.GetClientConfigForUser(haroldName)
haroldAuthorizationClient := authorizationv1typedclient.NewForConfigOrDie(haroldConfig)
haroldSARGetter := kubernetes.NewForConfigOrDie(haroldConfig).AuthorizationV1()
markConfig := oc.GetClientConfigForUser(markName)
markAuthorizationClient := authorizationv1typedclient.NewForConfigOrDie(markConfig)
markSARGetter := kubernetes.NewForConfigOrDie(markConfig).AuthorizationV1()
anonymousConfig := rest.AnonymousClientConfig(oc.AdminConfig())
anonymousAuthorizationClient := authorizationv1typedclient.NewForConfigOrDie(anonymousConfig)
anonymousSARGetter := kubernetes.NewForConfigOrDie(anonymousConfig).AuthorizationV1()
dannyConfig := oc.GetClientConfigForUser(dannyName)
dannyAuthorizationClient := authorizationv1typedclient.NewForConfigOrDie(dannyConfig)
dannySARGetter := kubernetes.NewForConfigOrDie(dannyConfig).AuthorizationV1()
askCanDannyGetProject := &authorizationv1.SubjectAccessReview{
User: dannyName,
Action: authorizationv1.Action{Verb: "get", Resource: "projects"},
}
subjectAccessReviewTest{
description: "cluster admin told danny can get project default",
localInterface: clusterAdminAuthorizationClient.LocalSubjectAccessReviews("default"),
localReview: &authorizationv1.LocalSubjectAccessReview{
User: dannyName,
Action: authorizationv1.Action{Verb: "get", Resource: "projects"},
},
kubeAuthInterface: clusterAdminLocalSARGetter,
response: authorizationv1.SubjectAccessReviewResponse{
Allowed: true,
Reason: `RBAC: allowed by RoleBinding "` + dannyViewRoleBindingName + `/default" of ClusterRole "view" to User "` + dannyName + `"`,
Namespace: "default",
},
}.run(t)
subjectAccessReviewTest{
description: "cluster admin told danny cannot get projects cluster-wide",
clusterInterface: clusterAdminAuthorizationClient.SubjectAccessReviews(),
clusterReview: askCanDannyGetProject,
kubeAuthInterface: clusterAdminLocalSARGetter,
response: authorizationv1.SubjectAccessReviewResponse{
Allowed: false,
Reason: "",
Namespace: "",
},
}.run(t)
subjectAccessReviewTest{
description: "as danny, can I make cluster subject access reviews",
clusterInterface: dannyAuthorizationClient.SubjectAccessReviews(),
clusterReview: askCanDannyGetProject,
kubeAuthInterface: dannySARGetter,
err: `subjectaccessreviews.authorization.openshift.io is forbidden: User "` + dannyName + `" cannot create resource "subjectaccessreviews" in API group "authorization.openshift.io" at the cluster scope`,
kubeErr: `subjectaccessreviews.authorization.k8s.io is forbidden: User "` + dannyName + `" cannot create resource "subjectaccessreviews" in API group "authorization.k8s.io" at the cluster scope`,
}.run(t)
subjectAccessReviewTest{
description: "as anonymous, can I make cluster subject access reviews",
clusterInterface: anonymousAuthorizationClient.SubjectAccessReviews(),
clusterReview: askCanDannyGetProject,
kubeAuthInterface: anonymousSARGetter,
err: `subjectaccessreviews.authorization.openshift.io is forbidden: User "system:anonymous" cannot create resource "subjectaccessreviews" in API group "authorization.openshift.io" at the cluster scope`,
kubeErr: `subjectaccessreviews.authorization.k8s.io is forbidden: User "system:anonymous" cannot create resource "subjectaccessreviews" in API group "authorization.k8s.io" at the cluster scope`,
}.run(t)
askCanValerieGetProject := &authorizationv1.LocalSubjectAccessReview{
User: valerieName,
Action: authorizationv1.Action{Verb: "get", Resource: "projects"},
}
subjectAccessReviewTest{
description: "harold told valerie can get project hammer-project",
localInterface: haroldAuthorizationClient.LocalSubjectAccessReviews(hammerProjectName),
localReview: askCanValerieGetProject,
kubeAuthInterface: haroldSARGetter,
response: authorizationv1.SubjectAccessReviewResponse{
Allowed: true,
Reason: `RBAC: allowed by RoleBinding "` + valerieViewRoleBindingName + `/` + hammerProjectName + `" of ClusterRole "view" to User "` + valerieName + `"`,
Namespace: hammerProjectName,
},
}.run(t)
subjectAccessReviewTest{
description: "mark told valerie cannot get project mallet-project",
localInterface: markAuthorizationClient.LocalSubjectAccessReviews(malletProjectName),
localReview: askCanValerieGetProject,
kubeAuthInterface: markSARGetter,
response: authorizationv1.SubjectAccessReviewResponse{
Allowed: false,
Reason: "",
Namespace: malletProjectName,
},
}.run(t)
askCanEdgarDeletePods := &authorizationv1.LocalSubjectAccessReview{
User: edgarName,
Action: authorizationv1.Action{Verb: "delete", Resource: "pods"},
}
subjectAccessReviewTest{
description: "mark told edgar can delete pods in mallet-project",
localInterface: markAuthorizationClient.LocalSubjectAccessReviews(malletProjectName),
localReview: askCanEdgarDeletePods,
kubeAuthInterface: markSARGetter,
response: authorizationv1.SubjectAccessReviewResponse{
Allowed: true,
Reason: `RBAC: allowed by RoleBinding "` + edgarEditRoleBindingName + `/` + malletProjectName + `" of ClusterRole "edit" to User "` + edgarName + `"`,
Namespace: malletProjectName,
},
}.run(t)
// ensure unprivileged users cannot check other users' access
subjectAccessReviewTest{
description: "harold denied ability to run subject access review in project mallet-project",
localInterface: haroldAuthorizationClient.LocalSubjectAccessReviews(malletProjectName),
localReview: askCanEdgarDeletePods,
kubeAuthInterface: haroldSARGetter,
kubeNamespace: malletProjectName,
err: `localsubjectaccessreviews.authorization.openshift.io is forbidden: User "` + haroldName + `" cannot create resource "localsubjectaccessreviews" in API group "authorization.openshift.io" in the namespace "` + malletProjectName + `"`,
kubeErr: `localsubjectaccessreviews.authorization.k8s.io is forbidden: User "` + haroldName + `" cannot create resource "localsubjectaccessreviews" in API group "authorization.k8s.io" in the namespace "` + malletProjectName + `"`,
}.run(t)
subjectAccessReviewTest{
description: "system:anonymous denied ability to run subject access review in project mallet-project",
localInterface: anonymousAuthorizationClient.LocalSubjectAccessReviews(malletProjectName),
localReview: askCanEdgarDeletePods,
kubeAuthInterface: anonymousSARGetter,
kubeNamespace: malletProjectName,
err: `localsubjectaccessreviews.authorization.openshift.io is forbidden: User "system:anonymous" cannot create resource "localsubjectaccessreviews" in API group "authorization.openshift.io" in the namespace "` + malletProjectName + `"`,
kubeErr: `localsubjectaccessreviews.authorization.k8s.io is forbidden: User "system:anonymous" cannot create resource "localsubjectaccessreviews" in API group "authorization.k8s.io" in the namespace "` + malletProjectName + `"`,
}.run(t)
// ensure message does not leak whether the namespace exists or not
subjectAccessReviewTest{
description: "harold denied ability to run subject access review in project nonexistent-project",
localInterface: haroldAuthorizationClient.LocalSubjectAccessReviews("nonexistent-project"),
localReview: askCanEdgarDeletePods,
kubeAuthInterface: haroldSARGetter,
kubeNamespace: "nonexistent-project",
err: `localsubjectaccessreviews.authorization.openshift.io is forbidden: User "` + haroldName + `" cannot create resource "localsubjectaccessreviews" in API group "authorization.openshift.io" in the namespace "nonexistent-project"`,
kubeErr: `localsubjectaccessreviews.authorization.k8s.io is forbidden: User "` + haroldName + `" cannot create resource "localsubjectaccessreviews" in API group "authorization.k8s.io" in the namespace "nonexistent-project"`,
}.run(t)
subjectAccessReviewTest{
description: "system:anonymous denied ability to run subject access review in project nonexistent-project",
localInterface: anonymousAuthorizationClient.LocalSubjectAccessReviews("nonexistent-project"),
localReview: askCanEdgarDeletePods,
kubeAuthInterface: anonymousSARGetter,
kubeNamespace: "nonexistent-project",
err: `localsubjectaccessreviews.authorization.openshift.io is forbidden: User "system:anonymous" cannot create resource "localsubjectaccessreviews" in API group "authorization.openshift.io" in the namespace "nonexistent-project"`,
kubeErr: `localsubjectaccessreviews.authorization.k8s.io is forbidden: User "system:anonymous" cannot create resource "localsubjectaccessreviews" in API group "authorization.k8s.io" in the namespace "nonexistent-project"`,
}.run(t)
askCanHaroldUpdateProject := &authorizationv1.LocalSubjectAccessReview{
User: haroldName,
Action: authorizationv1.Action{Verb: "update", Resource: "projects"},
}
subjectAccessReviewTest{
description: "harold told harold can update project hammer-project",
localInterface: haroldAuthorizationClient.LocalSubjectAccessReviews(hammerProjectName),
localReview: askCanHaroldUpdateProject,
kubeAuthInterface: haroldSARGetter,
response: authorizationv1.SubjectAccessReviewResponse{
Allowed: true,
Reason: `RBAC: allowed by RoleBinding "` + haroldAdminRoleBindingName + `/` + hammerProjectName + `" of ClusterRole "admin" to User "` + haroldName + `"`,
Namespace: hammerProjectName,
},
}.run(t)
askCanClusterAdminsCreateProject := &authorizationv1.SubjectAccessReview{
GroupsSlice: []string{"system:cluster-admins"},
Action: authorizationv1.Action{Verb: "create", Resource: "projects"},
}
subjectAccessReviewTest{
description: "cluster admin told cluster admins can create projects",
clusterInterface: clusterAdminAuthorizationClient.SubjectAccessReviews(),
clusterReview: askCanClusterAdminsCreateProject,
kubeAuthInterface: clusterAdminLocalSARGetter,
response: authorizationv1.SubjectAccessReviewResponse{
Allowed: true,
Reason: `RBAC: allowed by ClusterRoleBinding "cluster-admins" of ClusterRole "cluster-admin" to Group "system:cluster-admins"`,
Namespace: "",
},
}.run(t)
subjectAccessReviewTest{
description: "harold denied ability to run cluster subject access review",
clusterInterface: haroldAuthorizationClient.SubjectAccessReviews(),
clusterReview: askCanClusterAdminsCreateProject,
kubeAuthInterface: haroldSARGetter,
err: `subjectaccessreviews.authorization.openshift.io is forbidden: User "` + haroldName + `" cannot create resource "subjectaccessreviews" in API group "authorization.openshift.io" at the cluster scope`,
kubeErr: `subjectaccessreviews.authorization.k8s.io is forbidden: User "` + haroldName + `" cannot create resource "subjectaccessreviews" in API group "authorization.k8s.io" at the cluster scope`,
}.run(t)
askCanICreatePods := &authorizationv1.LocalSubjectAccessReview{
Action: authorizationv1.Action{Verb: "create", Resource: "pods"},
}
subjectAccessReviewTest{
description: "harold told he can create pods in project hammer-project",
localInterface: haroldAuthorizationClient.LocalSubjectAccessReviews(hammerProjectName),
localReview: askCanICreatePods,
kubeAuthInterface: haroldSARGetter,
response: authorizationv1.SubjectAccessReviewResponse{
Allowed: true,
Reason: `RBAC: allowed by RoleBinding "` + haroldAdminRoleBindingName + `/` + hammerProjectName + `" of ClusterRole "admin" to User "` + haroldName + `"`,
Namespace: hammerProjectName,
},
}.run(t)
subjectAccessReviewTest{
description: "system:anonymous told he can create pods in project hammer-project",
localInterface: anonymousAuthorizationClient.LocalSubjectAccessReviews(hammerProjectName),
localReview: askCanICreatePods,
kubeAuthInterface: anonymousSARGetter,
response: authorizationv1.SubjectAccessReviewResponse{
Allowed: true,
Reason: `RBAC: allowed by RoleBinding "` + anonEditRoleBindingName + `/` + hammerProjectName + `" of ClusterRole "edit" to User "system:anonymous"`,
Namespace: hammerProjectName,
},
}.run(t)
// test checking self permissions when denied
subjectAccessReviewTest{
description: "harold told he cannot create pods in project mallet-project",
localInterface: haroldAuthorizationClient.LocalSubjectAccessReviews(malletProjectName),
localReview: askCanICreatePods,
kubeAuthInterface: haroldSARGetter,
response: authorizationv1.SubjectAccessReviewResponse{
Allowed: false,
Reason: "",
Namespace: malletProjectName,
},
}.run(t)
subjectAccessReviewTest{
description: "system:anonymous told he cannot create pods in project mallet-project",
localInterface: anonymousAuthorizationClient.LocalSubjectAccessReviews(malletProjectName),
localReview: askCanICreatePods,
kubeAuthInterface: anonymousSARGetter,
response: authorizationv1.SubjectAccessReviewResponse{
Allowed: false,
Reason: "",
Namespace: malletProjectName,
},
}.run(t)
// test checking self-permissions doesn't leak whether namespace exists or not
// We carry a patch to allow this
subjectAccessReviewTest{
description: "harold told he cannot create pods in project nonexistent-project",
localInterface: haroldAuthorizationClient.LocalSubjectAccessReviews("nonexistent-project"),
localReview: askCanICreatePods,
kubeAuthInterface: haroldSARGetter,
response: authorizationv1.SubjectAccessReviewResponse{
Allowed: false,
Reason: "",
Namespace: "nonexistent-project",
},
}.run(t)
subjectAccessReviewTest{
description: "system:anonymous told he cannot create pods in project nonexistent-project",
localInterface: anonymousAuthorizationClient.LocalSubjectAccessReviews("nonexistent-project"),
localReview: askCanICreatePods,
kubeAuthInterface: anonymousSARGetter,
response: authorizationv1.SubjectAccessReviewResponse{
Allowed: false,
Reason: "",
Namespace: "nonexistent-project",
},
}.run(t)
askCanICreatePolicyBindings := &authorizationv1.LocalSubjectAccessReview{
Action: authorizationv1.Action{Verb: "create", Resource: "policybindings"},
}
subjectAccessReviewTest{
description: "harold told he can create policybindings in project hammer-project",
localInterface: haroldAuthorizationClient.LocalSubjectAccessReviews(hammerProjectName),
kubeAuthInterface: haroldSARGetter,
localReview: askCanICreatePolicyBindings,
response: authorizationv1.SubjectAccessReviewResponse{
Allowed: false,
Reason: "",
Namespace: hammerProjectName,
},
}.run(t)
})
})
})
})
type subjectAccessReviewTest struct {
description string
localInterface authorizationv1typedclient.LocalSubjectAccessReviewInterface
clusterInterface authorizationv1typedclient.SubjectAccessReviewInterface
localReview *authorizationv1.LocalSubjectAccessReview
clusterReview *authorizationv1.SubjectAccessReview
kubeNamespace string
kubeErr string
kubeSkip bool
kubeAuthInterface kauthorizationv1client.AuthorizationV1Interface
response authorizationv1.SubjectAccessReviewResponse
err string
}
func (test subjectAccessReviewTest) run(t g.GinkgoTInterface) {
PolicyCachePollInterval := 100 * time.Millisecond
PolicyCachePollTimeout := 10 * time.Second
g.By(test.description+" with openshift api", func() {
failMessage := ""
err := wait.Poll(PolicyCachePollInterval, PolicyCachePollTimeout, func() (bool, error) {
var err error
var actualResponse *authorizationv1.SubjectAccessReviewResponse
if test.localReview != nil {
actualResponse, err = test.localInterface.Create(context.Background(), test.localReview, metav1.CreateOptions{})
} else {
actualResponse, err = test.clusterInterface.Create(context.Background(), test.clusterReview, metav1.CreateOptions{})
}
if len(test.err) > 0 {
if err == nil {
failMessage = fmt.Sprintf("%s: Expected error: %v", test.description, test.err)
return false, nil
} else if !strings.HasPrefix(err.Error(), test.err) {
failMessage = fmt.Sprintf("%s: expected\n\t%v\ngot\n\t%v", test.description, test.err, err)
return false, nil
}
} else {
if err != nil {
failMessage = fmt.Sprintf("%s: unexpected error: %v", test.description, err)
return false, nil
}
}
if (actualResponse.Namespace != test.response.Namespace) ||
(actualResponse.Allowed != test.response.Allowed) ||
(!strings.HasPrefix(actualResponse.Reason, test.response.Reason)) {
if test.localReview != nil {
failMessage = fmt.Sprintf("%s: from local review\n\t%#v\nexpected\n\t%#v\ngot\n\t%#v", test.description, test.localReview, &test.response, actualResponse)
} else {
failMessage = fmt.Sprintf("%s: from review\n\t%#v\nexpected\n\t%#v\ngot\n\t%#v", test.description, test.clusterReview, &test.response, actualResponse)
}
return false, nil
}
failMessage = ""
return true, nil
})
if err != nil {
if len(failMessage) != 0 {
t.Error(failMessage)
}
t.Error(err)
}
if len(failMessage) != 0 {
t.Error(failMessage)
}
})
if test.kubeAuthInterface != nil {
g.By(test.description+" with kube api", func() {
var testNS string
if test.localReview != nil {
switch {
case len(test.localReview.Namespace) > 0:
testNS = test.localReview.Namespace
case len(test.response.Namespace) > 0:
testNS = test.response.Namespace
case len(test.kubeNamespace) > 0:
testNS = test.kubeNamespace
default:
t.Errorf("%s: no valid namespace found for kube auth test", test.description)
return
}
}
failMessage := ""
err := wait.Poll(PolicyCachePollInterval, PolicyCachePollTimeout, func() (bool, error) {
var err error
var actualResponse kubeauthorizationv1.SubjectAccessReviewStatus
if test.localReview != nil {
if len(test.localReview.User) == 0 && (len(test.localReview.GroupsSlice) == 0) {
var tmp *kubeauthorizationv1.SelfSubjectAccessReview
if tmp, err = test.kubeAuthInterface.SelfSubjectAccessReviews().Create(context.Background(), toKubeSelfSAR(testNS, test.localReview), metav1.CreateOptions{}); err == nil {
actualResponse = tmp.Status
}
} else {
var tmp *kubeauthorizationv1.LocalSubjectAccessReview
if tmp, err = test.kubeAuthInterface.LocalSubjectAccessReviews(testNS).Create(context.Background(), toKubeLocalSAR(testNS, test.localReview), metav1.CreateOptions{}); err == nil {
actualResponse = tmp.Status
}
}
} else {
var tmp *kubeauthorizationv1.SubjectAccessReview
if tmp, err = test.kubeAuthInterface.SubjectAccessReviews().Create(context.Background(), toKubeClusterSAR(test.clusterReview), metav1.CreateOptions{}); err == nil {
actualResponse = tmp.Status
}
}
testErr := test.kubeErr
if len(testErr) == 0 {
testErr = test.err
}
if len(testErr) > 0 {
if err == nil {
failMessage = fmt.Sprintf("%s: Expected error: %v\ngot\n\t%#v", test.description, testErr, actualResponse)
return false, nil
} else if !strings.HasPrefix(err.Error(), testErr) {
failMessage = fmt.Sprintf("%s: expected\n\t%v\ngot\n\t%v", test.description, testErr, err)
return false, nil
}
} else {
if err != nil {
failMessage = fmt.Sprintf("%s: unexpected error: %v", test.description, err)
return false, nil
}
}
if (actualResponse.Allowed != test.response.Allowed) || (!strings.HasPrefix(actualResponse.Reason, test.response.Reason)) {
if test.localReview != nil {
failMessage = fmt.Sprintf("%s: from local review\n\t%#v\nexpected\n\t%#v\ngot\n\t%#v", test.description, test.localReview, &test.response, actualResponse)
} else {
failMessage = fmt.Sprintf("%s: from review\n\t%#v\nexpected\n\t%#v\ngot\n\t%#v", test.description, test.clusterReview, &test.response, actualResponse)
}
return false, nil
}
failMessage = ""
return true, nil
})
if err != nil {
t.Error(err)
}
if len(failMessage) != 0 {
t.Error(failMessage)
}
})
} else if !test.kubeSkip {
t.Errorf("%s: missing kube auth interface and test is not whitelisted", test.description)
}
}
// TODO handle Subresource and NonResourceAttributes
func toKubeSelfSAR(testNS string, sar *authorizationv1.LocalSubjectAccessReview) *kubeauthorizationv1.SelfSubjectAccessReview {
return &kubeauthorizationv1.SelfSubjectAccessReview{
Spec: kubeauthorizationv1.SelfSubjectAccessReviewSpec{
ResourceAttributes: &kubeauthorizationv1.ResourceAttributes{
Namespace: testNS,
Verb: sar.Verb,
Group: sar.Group,
Version: sar.Version,
Resource: sar.Resource,
Name: sar.ResourceName,
},
},
}
}
// TODO handle Extra/Scopes, Subresource and NonResourceAttributes
func toKubeLocalSAR(testNS string, sar *authorizationv1.LocalSubjectAccessReview) *kubeauthorizationv1.LocalSubjectAccessReview {
return &kubeauthorizationv1.LocalSubjectAccessReview{
ObjectMeta: metav1.ObjectMeta{Namespace: testNS},
Spec: kubeauthorizationv1.SubjectAccessReviewSpec{
User: sar.User,
Groups: sar.GroupsSlice,
ResourceAttributes: &kubeauthorizationv1.ResourceAttributes{
Namespace: testNS,
Verb: sar.Verb,
Group: sar.Group,
Version: sar.Version,
Resource: sar.Resource,
Name: sar.ResourceName,
},
},
}
}
// TODO handle Extra/Scopes, Subresource and NonResourceAttributes
func toKubeClusterSAR(sar *authorizationv1.SubjectAccessReview) *kubeauthorizationv1.SubjectAccessReview {
return &kubeauthorizationv1.SubjectAccessReview{
Spec: kubeauthorizationv1.SubjectAccessReviewSpec{
User: sar.User,
Groups: sar.GroupsSlice,
ResourceAttributes: &kubeauthorizationv1.ResourceAttributes{
Verb: sar.Verb,
Group: sar.Group,
Version: sar.Version,
Resource: sar.Resource,
Name: sar.ResourceName,
},
},
}
}