|
| 1 | +/* |
| 2 | +Copyright 2026 The Flux 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 controller |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "fmt" |
| 22 | + "testing" |
| 23 | + "time" |
| 24 | + |
| 25 | + "github.com/fluxcd/pkg/apis/meta" |
| 26 | + "github.com/fluxcd/pkg/testserver" |
| 27 | + sourcev1 "github.com/fluxcd/source-controller/api/v1" |
| 28 | + . "github.com/onsi/gomega" |
| 29 | + corev1 "k8s.io/api/core/v1" |
| 30 | + rbacv1 "k8s.io/api/rbac/v1" |
| 31 | + apimeta "k8s.io/apimachinery/pkg/api/meta" |
| 32 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 33 | + "k8s.io/apimachinery/pkg/runtime/schema" |
| 34 | + "k8s.io/apimachinery/pkg/types" |
| 35 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 36 | + |
| 37 | + kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1" |
| 38 | +) |
| 39 | + |
| 40 | +func TestKustomizationReconciler_AppliesRoleAndRoleBinding(t *testing.T) { |
| 41 | + g := NewWithT(t) |
| 42 | + id := "custom-stage-" + randStringRunes(5) |
| 43 | + revision := "v1.0.0" |
| 44 | + |
| 45 | + err := createNamespace(id) |
| 46 | + g.Expect(err).NotTo(HaveOccurred(), "failed to create test namespace") |
| 47 | + |
| 48 | + err = createKubeConfigSecret(id) |
| 49 | + g.Expect(err).NotTo(HaveOccurred(), "failed to create kubeconfig secret") |
| 50 | + |
| 51 | + // Create a ServiceAccount with limited RBAC (not cluster-admin). |
| 52 | + // The SA can create Roles and RoleBindings, and has the permissions |
| 53 | + // that the test Role will grant (configmaps get/list). |
| 54 | + sa := corev1.ServiceAccount{ |
| 55 | + ObjectMeta: metav1.ObjectMeta{ |
| 56 | + Name: id, |
| 57 | + Namespace: id, |
| 58 | + }, |
| 59 | + } |
| 60 | + g.Expect(k8sClient.Create(context.Background(), &sa)).To(Succeed()) |
| 61 | + |
| 62 | + cr := rbacv1.ClusterRole{ |
| 63 | + ObjectMeta: metav1.ObjectMeta{ |
| 64 | + Name: id, |
| 65 | + }, |
| 66 | + Rules: []rbacv1.PolicyRule{ |
| 67 | + { |
| 68 | + APIGroups: []string{"rbac.authorization.k8s.io"}, |
| 69 | + Resources: []string{"roles", "rolebindings"}, |
| 70 | + Verbs: []string{"create", "update", "delete", "get", "list", "watch", "patch"}, |
| 71 | + }, |
| 72 | + // Grant the same permissions that the test Role will grant, |
| 73 | + // so RBAC escalation prevention allows creating the Role and |
| 74 | + // RoleBinding. |
| 75 | + { |
| 76 | + APIGroups: []string{""}, |
| 77 | + Resources: []string{"configmaps"}, |
| 78 | + Verbs: []string{"get", "list"}, |
| 79 | + }, |
| 80 | + }, |
| 81 | + } |
| 82 | + g.Expect(k8sClient.Create(context.Background(), &cr)).To(Succeed()) |
| 83 | + |
| 84 | + crb := rbacv1.ClusterRoleBinding{ |
| 85 | + ObjectMeta: metav1.ObjectMeta{ |
| 86 | + Name: id, |
| 87 | + }, |
| 88 | + Subjects: []rbacv1.Subject{ |
| 89 | + { |
| 90 | + Kind: "ServiceAccount", |
| 91 | + Name: sa.Name, |
| 92 | + Namespace: sa.Namespace, |
| 93 | + }, |
| 94 | + }, |
| 95 | + RoleRef: rbacv1.RoleRef{ |
| 96 | + APIGroup: "rbac.authorization.k8s.io", |
| 97 | + Kind: "ClusterRole", |
| 98 | + Name: cr.Name, |
| 99 | + }, |
| 100 | + } |
| 101 | + g.Expect(k8sClient.Create(context.Background(), &crb)).To(Succeed()) |
| 102 | + |
| 103 | + // Manifests contain a Role and RoleBinding that references the Role. |
| 104 | + // Without CustomStageKinds, the RoleBinding will fail to apply because |
| 105 | + // the Role doesn't exist yet (both are sorted in the same stage). |
| 106 | + manifests := func(name string) []testserver.File { |
| 107 | + return []testserver.File{ |
| 108 | + { |
| 109 | + Name: "role.yaml", |
| 110 | + Body: fmt.Sprintf(`--- |
| 111 | +apiVersion: rbac.authorization.k8s.io/v1 |
| 112 | +kind: Role |
| 113 | +metadata: |
| 114 | + name: %[1]s-role |
| 115 | + namespace: %[1]s |
| 116 | +rules: |
| 117 | +- apiGroups: [""] |
| 118 | + resources: ["configmaps"] |
| 119 | + verbs: ["get", "list"] |
| 120 | +`, name), |
| 121 | + }, |
| 122 | + { |
| 123 | + Name: "rolebinding.yaml", |
| 124 | + Body: fmt.Sprintf(`--- |
| 125 | +apiVersion: rbac.authorization.k8s.io/v1 |
| 126 | +kind: RoleBinding |
| 127 | +metadata: |
| 128 | + name: %[1]s-rolebinding |
| 129 | + namespace: %[1]s |
| 130 | +roleRef: |
| 131 | + apiGroup: rbac.authorization.k8s.io |
| 132 | + kind: Role |
| 133 | + name: %[1]s-role |
| 134 | +subjects: |
| 135 | +- kind: ServiceAccount |
| 136 | + name: default |
| 137 | + namespace: %[1]s |
| 138 | +`, name), |
| 139 | + }, |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + artifact, err := testServer.ArtifactFromFiles(manifests(id)) |
| 144 | + g.Expect(err).NotTo(HaveOccurred(), "failed to create artifact from files") |
| 145 | + |
| 146 | + repositoryName := types.NamespacedName{ |
| 147 | + Name: randStringRunes(5), |
| 148 | + Namespace: id, |
| 149 | + } |
| 150 | + |
| 151 | + err = applyGitRepository(repositoryName, artifact, revision) |
| 152 | + g.Expect(err).NotTo(HaveOccurred()) |
| 153 | + |
| 154 | + kustomizationKey := types.NamespacedName{ |
| 155 | + Name: randStringRunes(5), |
| 156 | + Namespace: id, |
| 157 | + } |
| 158 | + kustomization := &kustomizev1.Kustomization{ |
| 159 | + ObjectMeta: metav1.ObjectMeta{ |
| 160 | + Name: kustomizationKey.Name, |
| 161 | + Namespace: kustomizationKey.Namespace, |
| 162 | + }, |
| 163 | + Spec: kustomizev1.KustomizationSpec{ |
| 164 | + Interval: metav1.Duration{Duration: reconciliationInterval}, |
| 165 | + Path: "./", |
| 166 | + KubeConfig: &meta.KubeConfigReference{ |
| 167 | + SecretRef: &meta.SecretKeyReference{ |
| 168 | + Name: "kubeconfig", |
| 169 | + }, |
| 170 | + }, |
| 171 | + SourceRef: kustomizev1.CrossNamespaceSourceReference{ |
| 172 | + Name: repositoryName.Name, |
| 173 | + Namespace: repositoryName.Namespace, |
| 174 | + Kind: sourcev1.GitRepositoryKind, |
| 175 | + }, |
| 176 | + TargetNamespace: id, |
| 177 | + ServiceAccountName: id, // Impersonate the limited SA |
| 178 | + Prune: true, |
| 179 | + }, |
| 180 | + } |
| 181 | + |
| 182 | + g.Expect(k8sClient.Create(context.Background(), kustomization)).To(Succeed()) |
| 183 | + |
| 184 | + resultK := &kustomizev1.Kustomization{} |
| 185 | + readyCondition := &metav1.Condition{} |
| 186 | + |
| 187 | + t.Run("fails to reconcile Role and RoleBinding without custom stage", func(t *testing.T) { |
| 188 | + g.Eventually(func() bool { |
| 189 | + _ = k8sClient.Get(context.Background(), client.ObjectKeyFromObject(kustomization), resultK) |
| 190 | + readyCondition = apimeta.FindStatusCondition(resultK.Status.Conditions, meta.ReadyCondition) |
| 191 | + return readyCondition != nil && readyCondition.Reason == meta.ReconciliationFailedReason |
| 192 | + }, timeout, time.Second).Should(BeTrue()) |
| 193 | + |
| 194 | + // The error message format is: |
| 195 | + // "RoleBinding/<namespace>/<name>-rolebinding not found: rolebindings.rbac.authorization.k8s.io \"<name>-role\" not found" |
| 196 | + // This proves that: |
| 197 | + // 1. The involved object is the RoleBinding (dry-run failed on it) |
| 198 | + // 2. The referenced Role was not found during dry-run validation |
| 199 | + expectedMsg := fmt.Sprintf( |
| 200 | + "RoleBinding/%[1]s/%[1]s-rolebinding not found: rolebindings.rbac.authorization.k8s.io %q not found", |
| 201 | + id, id+"-role") |
| 202 | + g.Expect(readyCondition.Message).To(HavePrefix(expectedMsg)) |
| 203 | + }) |
| 204 | + |
| 205 | + t.Run("reconciles Role and RoleBinding with custom stage", func(t *testing.T) { |
| 206 | + // Capture the current CustomStageKinds |
| 207 | + originalCustomStageKinds := reconciler.CustomStageKinds |
| 208 | + t.Cleanup(func() { |
| 209 | + reconciler.CustomStageKinds = originalCustomStageKinds |
| 210 | + }) |
| 211 | + |
| 212 | + // Set CustomStageKinds to include Role |
| 213 | + reconciler.CustomStageKinds = map[schema.GroupKind]struct{}{ |
| 214 | + {Group: "rbac.authorization.k8s.io", Kind: "Role"}: {}, |
| 215 | + } |
| 216 | + |
| 217 | + // Trigger reconciliation by updating the revision |
| 218 | + revision = "v2.0.0" |
| 219 | + err = applyGitRepository(repositoryName, artifact, revision) |
| 220 | + g.Expect(err).NotTo(HaveOccurred()) |
| 221 | + |
| 222 | + g.Eventually(func() bool { |
| 223 | + _ = k8sClient.Get(context.Background(), client.ObjectKeyFromObject(kustomization), resultK) |
| 224 | + readyCondition = apimeta.FindStatusCondition(resultK.Status.Conditions, meta.ReadyCondition) |
| 225 | + return resultK.Status.LastAppliedRevision == revision |
| 226 | + }, timeout, time.Second).Should(BeTrue()) |
| 227 | + |
| 228 | + g.Expect(readyCondition.Reason).To(Equal(meta.ReconciliationSucceededReason)) |
| 229 | + |
| 230 | + // Verify the Role and RoleBinding were created |
| 231 | + role := &rbacv1.Role{} |
| 232 | + err = k8sClient.Get(context.Background(), types.NamespacedName{Name: id + "-role", Namespace: id}, role) |
| 233 | + g.Expect(err).NotTo(HaveOccurred()) |
| 234 | + |
| 235 | + roleBinding := &rbacv1.RoleBinding{} |
| 236 | + err = k8sClient.Get(context.Background(), types.NamespacedName{Name: id + "-rolebinding", Namespace: id}, roleBinding) |
| 237 | + g.Expect(err).NotTo(HaveOccurred()) |
| 238 | + }) |
| 239 | +} |
0 commit comments