diff --git a/api/v1beta1/zz_generated.deepcopy.go b/api/v1beta1/zz_generated.deepcopy.go index 9c18a7ce..e221219e 100644 --- a/api/v1beta1/zz_generated.deepcopy.go +++ b/api/v1beta1/zz_generated.deepcopy.go @@ -21,11 +21,12 @@ limitations under the License. package v1beta1 import ( - apiv1beta1 "github.com/projectsveltos/libsveltos/api/v1beta1" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/intstr" + + apiv1beta1 "github.com/projectsveltos/libsveltos/api/v1beta1" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index eb34aceb..953b0ea2 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -217,6 +217,7 @@ rules: - configurationgroups/status - debuggingconfigurations - eventtriggers + - rolerequests - sveltosclusters - sveltosclusters/status verbs: diff --git a/controllers/clustersummary_controller.go b/controllers/clustersummary_controller.go index 8bbd1317..1397fca4 100644 --- a/controllers/clustersummary_controller.go +++ b/controllers/clustersummary_controller.go @@ -160,6 +160,7 @@ type reconcileCooldown struct { //+kubebuilder:rbac:groups=lib.projectsveltos.io,resources=reloaders,verbs=get;list;watch;create;update;patch;delete //+kubebuilder:rbac:groups="events.k8s.io",resources=events,verbs=create;update;patch //+kubebuilder:rbac:groups=lib.projectsveltos.io,resources=configurationgroups,verbs=get;list;watch;create;delete;update;patch +//+kubebuilder:rbac:groups=lib.projectsveltos.io,resources=rolerequests,verbs=get;list;watch //+kubebuilder:rbac:groups=lib.projectsveltos.io,resources=configurationgroups/status,verbs=get;list;watch //+kubebuilder:rbac:groups=lib.projectsveltos.io,resources=configurationbundles,verbs=get;list;watch;create;delete;update;patch //+kubebuilder:rbac:groups=lib.projectsveltos.io,resources=configurationbundles/status,verbs=get;list;watch;update diff --git a/controllers/clustersummary_controller_test.go b/controllers/clustersummary_controller_test.go index 8ddf1609..905839c5 100644 --- a/controllers/clustersummary_controller_test.go +++ b/controllers/clustersummary_controller_test.go @@ -529,6 +529,15 @@ var _ = Describe("ClustersummaryController", func() { kubeconfigSecret.Data[testValueKey] = []byte("not a valid kubeconfig") Expect(testEnv.Update(context.TODO(), kubeconfigSecret)).To(Succeed()) + // testEnv.Client reads from a cache: the kubeconfig is read through it, so wait until the cache + // serves the corrupted one. Otherwise the previous, valid, kubeconfig is used and removal succeeds. + Eventually(func() bool { + current := &corev1.Secret{} + err := testEnv.Get(context.TODO(), + types.NamespacedName{Namespace: cluster.Namespace, Name: cluster.Name + kubeconfigPostfix}, current) + return err == nil && string(current.Data[testValueKey]) == "not a valid kubeconfig" + }, timeout, pollingInterval).Should(BeTrue()) + clusterSummaryScope, err := scope.NewClusterSummaryScope(&scope.ClusterSummaryScopeParams{ Client: testEnv.Client, Logger: textlogger.NewLogger(textlogger.NewConfig()), diff --git a/controllers/controllers_suite_test.go b/controllers/controllers_suite_test.go index af0ee56d..a5866cdf 100644 --- a/controllers/controllers_suite_test.go +++ b/controllers/controllers_suite_test.go @@ -142,6 +142,12 @@ var _ = BeforeSuite(func() { Expect(testEnv.Create(context.TODO(), clusterSetCRD)).To(Succeed()) Expect(waitForObject(context.TODO(), testEnv, clusterSetCRD)).To(Succeed()) + var roleRequestCRD *unstructured.Unstructured + roleRequestCRD, err = k8s_utils.GetUnstructured(libsveltoscrd.GetRoleRequestCRDYAML()) + Expect(err).To(BeNil()) + Expect(testEnv.Create(context.TODO(), roleRequestCRD)).To(Succeed()) + Expect(waitForObject(context.TODO(), testEnv, roleRequestCRD)).To(Succeed()) + projectsveltosNs := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: sveltosNamespace, diff --git a/controllers/export_test.go b/controllers/export_test.go index 56f66474..617f77eb 100644 --- a/controllers/export_test.go +++ b/controllers/export_test.go @@ -614,3 +614,7 @@ var NewKeyedLock = newKeyedLock func (k *keyedLock) Lock(ctx context.Context, key string) (unlock func(), err error) { return k.lock(ctx, key) } + +var ( + GetManagedClusterServiceAccountNamespace = getManagedClusterServiceAccountNamespace +) diff --git a/controllers/handlers_utils.go b/controllers/handlers_utils.go index 95c3e4e8..bfecf292 100644 --- a/controllers/handlers_utils.go +++ b/controllers/handlers_utils.go @@ -62,6 +62,7 @@ import ( "github.com/projectsveltos/libsveltos/lib/mgmtagent" "github.com/projectsveltos/libsveltos/lib/patcher" "github.com/projectsveltos/libsveltos/lib/pullmode" + "github.com/projectsveltos/libsveltos/lib/roles" libsveltostemplate "github.com/projectsveltos/libsveltos/lib/template" ) @@ -820,6 +821,52 @@ func getClusterSummaryAdmin(clusterSummary *configv1beta1.ClusterSummary) (names return } +// appendAdminSetters appends to setters the ones identifying the ServiceAccount sveltos-applier impersonates when +// applying resources on behalf of a tenant admin. Nothing is appended for a platform admin. +func appendAdminSetters(ctx context.Context, clusterSummary *configv1beta1.ClusterSummary, + setters []pullmode.Option) ([]pullmode.Option, error) { + + adminNamespace, adminName := getClusterSummaryAdmin(clusterSummary) + if adminName == "" { + return setters, nil + } + + setters = append(setters, pullmode.WithServiceAccount(adminNamespace, adminName)) + + managedClusterNamespace, err := getManagedClusterServiceAccountNamespace(ctx, clusterSummary, + adminNamespace, adminName) + if err != nil { + return nil, err + } + if managedClusterNamespace != "" { + setters = append(setters, pullmode.WithManagedClusterServiceAccountNamespace(managedClusterNamespace)) + } + + return setters, nil +} + +// getManagedClusterServiceAccountNamespace returns the namespace, in the managed cluster, of the ServiceAccount +// representing the admin (a ServiceAccount in the management cluster) of the ClusterSummary. sveltos-applier +// impersonates that ServiceAccount. +// The namespace is the one chosen by the RoleRequest granting the admin permissions in the cluster. An empty +// string is returned when there is none: the Sveltos namespace, which sveltos-applier knows, is then used. +func getManagedClusterServiceAccountNamespace(ctx context.Context, clusterSummary *configv1beta1.ClusterSummary, + adminNamespace, adminName string) (string, error) { + + clusterRef := getClusterSummaryClusterRef(clusterSummary) + namespace, err := roles.GetServiceAccountNamespaceInManagedCluster(ctx, getManagementClusterClient(), + &clusterRef, adminNamespace, adminName, "") + if err != nil { + if meta.IsNoMatchError(err) { + // RoleRequest CRD is not installed: no RoleRequest, so no custom namespace + return "", nil + } + return "", fmt.Errorf("failed to get the ServiceAccount namespace in the managed cluster: %w", err) + } + + return namespace, nil +} + // validateClusterSummaryAdmin verifies the tenant identity carried by the ClusterSummary labels. // A ClusterSummary with none of the labels is a platform admin one: nothing is impersonated. // As soon as one of the labels is present, both must be set to a non empty value. An empty @@ -2004,9 +2051,9 @@ func prepareSetters(ctx context.Context, clusterSummary *configv1beta1.ClusterSu setters = append(setters, pullmode.WithSourceStatus(libsveltosv1beta1.SourceStatusActive)) } - adminNamespace, adminName := getClusterSummaryAdmin(clusterSummary) - if adminName != "" { - setters = append(setters, pullmode.WithServiceAccount(adminNamespace, adminName)) + setters, err := appendAdminSetters(ctx, clusterSummary, setters) + if err != nil { + return nil, err } setters = append(setters, pullmode.WithRequestorHash(configurationHash)) diff --git a/controllers/handlers_utils_test.go b/controllers/handlers_utils_test.go index 58788260..80550977 100644 --- a/controllers/handlers_utils_test.go +++ b/controllers/handlers_utils_test.go @@ -24,6 +24,7 @@ import ( "path/filepath" "reflect" "strings" + "time" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -232,6 +233,106 @@ var _ = Describe("HandlersUtils", func() { Expect(saName).To(Equal(adminName)) }) + Context("getManagedClusterServiceAccountNamespace", func() { + var adminNamespace, adminName string + + BeforeEach(func() { + adminNamespace = randomString() + adminName = randomString() + }) + + // createRoleRequest creates a RoleRequest for the admin, with the given status in cluster + createRoleRequest := func(saNamespace, saName, managedClusterNamespace string, + clusterName string, status libsveltosv1beta1.SveltosFeatureStatus) *libsveltosv1beta1.RoleRequest { + + roleRequest := &libsveltosv1beta1.RoleRequest{ + ObjectMeta: metav1.ObjectMeta{Name: randomString()}, + Spec: libsveltosv1beta1.RoleRequestSpec{ + ServiceAccountNamespace: saNamespace, + ServiceAccountName: saName, + ManagedClusterServiceAccountNamespace: managedClusterNamespace, + }, + } + Expect(testEnv.Create(context.TODO(), roleRequest)).To(Succeed()) + DeferCleanup(func() { + Expect(client.IgnoreNotFound(testEnv.Delete(context.TODO(), roleRequest))).To(Succeed()) + }) + + roleRequest.Status.ClusterInfo = []libsveltosv1beta1.ClusterInfo{ + { + Cluster: corev1.ObjectReference{ + Namespace: clusterSummary.Spec.ClusterNamespace, + Name: clusterName, + Kind: clusterv1.ClusterKind, + APIVersion: clusterv1.GroupVersion.String(), + }, + Status: status, + // hash is a required field + Hash: []byte(randomString()), + }, + } + Expect(testEnv.Status().Update(context.TODO(), roleRequest)).To(Succeed()) + + Eventually(func() bool { + current := &libsveltosv1beta1.RoleRequest{} + err := testEnv.Get(context.TODO(), types.NamespacedName{Name: roleRequest.Name}, current) + return err == nil && len(current.Status.ClusterInfo) == 1 + }, timeout, pollingInterval).Should(BeTrue()) + + return roleRequest + } + + It("returns an empty namespace when no RoleRequest is deployed for the admin in the cluster", func() { + namespace, err := controllers.GetManagedClusterServiceAccountNamespace(context.TODO(), clusterSummary, + adminNamespace, adminName) + Expect(err).To(BeNil()) + Expect(namespace).To(BeEmpty()) + }) + + It("returns the namespace asked by the RoleRequest deployed for the admin in the cluster", func() { + managedClusterNamespace := randomString() + createRoleRequest(adminNamespace, adminName, managedClusterNamespace, clusterSummary.Spec.ClusterName, + libsveltosv1beta1.SveltosStatusProvisioned) + + Eventually(func() string { + namespace, err := controllers.GetManagedClusterServiceAccountNamespace(context.TODO(), clusterSummary, + adminNamespace, adminName) + Expect(err).To(BeNil()) + return namespace + }, timeout, pollingInterval).Should(Equal(managedClusterNamespace)) + }) + + It("returns an empty namespace when the RoleRequest does not ask for one", func() { + createRoleRequest(adminNamespace, adminName, "", clusterSummary.Spec.ClusterName, + libsveltosv1beta1.SveltosStatusProvisioned) + + namespace, err := controllers.GetManagedClusterServiceAccountNamespace(context.TODO(), clusterSummary, + adminNamespace, adminName) + Expect(err).To(BeNil()) + Expect(namespace).To(BeEmpty()) + }) + + It("ignores RoleRequests failing in the cluster, for another cluster or for another admin", func() { + // Not deployed in the cluster: e.g. its namespace conflicts with the one already in use + createRoleRequest(adminNamespace, adminName, randomString(), clusterSummary.Spec.ClusterName, + libsveltosv1beta1.SveltosStatusFailed) + // Deployed in another cluster + createRoleRequest(adminNamespace, adminName, randomString(), randomString(), + libsveltosv1beta1.SveltosStatusProvisioned) + // Deployed in the cluster for another admin + createRoleRequest(adminNamespace, randomString(), randomString(), clusterSummary.Spec.ClusterName, + libsveltosv1beta1.SveltosStatusProvisioned) + + // RoleRequests are read from a cache: wait until all of them are seen before verifying none matters + Consistently(func() string { + namespace, err := controllers.GetManagedClusterServiceAccountNamespace(context.TODO(), clusterSummary, + adminNamespace, adminName) + Expect(err).To(BeNil()) + return namespace + }, 5*time.Second, time.Second).Should(BeEmpty()) + }) + }) + It("validateClusterSummaryAdmin accepts no tenant labels or both labels set", func() { Expect(controllers.ValidateClusterSummaryAdmin(clusterSummary)).To(Succeed()) diff --git a/go.mod b/go.mod index ca836fe3..590d7ce1 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/onsi/gomega v1.44.0 github.com/opencontainers/image-spec v1.1.1 github.com/pkg/errors v0.9.1 - github.com/projectsveltos/libsveltos v1.18.1-0.20261202143947-d5020b2bd612 + github.com/projectsveltos/libsveltos v1.18.1-0.20261205090214-7fbab21f1683 github.com/prometheus/client_golang v1.25.0 github.com/sigstore/cosign/v3 v3.1.6 github.com/sigstore/sigstore v1.11.4 diff --git a/go.sum b/go.sum index 5a686217..e54c8ff4 100644 --- a/go.sum +++ b/go.sum @@ -645,6 +645,8 @@ github.com/poy/onpar v1.1.2 h1:QaNrNiZx0+Nar5dLgTVp5mXkyoVFIbepjyEoGSnhbAY= github.com/poy/onpar v1.1.2/go.mod h1:6X8FLNoxyr9kkmnlqpK6LSoiOtrO6MICtWwEuWkLjzg= github.com/projectsveltos/libsveltos v1.18.1-0.20261202143947-d5020b2bd612 h1:CgY/N51ojIZVjT1B3u6mhJpc6OAY7GRsILlfSlExnGg= github.com/projectsveltos/libsveltos v1.18.1-0.20261202143947-d5020b2bd612/go.mod h1:m4ts0OeHjqhLp/zu/ryZdprj/bPuKqJHqsS32tzEGaI= +github.com/projectsveltos/libsveltos v1.18.1-0.20261205090214-7fbab21f1683 h1:DDPnwVACkx5m3Q0fx0orhRE49KWZKow5ZEyrXivCeRU= +github.com/projectsveltos/libsveltos v1.18.1-0.20261205090214-7fbab21f1683/go.mod h1:m4ts0OeHjqhLp/zu/ryZdprj/bPuKqJHqsS32tzEGaI= github.com/projectsveltos/lua-utils/glua-json v0.0.0-20251212200258-2b3cdcb7c0f5 h1:khnc+994UszxZYu69J+R5FKiLA/Nk1JQj0EYAkwTWz0= github.com/projectsveltos/lua-utils/glua-json v0.0.0-20251212200258-2b3cdcb7c0f5/go.mod h1:yVL8KQFa9tmcxgwl9nwIMtKgtmIVC1zaFRSCfOwYvPY= github.com/projectsveltos/lua-utils/glua-runes v0.0.0-20251212200258-2b3cdcb7c0f5 h1:YbsebwRwTRhV8QacvEAdFqxcxHdeu7JTVtsBovbkgos= diff --git a/manifest/manifest.yaml b/manifest/manifest.yaml index 7699a808..d26c2245 100644 --- a/manifest/manifest.yaml +++ b/manifest/manifest.yaml @@ -12610,6 +12610,7 @@ rules: - configurationgroups/status - debuggingconfigurations - eventtriggers + - rolerequests - sveltosclusters - sveltosclusters/status verbs: diff --git a/test/pullmode-sveltosapplier.yaml b/test/pullmode-sveltosapplier.yaml index 930a449e..c9886a2b 100644 --- a/test/pullmode-sveltosapplier.yaml +++ b/test/pullmode-sveltosapplier.yaml @@ -100,7 +100,7 @@ spec: valueFrom: fieldRef: fieldPath: metadata.namespace - image: docker.io/projectsveltos/sveltos-applier@sha256:69ab495edcdadfde4e185b8bc1be29928b1afc782c287474d831a0c30f71a5e2 + image: docker.io/projectsveltos/sveltos-applier@sha256:d764f4e6bcdbee4cbce68d5877f1397ae0b0aa10eca830091343990564e65dfb livenessProbe: failureThreshold: 3 httpGet: