-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathrbac_test.go
More file actions
882 lines (849 loc) · 31.8 KB
/
rbac_test.go
File metadata and controls
882 lines (849 loc) · 31.8 KB
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
package authorization
import (
"context"
"errors"
"fmt"
"strings"
"testing"
"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/api/meta/testrestmapper"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apiserver/pkg/authentication/user"
"k8s.io/apiserver/pkg/authorization/authorizer"
"k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/kubernetes/pkg/registry/rbac/validation"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
)
var (
testManifest = `apiVersion: v1
kind: Service
metadata:
name: test-service
namespace: test-namespace
spec:
clusterIP: None
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: test-extension-role
namespace: test-namespace
rules:
- apiGroups: ["*"]
resources: [serviceaccounts]
verbs: [watch]
- apiGroups: ["*"]
resources: [certificates]
verbs: [create]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: test-extension-binding
namespace: test-namespace
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: test-extension-role
subjects:
- kind: ServiceAccount
name: test-serviceaccount
namespace: test-namespace
`
testManifestMultiNamespace = `apiVersion: v1
kind: Service
metadata:
name: test-service
namespace: test-namespace
spec:
clusterIP: None
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: test-extension-role
namespace: test-namespace
rules:
- apiGroups: ["*"]
resources: [serviceaccounts]
verbs: [watch]
- apiGroups: ["*"]
resources: [certificates]
verbs: [create]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: test-extension-binding
namespace: test-namespace
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: test-extension-role
subjects:
- kind: ServiceAccount
name: test-serviceaccount
namespace: test-namespace
---
kind: Service
metadata:
name: test-service
namespace: a-test-namespace
spec:
clusterIP: None
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: test-extension-role
namespace: a-test-namespace
rules:
- apiGroups: ["*"]
resources: [serviceaccounts]
verbs: [watch]
- apiGroups: ["*"]
resources: [certificates]
verbs: [create]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: test-extension-binding
namespace: a-test-namespace
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: test-extension-role
subjects:
- kind: ServiceAccount
name: test-serviceaccount
namespace: a-test-namespace
`
saName = "test-serviceaccount"
ns = "test-namespace"
testUser = &user.DefaultInfo{Name: fmt.Sprintf("system:serviceaccount:%s:%s", ns, saName)}
objects = []client.Object{
&corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "test-namespace",
},
},
&rbacv1.ClusterRoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "admin-clusterrole-binding",
},
Subjects: []rbacv1.Subject{
{
Kind: "ServiceAccount",
Name: saName,
Namespace: ns,
},
},
RoleRef: rbacv1.RoleRef{
Name: "admin-clusterrole",
Kind: "ClusterRole",
},
},
&corev1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Name: "test-serviceaccount",
Namespace: "test-namespace",
},
},
}
privilegedClusterRole = &rbacv1.ClusterRole{
ObjectMeta: metav1.ObjectMeta{
Name: "admin-clusterrole",
},
Rules: []rbacv1.PolicyRule{
{
APIGroups: []string{"*"},
Resources: []string{"*"},
Verbs: []string{"*"},
},
},
}
limitedClusterRole = &rbacv1.ClusterRole{
ObjectMeta: metav1.ObjectMeta{
Name: "admin-clusterrole",
},
Rules: []rbacv1.PolicyRule{
{
APIGroups: []string{""},
Resources: []string{""},
Verbs: []string{""},
},
},
}
escalatingClusterRole = &rbacv1.ClusterRole{
ObjectMeta: metav1.ObjectMeta{
Name: "admin-clusterrole",
},
Rules: []rbacv1.PolicyRule{
{
APIGroups: []string{"*"},
Resources: []string{"serviceaccounts", "services"},
Verbs: []string{"*"},
},
{
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"roles", "clusterroles", "rolebindings", "clusterrolebindings"},
Verbs: []string{"get", "patch", "watch", "list", "create", "update", "delete", "escalate", "bind"},
},
},
}
expectedSingleNamespaceMissingRules = []ScopedPolicyRules{
{
Namespace: "",
MissingRules: []rbacv1.PolicyRule{
{
Verbs: []string{"list", "watch"},
APIGroups: []string{""},
Resources: []string{"services"},
ResourceNames: []string(nil),
NonResourceURLs: []string(nil)},
{
Verbs: []string{"list", "watch"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"rolebindings"},
ResourceNames: []string(nil),
NonResourceURLs: []string(nil)},
{
Verbs: []string{"list", "watch"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"roles"},
ResourceNames: []string(nil),
NonResourceURLs: []string(nil),
},
},
},
{
Namespace: "test-namespace",
MissingRules: []rbacv1.PolicyRule{
{
Verbs: []string{"create"},
APIGroups: []string{"*"},
Resources: []string{"certificates"}},
{
Verbs: []string{"create"},
APIGroups: []string{""},
Resources: []string{"services"}},
{
Verbs: []string{"create"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"rolebindings"}},
{
Verbs: []string{"create"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"roles"}},
{
Verbs: []string{"delete", "get", "patch", "update"},
APIGroups: []string{""},
Resources: []string{"services"},
ResourceNames: []string{"test-service"}},
{
Verbs: []string{"delete", "get", "patch", "update"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"rolebindings"},
ResourceNames: []string{"test-extension-binding"}},
{
Verbs: []string{"delete", "get", "patch", "update"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"roles"},
ResourceNames: []string{"test-extension-role"}},
{
Verbs: []string{"watch"},
APIGroups: []string{"*"},
Resources: []string{"serviceaccounts"},
},
},
},
}
expectedMultiNamespaceMissingRules = []ScopedPolicyRules{
{
Namespace: "",
MissingRules: []rbacv1.PolicyRule{
{
Verbs: []string{"list", "watch"},
APIGroups: []string{""},
Resources: []string{"services"},
ResourceNames: []string(nil),
NonResourceURLs: []string(nil)},
{
Verbs: []string{"list", "watch"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"rolebindings"},
ResourceNames: []string(nil),
NonResourceURLs: []string(nil)},
{
Verbs: []string{"list", "watch"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"roles"},
ResourceNames: []string(nil),
NonResourceURLs: []string(nil),
},
},
},
{
Namespace: "a-test-namespace",
MissingRules: []rbacv1.PolicyRule{
{
Verbs: []string{"create"},
APIGroups: []string{"*"},
Resources: []string{"certificates"}},
{
Verbs: []string{"create"},
APIGroups: []string{""},
Resources: []string{"services"}},
{
Verbs: []string{"create"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"rolebindings"}},
{
Verbs: []string{"create"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"roles"}},
{
Verbs: []string{"delete", "get", "patch", "update"},
APIGroups: []string{""},
Resources: []string{"services"},
ResourceNames: []string{"test-service"}},
{
Verbs: []string{"delete", "get", "patch", "update"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"rolebindings"},
ResourceNames: []string{"test-extension-binding"}},
{
Verbs: []string{"delete", "get", "patch", "update"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"roles"},
ResourceNames: []string{"test-extension-role"}},
{
Verbs: []string{"watch"},
APIGroups: []string{"*"},
Resources: []string{"serviceaccounts"},
},
},
},
{
Namespace: "test-namespace",
MissingRules: []rbacv1.PolicyRule{
{
Verbs: []string{"create"},
APIGroups: []string{"*"},
Resources: []string{"certificates"}},
{
Verbs: []string{"create"},
APIGroups: []string{""},
Resources: []string{"services"}},
{
Verbs: []string{"create"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"rolebindings"}},
{
Verbs: []string{"create"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"roles"}},
{
Verbs: []string{"delete", "get", "patch", "update"},
APIGroups: []string{""},
Resources: []string{"services"},
ResourceNames: []string{"test-service"}},
{
Verbs: []string{"delete", "get", "patch", "update"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"rolebindings"},
ResourceNames: []string{"test-extension-binding"}},
{
Verbs: []string{"delete", "get", "patch", "update"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"roles"},
ResourceNames: []string{"test-extension-role"}},
{
Verbs: []string{"watch"},
APIGroups: []string{"*"},
Resources: []string{"serviceaccounts"},
},
},
},
}
)
func setupFakeClient(role client.Object) client.Client {
s := runtime.NewScheme()
_ = corev1.AddToScheme(s)
_ = rbacv1.AddToScheme(s)
restMapper := testrestmapper.TestOnlyStaticRESTMapper(s)
fakeClientBuilder := fake.NewClientBuilder().WithObjects(append(objects, role)...).WithRESTMapper(restMapper)
return fakeClientBuilder.Build()
}
func TestPreAuthorize_Success(t *testing.T) {
t.Run("preauthorize succeeds with no missing rbac rules", func(t *testing.T) {
fakeClient := setupFakeClient(privilegedClusterRole)
preAuth := NewRBACPreAuthorizer(fakeClient, WithClusterCollectionVerbs("list", "watch"))
missingRules, err := preAuth.PreAuthorize(context.TODO(), testUser, strings.NewReader(testManifest))
require.NoError(t, err)
require.Equal(t, []ScopedPolicyRules{}, missingRules)
})
}
func TestPreAuthorize_MissingRBAC(t *testing.T) {
t.Run("preauthorize fails and finds missing rbac rules", func(t *testing.T) {
fakeClient := setupFakeClient(limitedClusterRole)
preAuth := NewRBACPreAuthorizer(fakeClient, WithClusterCollectionVerbs("list", "watch"))
missingRules, err := preAuth.PreAuthorize(context.TODO(), testUser, strings.NewReader(testManifest))
require.NoError(t, err)
require.Equal(t, expectedSingleNamespaceMissingRules, missingRules)
})
}
func TestPreAuthorizeMultiNamespace_MissingRBAC(t *testing.T) {
t.Run("preauthorize fails and finds missing rbac rules in multiple namespaces", func(t *testing.T) {
fakeClient := setupFakeClient(limitedClusterRole)
preAuth := NewRBACPreAuthorizer(fakeClient, WithClusterCollectionVerbs("list", "watch"))
missingRules, err := preAuth.PreAuthorize(context.TODO(), testUser, strings.NewReader(testManifestMultiNamespace))
require.NoError(t, err)
require.Equal(t, expectedMultiNamespaceMissingRules, missingRules)
})
}
func TestPreAuthorize_CheckEscalation(t *testing.T) {
t.Run("preauthorize succeeds with no missing rbac rules", func(t *testing.T) {
fakeClient := setupFakeClient(escalatingClusterRole)
preAuth := NewRBACPreAuthorizer(fakeClient, WithClusterCollectionVerbs("list", "watch"))
missingRules, err := preAuth.PreAuthorize(context.TODO(), testUser, strings.NewReader(testManifest))
require.NoError(t, err)
require.Equal(t, []ScopedPolicyRules{}, missingRules)
})
}
func TestPreAuthorize_AdditionalRequiredPerms_MissingRBAC(t *testing.T) {
t.Run("preauthorize fails and finds missing rbac rules coming from the additional required permissions", func(t *testing.T) {
fakeClient := setupFakeClient(escalatingClusterRole)
preAuth := NewRBACPreAuthorizer(fakeClient, WithClusterCollectionVerbs("list", "watch"))
missingRules, err := preAuth.PreAuthorize(context.TODO(), testUser, strings.NewReader(testManifest), func(user user.Info) []authorizer.AttributesRecord {
return []authorizer.AttributesRecord{
{
User: user,
Verb: "create",
APIGroup: corev1.SchemeGroupVersion.Group,
APIVersion: corev1.SchemeGroupVersion.Version,
Resource: "pods",
ResourceRequest: true,
},
}
})
require.NoError(t, err)
require.Equal(t, []ScopedPolicyRules{
{
Namespace: "",
MissingRules: []rbacv1.PolicyRule{
{
Verbs: []string{"create"},
APIGroups: []string{""},
Resources: []string{"pods"},
},
},
},
}, missingRules)
})
}
func TestPreAuthorize_WithClusterCollectionVerbs(t *testing.T) {
// expectedNamespacedMissingRules are the missing rules expected in the "test-namespace"
// namespace regardless of cluster collection verb configuration. These come from object
// verbs (get, patch, update, delete), namespaced collection verbs (create), and the
// escalation check for the role/rolebinding in the manifest.
expectedNamespacedMissingRules := ScopedPolicyRules{
Namespace: "test-namespace",
MissingRules: []rbacv1.PolicyRule{
{
Verbs: []string{"create"},
APIGroups: []string{"*"},
Resources: []string{"certificates"}},
{
Verbs: []string{"create"},
APIGroups: []string{""},
Resources: []string{"services"}},
{
Verbs: []string{"create"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"rolebindings"}},
{
Verbs: []string{"create"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"roles"}},
{
Verbs: []string{"delete", "get", "patch", "update"},
APIGroups: []string{""},
Resources: []string{"services"},
ResourceNames: []string{"test-service"}},
{
Verbs: []string{"delete", "get", "patch", "update"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"rolebindings"},
ResourceNames: []string{"test-extension-binding"}},
{
Verbs: []string{"delete", "get", "patch", "update"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"roles"},
ResourceNames: []string{"test-extension-role"}},
{
Verbs: []string{"watch"},
APIGroups: []string{"*"},
Resources: []string{"serviceaccounts"},
},
},
}
t.Run("no cluster collection verbs option omits cluster-scoped collection rules", func(t *testing.T) {
fakeClient := setupFakeClient(limitedClusterRole)
preAuth := NewRBACPreAuthorizer(fakeClient)
missingRules, err := preAuth.PreAuthorize(context.TODO(), testUser, strings.NewReader(testManifest))
require.NoError(t, err)
// With no cluster collection verbs, there should be no cluster-scoped (namespace="") missing rules
require.Equal(t, []ScopedPolicyRules{expectedNamespacedMissingRules}, missingRules)
})
t.Run("cluster verbs option only checks those verbs at cluster scope", func(t *testing.T) {
fakeClient := setupFakeClient(limitedClusterRole)
preAuth := NewRBACPreAuthorizer(fakeClient, WithClusterCollectionVerbs("get", "patch", "update"))
missingRules, err := preAuth.PreAuthorize(context.TODO(), testUser, strings.NewReader(testManifest))
require.NoError(t, err)
require.Equal(t, []ScopedPolicyRules{
{
Namespace: "",
MissingRules: []rbacv1.PolicyRule{
{
Verbs: []string{"get", "patch", "update"},
APIGroups: []string{""},
Resources: []string{"services"},
ResourceNames: []string(nil),
NonResourceURLs: []string(nil)},
{
Verbs: []string{"get", "patch", "update"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"rolebindings"},
ResourceNames: []string(nil),
NonResourceURLs: []string(nil)},
{
Verbs: []string{"get", "patch", "update"},
APIGroups: []string{"rbac.authorization.k8s.io"},
Resources: []string{"roles"},
ResourceNames: []string(nil),
NonResourceURLs: []string(nil),
},
},
},
expectedNamespacedMissingRules,
}, missingRules)
})
t.Run("privileged user with no cluster collection verbs succeeds", func(t *testing.T) {
fakeClient := setupFakeClient(privilegedClusterRole)
preAuth := NewRBACPreAuthorizer(fakeClient)
missingRules, err := preAuth.PreAuthorize(context.TODO(), testUser, strings.NewReader(testManifest))
require.NoError(t, err)
require.Equal(t, []ScopedPolicyRules{}, missingRules)
})
}
func TestPreAuthorize_NamespacedCollectionVerbs(t *testing.T) {
// With namespacedCollectionVerbs now being a fixed variable (containing "create"),
// this test verifies that "create" permissions are always checked at the namespace level.
t.Run("create verb is always checked as namespaced collection verb", func(t *testing.T) {
fakeClient := setupFakeClient(limitedClusterRole)
preAuth := NewRBACPreAuthorizer(fakeClient, WithClusterCollectionVerbs("list", "watch"))
missingRules, err := preAuth.PreAuthorize(context.TODO(), testUser, strings.NewReader(testManifest))
require.NoError(t, err)
// The "create" verb should always appear in missing rules because it's part of the
// namespacedCollectionVerbs. This test verifies expectedSingleNamespaceMissingRules
// which includes "create" verbs for namespace-scoped resources.
require.Equal(t, expectedSingleNamespaceMissingRules, missingRules)
})
t.Run("privileged user with namespaced collection verbs succeeds", func(t *testing.T) {
fakeClient := setupFakeClient(privilegedClusterRole)
preAuth := NewRBACPreAuthorizer(fakeClient)
missingRules, err := preAuth.PreAuthorize(context.TODO(), testUser, strings.NewReader(testManifest))
require.NoError(t, err)
require.Equal(t, []ScopedPolicyRules{}, missingRules)
})
}
// TestParseEscalationErrorForMissingRules Are tests with respect to https://github.com/kubernetes/api/blob/e8d4d542f6a9a16a694bfc8e3b8cd1557eecfc9d/rbac/v1/types.go#L49-L74
// Goal is: prove the regex works as planned AND that if the error messages ever change we'll learn about it with these tests
func TestParseEscalationErrorForMissingRules_ParsingLogic(t *testing.T) {
testCases := []struct {
name string
inputError error
expectedResult *parseResult
expectError require.ErrorAssertionFunc
}{
{
name: "One Missing Resource Rule",
inputError: errors.New(`user "test-user" (groups=["test"]) is attempting to grant RBAC permissions not currently held:
{APIGroups:["apps"], Resources:["deployments"], Verbs:["get"]}`),
expectedResult: &parseResult{
MissingRules: []rbacv1.PolicyRule{
{APIGroups: []string{"apps"}, Resources: []string{"deployments"}, Verbs: []string{"get"}},
},
},
expectError: require.NoError,
},
{
name: "Multiple Missing Rules (Resource + NonResource)",
inputError: errors.New(`user "sa" (groups=["system:authenticated"]) is attempting to grant RBAC permissions not currently held:
{APIGroups:[""], Resources:["pods"], Verbs:["list" "watch"]}
{NonResourceURLs:["/healthz"], Verbs:["get"]}`),
expectedResult: &parseResult{
MissingRules: []rbacv1.PolicyRule{
{APIGroups: []string{""}, Resources: []string{"pods"}, Verbs: []string{"list", "watch"}},
{NonResourceURLs: []string{"/healthz"}, Verbs: []string{"get"}},
},
},
expectError: require.NoError,
},
{
name: "One Missing Rule with Resolution Errors",
inputError: errors.New(`user "test-admin" (groups=["system:masters"]) is attempting to grant RBAC permissions not currently held:
{APIGroups:["batch"], Resources:["jobs"], Verbs:["create"]}; resolution errors: [role "missing-role" not found]`),
expectedResult: &parseResult{
MissingRules: []rbacv1.PolicyRule{
{APIGroups: []string{"batch"}, Resources: []string{"jobs"}, Verbs: []string{"create"}},
},
ResolutionErrors: errors.New(`[role "missing-role" not found]`),
},
expectError: require.NoError,
},
{
name: "Multiple Missing Rules with Resolution Errors",
inputError: errors.New(`user "another-user" (groups=[]) is attempting to grant RBAC permissions not currently held:
{APIGroups:[""], Resources:["secrets"], Verbs:["get"]}
{APIGroups:[""], Resources:["configmaps"], Verbs:["list"]}; resolution errors: [clusterrole "missing-clusterrole" not found, role "other-missing" not found]`),
expectedResult: &parseResult{
MissingRules: []rbacv1.PolicyRule{
{APIGroups: []string{""}, Resources: []string{"secrets"}, Verbs: []string{"get"}},
{APIGroups: []string{""}, Resources: []string{"configmaps"}, Verbs: []string{"list"}},
},
ResolutionErrors: errors.New(`[clusterrole "missing-clusterrole" not found, role "other-missing" not found]`),
},
expectError: require.NoError,
},
{
name: "Missing Rule (All Resource Fields)",
inputError: errors.New(`user "resource-name-user" (groups=["test"]) is attempting to grant RBAC permissions not currently held:
{APIGroups:["extensions"], Resources:["ingresses"], ResourceNames:["my-ingress"], Verbs:["update" "patch"]}`),
expectedResult: &parseResult{
MissingRules: []rbacv1.PolicyRule{
{APIGroups: []string{"extensions"}, Resources: []string{"ingresses"}, ResourceNames: []string{"my-ingress"}, Verbs: []string{"update", "patch"}},
},
},
expectError: require.NoError,
},
{
name: "Missing Rule (No ResourceNames)",
inputError: errors.New(`user "no-res-name-user" (groups=["test"]) is attempting to grant RBAC permissions not currently held:
{APIGroups:["networking.k8s.io"], Resources:["networkpolicies"], Verbs:["watch"]}`),
expectedResult: &parseResult{
MissingRules: []rbacv1.PolicyRule{
{APIGroups: []string{"networking.k8s.io"}, Resources: []string{"networkpolicies"}, Verbs: []string{"watch"}},
},
},
expectError: require.NoError,
},
{
name: "Missing Rule (NonResourceURLs only)",
inputError: errors.New(`user "url-user" (groups=["test"]) is attempting to grant RBAC permissions not currently held:
{NonResourceURLs:["/version" "/apis"], Verbs:["get"]}`),
expectedResult: &parseResult{
MissingRules: []rbacv1.PolicyRule{
{NonResourceURLs: []string{"/version", "/apis"}, Verbs: []string{"get"}},
},
},
expectError: require.NoError,
},
{
name: "Unexpected Format",
inputError: errors.New("some completely different error message that doesn't match"),
expectedResult: &parseResult{},
expectError: func(t require.TestingT, err error, i ...interface{}) {
require.ErrorContains(t, err, "unexpected format of escalation check error string")
},
},
{
name: "Empty Permissions String",
inputError: errors.New(`user "empty-perms" (groups=["test"]) is attempting to grant RBAC permissions not currently held:
`),
expectedResult: &parseResult{},
expectError: func(t require.TestingT, err error, i ...interface{}) {
require.ErrorContains(t, err, "unexpected format of escalation check error string")
},
},
{
name: "Rule with Empty Strings in lists",
inputError: errors.New(`user "empty-strings" (groups=["test"]) is attempting to grant RBAC permissions not currently held:
{APIGroups:["" "apps"], Resources:["" "deployments"], Verbs:["get" ""]}`),
expectedResult: &parseResult{
MissingRules: []rbacv1.PolicyRule{
{APIGroups: []string{"", "apps"}, Resources: []string{"", "deployments"}, Verbs: []string{"get", ""}},
},
},
expectError: require.NoError,
},
{
name: "Rule with Only Empty Verb",
inputError: errors.New(`user "empty-verb" (groups=["test"]) is attempting to grant RBAC permissions not currently held:
{APIGroups:[""], Resources:["pods"], Verbs:[""]}`),
expectedResult: &parseResult{
MissingRules: []rbacv1.PolicyRule{
{APIGroups: []string{""}, Resources: []string{"pods"}, Verbs: []string{""}},
},
},
expectError: require.NoError,
},
{
name: "Rule with no fields",
inputError: errors.New(`user "empty-verb" (groups=["test"]) is attempting to grant RBAC permissions not currently held:
{}`),
expectedResult: &parseResult{
MissingRules: []rbacv1.PolicyRule{{}},
},
expectError: require.NoError,
},
{
name: "Rule with no colon separator",
inputError: errors.New(`user "empty-verb" (groups=["test"]) is attempting to grant RBAC permissions not currently held:
{APIGroups:[""], Resources, Verbs:["get"]}
`),
expectedResult: &parseResult{},
expectError: func(t require.TestingT, err error, i ...interface{}) {
require.ErrorContains(t, err, `unexpected item "Resources": expected <Type>:[<values>...]`)
},
},
{
name: "Rule with unknown field",
inputError: errors.New(`user "empty-verb" (groups=["test"]) is attempting to grant RBAC permissions not currently held:
{FooBar:["baz"]}
{APIGroups:[""], Resources:["secrets"], Verbs:["get"]}
`),
expectedResult: &parseResult{
MissingRules: []rbacv1.PolicyRule{
{APIGroups: []string{""}, Resources: []string{"secrets"}, Verbs: []string{"get"}},
},
},
expectError: func(t require.TestingT, err error, i ...interface{}) {
require.ErrorContains(t, err, `unknown field: "FooBar"`)
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
rules, err := parseEscalationErrorForMissingRules(tc.inputError)
tc.expectError(t, err)
require.Equal(t, tc.expectedResult, rules)
})
}
}
func TestParseEscalationErrorForMissingRules_KubernetesCompatibility(t *testing.T) {
testCases := []struct {
name string
ruleResolver validation.AuthorizationRuleResolver
wantRules []rbacv1.PolicyRule
expectedErrorString string
expectedResult *parseResult
}{
{
name: "missing rules",
ruleResolver: mockRulesResolver{
rules: []rbacv1.PolicyRule{},
err: nil,
},
wantRules: []rbacv1.PolicyRule{
{APIGroups: []string{""}, Resources: []string{"secrets"}, Verbs: []string{"get"}, ResourceNames: []string{"test-secret"}},
{APIGroups: []string{""}, Resources: []string{"configmaps"}, Verbs: []string{"get", "list", "watch"}},
{APIGroups: []string{"apps"}, Resources: []string{"deployments", "replicasets"}, Verbs: []string{"create", "update", "patch", "delete"}},
{NonResourceURLs: []string{"/healthz", "/livez"}, Verbs: []string{"get", "post"}},
},
expectedErrorString: `user "user" (groups=["a" "b"]) is attempting to grant RBAC permissions not currently held:
{APIGroups:[""], Resources:["configmaps"], Verbs:["get" "list" "watch"]}
{APIGroups:[""], Resources:["secrets"], ResourceNames:["test-secret"], Verbs:["get"]}
{APIGroups:["apps"], Resources:["deployments"], Verbs:["create" "update" "patch" "delete"]}
{APIGroups:["apps"], Resources:["replicasets"], Verbs:["create" "update" "patch" "delete"]}
{NonResourceURLs:["/healthz"], Verbs:["get"]}
{NonResourceURLs:["/healthz"], Verbs:["post"]}
{NonResourceURLs:["/livez"], Verbs:["get"]}
{NonResourceURLs:["/livez"], Verbs:["post"]}`,
expectedResult: &parseResult{
MissingRules: []rbacv1.PolicyRule{
{APIGroups: []string{""}, Resources: []string{"configmaps"}, Verbs: []string{"get", "list", "watch"}},
{APIGroups: []string{""}, Resources: []string{"secrets"}, Verbs: []string{"get"}, ResourceNames: []string{"test-secret"}},
{APIGroups: []string{"apps"}, Resources: []string{"deployments"}, Verbs: []string{"create", "update", "patch", "delete"}},
{APIGroups: []string{"apps"}, Resources: []string{"replicasets"}, Verbs: []string{"create", "update", "patch", "delete"}},
{NonResourceURLs: []string{"/healthz"}, Verbs: []string{"get"}},
{NonResourceURLs: []string{"/healthz"}, Verbs: []string{"post"}},
{NonResourceURLs: []string{"/livez"}, Verbs: []string{"get"}},
{NonResourceURLs: []string{"/livez"}, Verbs: []string{"post"}},
},
},
},
{
name: "resolution failure",
ruleResolver: mockRulesResolver{
rules: []rbacv1.PolicyRule{},
err: errors.New("resolution error"),
},
wantRules: []rbacv1.PolicyRule{
{APIGroups: []string{""}, Resources: []string{"secrets"}, Verbs: []string{"get"}, ResourceNames: []string{"test-secret"}},
{APIGroups: []string{""}, Resources: []string{"configmaps"}, Verbs: []string{"get", "list", "watch"}},
{APIGroups: []string{"apps"}, Resources: []string{"deployments", "replicasets"}, Verbs: []string{"create", "update", "patch", "delete"}},
{NonResourceURLs: []string{"/healthz", "/livez"}, Verbs: []string{"get", "post"}},
},
expectedErrorString: `user "user" (groups=["a" "b"]) is attempting to grant RBAC permissions not currently held:
{APIGroups:[""], Resources:["configmaps"], Verbs:["get" "list" "watch"]}
{APIGroups:[""], Resources:["secrets"], ResourceNames:["test-secret"], Verbs:["get"]}
{APIGroups:["apps"], Resources:["deployments"], Verbs:["create" "update" "patch" "delete"]}
{APIGroups:["apps"], Resources:["replicasets"], Verbs:["create" "update" "patch" "delete"]}
{NonResourceURLs:["/healthz"], Verbs:["get"]}
{NonResourceURLs:["/healthz"], Verbs:["post"]}
{NonResourceURLs:["/livez"], Verbs:["get"]}
{NonResourceURLs:["/livez"], Verbs:["post"]}; resolution errors: [resolution error]`,
expectedResult: &parseResult{
MissingRules: []rbacv1.PolicyRule{
{APIGroups: []string{""}, Resources: []string{"configmaps"}, Verbs: []string{"get", "list", "watch"}},
{APIGroups: []string{""}, Resources: []string{"secrets"}, Verbs: []string{"get"}, ResourceNames: []string{"test-secret"}},
{APIGroups: []string{"apps"}, Resources: []string{"deployments"}, Verbs: []string{"create", "update", "patch", "delete"}},
{APIGroups: []string{"apps"}, Resources: []string{"replicasets"}, Verbs: []string{"create", "update", "patch", "delete"}},
{NonResourceURLs: []string{"/healthz"}, Verbs: []string{"get"}},
{NonResourceURLs: []string{"/healthz"}, Verbs: []string{"post"}},
{NonResourceURLs: []string{"/livez"}, Verbs: []string{"get"}},
{NonResourceURLs: []string{"/livez"}, Verbs: []string{"post"}},
},
ResolutionErrors: errors.New("[resolution error]"),
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
ctx := request.WithUser(request.WithNamespace(context.Background(), "namespace"), &user.DefaultInfo{
Name: "user",
Groups: []string{"a", "b"},
})
// Let's actually call the upstream function that generates and returns the
// error message that we are attempting to parse correctly. The hope is that
// these tests will start failing if we bump to a new version of kubernetes
// that causes our parsing logic to be incorrect.
err := validation.ConfirmNoEscalation(ctx, tc.ruleResolver, tc.wantRules)
require.Error(t, err)
require.Equal(t, tc.expectedErrorString, err.Error())
res, err := parseEscalationErrorForMissingRules(err)
require.NoError(t, err)
require.Equal(t, tc.expectedResult, res)
})
}
}
type mockRulesResolver struct {
rules []rbacv1.PolicyRule
err error
}
func (m mockRulesResolver) GetRoleReferenceRules(ctx context.Context, roleRef rbacv1.RoleRef, namespace string) ([]rbacv1.PolicyRule, error) {
panic("unimplemented")
}
func (m mockRulesResolver) RulesFor(ctx context.Context, user user.Info, namespace string) ([]rbacv1.PolicyRule, error) {
return m.rules, m.err
}
func (m mockRulesResolver) VisitRulesFor(ctx context.Context, user user.Info, namespace string, visitor func(source fmt.Stringer, rule *rbacv1.PolicyRule, err error) bool) {
panic("unimplemented")
}