plugin-barman-cloud/internal/cnpgi/operator/rbac/ensure_test.go
Armando Ruocco d05559a07f fix(rbac): reconcile Role when ObjectStore spec changes
When an ObjectStore's credentials change (e.g., secret rename), the
RBAC Role granting the Cluster's ServiceAccount access to those secrets
was not updated because nothing triggered a Cluster reconciliation.

Implement the ObjectStore controller's Reconcile to detect referencing
Clusters and update their Roles directly. Extract ensureRole into a
shared rbac.EnsureRole function used by both the Pre hook and the
ObjectStore controller.

The shared EnsureRole accepts optional beforeCreate callbacks so the
Pre hook can set owner references on Role creation, while the
ObjectStore controller path skips ownership (it only updates existing
Roles).

Handle deleted ObjectStores gracefully by skipping NotFound errors
during Role reconciliation, and filter status-only changes with
GenerationChangedPredicate.

Add RBAC permission for the plugin to list/watch Clusters so the
ObjectStore controller can find affected Clusters. Regenerate
config/rbac/role.yaml.

Signed-off-by: Armando Ruocco <armando.ruocco@enterprisedb.com>
2026-03-26 16:14:24 +01:00

207 lines
6.0 KiB
Go

/*
Copyright © contributors to CloudNativePG, established as
CloudNativePG a Series of LF Projects, LLC.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
package rbac_test
import (
"context"
"fmt"
cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
barmanapi "github.com/cloudnative-pg/barman-cloud/pkg/api"
machineryapi "github.com/cloudnative-pg/machinery/pkg/api"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
barmancloudv1 "github.com/cloudnative-pg/plugin-barman-cloud/api/v1"
"github.com/cloudnative-pg/plugin-barman-cloud/internal/cnpgi/operator/rbac"
)
func newScheme() *runtime.Scheme {
s := runtime.NewScheme()
_ = rbacv1.AddToScheme(s)
_ = cnpgv1.AddToScheme(s)
_ = barmancloudv1.AddToScheme(s)
return s
}
func newCluster(name, namespace string) *cnpgv1.Cluster {
return &cnpgv1.Cluster{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
}
}
func newObjectStore(name, namespace, secretName string) barmancloudv1.ObjectStore {
return barmancloudv1.ObjectStore{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
Spec: barmancloudv1.ObjectStoreSpec{
Configuration: barmanapi.BarmanObjectStoreConfiguration{
DestinationPath: "s3://bucket/path",
BarmanCredentials: barmanapi.BarmanCredentials{
AWS: &barmanapi.S3Credentials{
AccessKeyIDReference: &machineryapi.SecretKeySelector{
LocalObjectReference: machineryapi.LocalObjectReference{
Name: secretName,
},
Key: "ACCESS_KEY_ID",
},
},
},
},
},
}
}
var _ = Describe("EnsureRole", func() {
var (
ctx context.Context
cluster *cnpgv1.Cluster
objects []barmancloudv1.ObjectStore
fakeClient client.Client
)
BeforeEach(func() {
ctx = context.Background()
cluster = newCluster("test-cluster", "default")
objects = []barmancloudv1.ObjectStore{
newObjectStore("my-store", "default", "aws-creds"),
}
})
Context("when the Role does not exist", func() {
BeforeEach(func() {
fakeClient = fake.NewClientBuilder().WithScheme(newScheme()).Build()
})
It("should create the Role", func() {
err := rbac.EnsureRole(ctx, fakeClient, cluster, objects)
Expect(err).NotTo(HaveOccurred())
var role rbacv1.Role
err = fakeClient.Get(ctx, client.ObjectKey{
Namespace: "default",
Name: "test-cluster-barman-cloud",
}, &role)
Expect(err).NotTo(HaveOccurred())
Expect(role.Rules).To(HaveLen(3))
})
It("should apply beforeCreate callbacks", func() {
called := false
err := rbac.EnsureRole(ctx, fakeClient, cluster, objects, func(role *rbacv1.Role) error {
called = true
role.Labels = map[string]string{"owner": "test-cluster"}
return nil
})
Expect(err).NotTo(HaveOccurred())
Expect(called).To(BeTrue())
var role rbacv1.Role
err = fakeClient.Get(ctx, client.ObjectKey{
Namespace: "default",
Name: "test-cluster-barman-cloud",
}, &role)
Expect(err).NotTo(HaveOccurred())
Expect(role.Labels).To(HaveKeyWithValue("owner", "test-cluster"))
})
It("should return error if beforeCreate callback fails", func() {
err := rbac.EnsureRole(ctx, fakeClient, cluster, objects, func(_ *rbacv1.Role) error {
return fmt.Errorf("callback error")
})
Expect(err).To(MatchError("callback error"))
})
})
Context("when the Role exists with matching rules", func() {
BeforeEach(func() {
fakeClient = fake.NewClientBuilder().WithScheme(newScheme()).Build()
Expect(rbac.EnsureRole(ctx, fakeClient, cluster, objects)).To(Succeed())
})
It("should not patch the Role", func() {
var before rbacv1.Role
Expect(fakeClient.Get(ctx, client.ObjectKey{
Namespace: "default",
Name: "test-cluster-barman-cloud",
}, &before)).To(Succeed())
err := rbac.EnsureRole(ctx, fakeClient, cluster, objects)
Expect(err).NotTo(HaveOccurred())
var after rbacv1.Role
Expect(fakeClient.Get(ctx, client.ObjectKey{
Namespace: "default",
Name: "test-cluster-barman-cloud",
}, &after)).To(Succeed())
Expect(after.ResourceVersion).To(Equal(before.ResourceVersion))
})
})
Context("when the Role exists with different rules", func() {
BeforeEach(func() {
fakeClient = fake.NewClientBuilder().WithScheme(newScheme()).Build()
// Create with old secret
oldObjects := []barmancloudv1.ObjectStore{
newObjectStore("my-store", "default", "old-secret"),
}
Expect(rbac.EnsureRole(ctx, fakeClient, cluster, oldObjects)).To(Succeed())
})
It("should patch the Role with new rules", func() {
// Now call with new secret name
err := rbac.EnsureRole(ctx, fakeClient, cluster, objects)
Expect(err).NotTo(HaveOccurred())
var role rbacv1.Role
Expect(fakeClient.Get(ctx, client.ObjectKey{
Namespace: "default",
Name: "test-cluster-barman-cloud",
}, &role)).To(Succeed())
// The secrets rule should reference the new secret
secretsRule := role.Rules[2]
Expect(secretsRule.ResourceNames).To(ContainElement("aws-creds"))
Expect(secretsRule.ResourceNames).NotTo(ContainElement("old-secret"))
})
It("should not call beforeCreate callbacks on update", func() {
called := false
err := rbac.EnsureRole(ctx, fakeClient, cluster, objects, func(_ *rbacv1.Role) error {
called = true
return nil
})
Expect(err).NotTo(HaveOccurred())
Expect(called).To(BeFalse())
})
})
})