From d0b08e2e3223706d6d32af54a6c54f37d0123226 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Drzewiecki?= Date: Thu, 5 Dec 2024 16:30:58 +0100 Subject: [PATCH] should not delete ServiceAccounts CRBs --- .../runtime_fsm_apply_clusterrolebindings.go | 7 +++-- .../runtime/fsm/runtime_fsm_apply_crb_test.go | 27 +++++++++++++++++++ 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/internal/controller/runtime/fsm/runtime_fsm_apply_clusterrolebindings.go b/internal/controller/runtime/fsm/runtime_fsm_apply_clusterrolebindings.go index 33ad251b..49c6d3e6 100644 --- a/internal/controller/runtime/fsm/runtime_fsm_apply_clusterrolebindings.go +++ b/internal/controller/runtime/fsm/runtime_fsm_apply_clusterrolebindings.go @@ -111,10 +111,9 @@ func isRBACUserKindOneOf(names []string) func(rbacv1.Subject) bool { } } -func isRBACServiceAccountKindOneOf(names []string) func(rbacv1.Subject) bool { +func isRBACServiceAccountKind() func(rbacv1.Subject) bool { return func(s rbacv1.Subject) bool { - return s.Kind == rbacv1.ServiceAccountKind && - slices.Contains(names, s.Name) + return s.Kind == rbacv1.ServiceAccountKind } } @@ -136,7 +135,7 @@ func getRemoved(crbs []rbacv1.ClusterRoleBinding, admins []string) (removed []rb continue } - index = slices.IndexFunc(crb.Subjects, isRBACServiceAccountKindOneOf(admins)) + index = slices.IndexFunc(crb.Subjects, isRBACServiceAccountKind()) if index >= 0 { // cluster role binding does not contain serviceaccount subject continue diff --git a/internal/controller/runtime/fsm/runtime_fsm_apply_crb_test.go b/internal/controller/runtime/fsm/runtime_fsm_apply_crb_test.go index 62c78823..af233c8e 100644 --- a/internal/controller/runtime/fsm/runtime_fsm_apply_crb_test.go +++ b/internal/controller/runtime/fsm/runtime_fsm_apply_crb_test.go @@ -110,6 +110,14 @@ var _ = Describe(`runtime_fsm_apply_crb`, Label("applyCRB"), func() { }, expected: nil, }), + Entry("should not remove Service account CRB not managed by reconciler or KIM", tcCRBData{ + admins: []string{"test1", "test2"}, + crbs: []rbacv1.ClusterRoleBinding{ + toServiceAccountClusterRoleBinding("test3-should-stay"), + toServiceAccountClusterRoleBinding("test4-should-stay"), + }, + expected: nil, + }), Entry("should remove CRB managed by reconciler or KIM, that are not in the admin list", tcCRBData{ admins: []string{"test4", "test5"}, crbs: []rbacv1.ClusterRoleBinding{ @@ -285,3 +293,22 @@ func toManagedClusterRoleBinding(name, managedBy string) rbacv1.ClusterRoleBindi } return clusterRoleBinding } + +func toServiceAccountClusterRoleBinding(name string) rbacv1.ClusterRoleBinding { + return rbacv1.ClusterRoleBinding{ + ObjectMeta: metav1.ObjectMeta{ + Name: name, + }, + Subjects: []rbacv1.Subject{{ + Kind: rbacv1.ServiceAccountKind, + Name: "cluster-admin", + Namespace: "cicdnamespace", + APIGroup: rbacv1.GroupName, + }}, + RoleRef: rbacv1.RoleRef{ + APIGroup: rbacv1.GroupName, + Kind: "ClusterRole", + Name: "cluster-admin", + }, + } +}