Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions controllers/clustersummary_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,29 @@ func (r *ClusterSummaryReconciler) Reconcile(ctx context.Context, req ctrl.Reque
return r.reconcileNormal(ctx, clusterSummaryScope, logger)
}

// blockOnInvalidTenantIdentity returns true, after setting the failure message, when the tenant
// identity carried by the ClusterSummary labels is invalid. It is checked both when the
// ClusterSummary is deployed and when it is deleted: with an invalid identity, deploy and cleanup would
// run with the addon-controller own permissions. Something might already be deployed: do not
// guess. Nothing is done and the finalizer is kept, so the user can decide how to fix the labels
// on the ClusterProfile (remove them or set the correct ones).
// The error is non retriable: there is no requeue. A change of the tenant labels on the
// ClusterSummary, which the profile reconciler propagates, reconciles the ClusterSummary again
// (see ClusterSummaryPredicate).
func (r *ClusterSummaryReconciler) blockOnInvalidTenantIdentity(clusterSummary *configv1beta1.ClusterSummary,
logger logr.Logger) bool {

err := validateClusterSummaryAdmin(clusterSummary)
if err == nil {
return false
}

msg := err.Error()
logger.Error(err, msg)
clusterSummary.Status.FailureMessage = &msg
return true
}

// checkClusterHealth checks if the cluster is ready and the agent is healthy.
// Returns (proceed, result, error)
func (r *ClusterSummaryReconciler) checkClusterHealth(ctx context.Context,
Expand Down Expand Up @@ -335,6 +358,10 @@ func (r *ClusterSummaryReconciler) reconcileDelete(

logger.V(logs.LogDebug).Info("Reconciling ClusterSummary delete")

if r.blockOnInvalidTenantIdentity(clusterSummaryScope.ClusterSummary, logger) {
return reconcile.Result{}, nil
}

r.updateDeletedInstancs(clusterSummaryScope)

// HealthCheck and ClusterHealthCheck live in the management cluster: they can be removed
Expand Down Expand Up @@ -516,6 +543,10 @@ func (r *ClusterSummaryReconciler) reconcileNormal(ctx context.Context,

logger.V(logs.LogDebug).Info("Reconciling ClusterSummary")

if r.blockOnInvalidTenantIdentity(clusterSummaryScope.ClusterSummary, logger) {
return reconcile.Result{}, nil
}

if !controllerutil.ContainsFinalizer(clusterSummaryScope.ClusterSummary, configv1beta1.ClusterSummaryFinalizer) {
if err := r.addFinalizer(ctx, clusterSummaryScope); err != nil {
logger.V(logs.LogInfo).Error(err, "failed to add finalizer")
Expand Down
63 changes: 63 additions & 0 deletions controllers/clustersummary_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -935,6 +935,69 @@ var _ = Describe("ClustersummaryController", func() {
).Should(BeTrue())
})

It("Does nothing when the tenant labels are set to an empty value", func() {
clusterSummary.Labels = map[string]string{
libsveltosv1beta1.ServiceAccountNameLabel: "",
libsveltosv1beta1.ServiceAccountNamespaceLabel: randomString(),
}
initObjects := []client.Object{
clusterProfile,
clusterSummary,
cluster,
}

c := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(initObjects...).WithObjects(initObjects...).Build()

deployer := fakedeployer.GetClient(context.TODO(), textlogger.NewLogger(textlogger.NewConfig()), c)
reconciler := getClusterSummaryReconciler(c, deployer)

clusterSummaryName := client.ObjectKey{Name: clusterSummary.Name, Namespace: clusterSummary.Namespace}
result, err := reconciler.Reconcile(context.TODO(), ctrl.Request{NamespacedName: clusterSummaryName})
Expect(err).ToNot(HaveOccurred())
// Non retriable: no requeue. A change of the labels on the ClusterSummary reconciles it again
Expect(result.RequeueAfter).To(BeZero())

currentClusterSummary := &configv1beta1.ClusterSummary{}
Expect(c.Get(context.TODO(), clusterSummaryName, currentClusterSummary)).To(Succeed())
Expect(currentClusterSummary.Status.FailureMessage).ToNot(BeNil())
Expect(*currentClusterSummary.Status.FailureMessage).To(ContainSubstring(libsveltosv1beta1.ServiceAccountNameLabel))
// Nothing was done: not even the finalizer was added
Expect(controllerutil.ContainsFinalizer(currentClusterSummary, configv1beta1.ClusterSummaryFinalizer)).To(BeFalse())
})

It("Does not delete a ClusterSummary whose tenant labels are set to an empty value", func() {
// Something might have been deployed before the labels were changed: the finalizer
// must stay so the user can decide how to fix the labels
now := metav1.Now()
clusterSummary.DeletionTimestamp = &now
clusterSummary.Finalizers = []string{configv1beta1.ClusterSummaryFinalizer}
clusterSummary.Labels = map[string]string{
libsveltosv1beta1.ServiceAccountNameLabel: randomString(),
libsveltosv1beta1.ServiceAccountNamespaceLabel: "",
}
initObjects := []client.Object{
clusterProfile,
clusterSummary,
cluster,
}

c := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(initObjects...).WithObjects(initObjects...).Build()

deployer := fakedeployer.GetClient(context.TODO(), textlogger.NewLogger(textlogger.NewConfig()), c)
reconciler := getClusterSummaryReconciler(c, deployer)

clusterSummaryName := client.ObjectKey{Name: clusterSummary.Name, Namespace: clusterSummary.Namespace}
result, err := reconciler.Reconcile(context.TODO(), ctrl.Request{NamespacedName: clusterSummaryName})
Expect(err).ToNot(HaveOccurred())
Expect(result.RequeueAfter).To(BeZero())

currentClusterSummary := &configv1beta1.ClusterSummary{}
Expect(c.Get(context.TODO(), clusterSummaryName, currentClusterSummary)).To(Succeed())
Expect(controllerutil.ContainsFinalizer(currentClusterSummary, configv1beta1.ClusterSummaryFinalizer)).To(BeTrue())
Expect(currentClusterSummary.Status.FailureMessage).ToNot(BeNil())
Expect(*currentClusterSummary.Status.FailureMessage).To(ContainSubstring(libsveltosv1beta1.ServiceAccountNamespaceLabel))
})

It("shouldRedeploy returns true in DryRun mode", func() {
clusterSummary.Spec.ClusterProfileSpec.SyncMode = configv1beta1.SyncModeDryRun
clusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{
Expand Down
7 changes: 7 additions & 0 deletions controllers/clustersummary_predicates.go
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,13 @@ func (p ClusterSummaryPredicate) Update(e event.UpdateEvent) bool {
return true
}

// The tenant identity decides which permissions are used to deploy: a change must be acted on.
// This is also what unblocks a ClusterSummary stopped because of an invalid identity.
if tenantLabelsChanged(oldClusterSummary.GetLabels(), newClusterSummary.GetLabels()) {
log.V(logs.LogVerbose).Info("Tenant labels changed. Reconciling ClusterSummary.")
return true
}

// ProfileRedeployAnnotation is part of the hash: a change forces a redeployment, which
// can only happen if the ClusterSummary is reconciled
newAnnot := newClusterSummary.GetAnnotations()
Expand Down
36 changes: 36 additions & 0 deletions controllers/clustersummary_predicates_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,42 @@ var _ = Describe("Clustersummary Predicates: ClusterSummaryPredicate", func() {
Expect(result).To(BeFalse())
})

It("Update returns false when a label unrelated to the tenant identity changes", func() {
clusterSummaryPredicate := controllers.ClusterSummaryPredicate{Logger: logger}

oldClusterSummary := clusterSummary.DeepCopy()
clusterSummary.Labels = map[string]string{randomString(): randomString()}

e := event.UpdateEvent{ObjectNew: clusterSummary, ObjectOld: oldClusterSummary}
Expect(clusterSummaryPredicate.Update(e)).To(BeFalse())
})

It("Update returns true when a tenant label is added, set to empty, changed or removed", func() {
clusterSummaryPredicate := controllers.ClusterSummaryPredicate{Logger: logger}

for _, key := range []string{
libsveltosv1beta1.ServiceAccountNameLabel, libsveltosv1beta1.ServiceAccountNamespaceLabel,
} {
withValue := func(value string) *configv1beta1.ClusterSummary {
cs := clusterSummary.DeepCopy()
cs.Labels = map[string]string{key: value}
return cs
}
withoutLabel := clusterSummary.DeepCopy()
withoutLabel.Labels = nil

for _, change := range []struct{ oldClusterSummary, newClusterSummary *configv1beta1.ClusterSummary }{
{withoutLabel, withValue(randomString())},
{withValue(randomString()), withValue("")},
{withValue(randomString()), withValue(randomString())},
{withValue(randomString()), withoutLabel},
} {
e := event.UpdateEvent{ObjectNew: change.newClusterSummary, ObjectOld: change.oldClusterSummary}
Expect(clusterSummaryPredicate.Update(e)).To(BeTrue(), key)
}
}
})

It("Update returns true when FeatureSummaries change", func() {
clusterSummaryPredicate := controllers.ClusterSummaryPredicate{Logger: logger}

Expand Down
7 changes: 6 additions & 1 deletion controllers/delete_checks.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,12 @@ func validateDeleteChecks(ctx context.Context, clusterSummary *configv1beta1.Clu
}

logger.V(logs.LogDebug).Info("validate delete checks")
err = clusterops.ValidateHealthPolicies(ctx, getManagementClusterClient(), clusterSummary, getSveltosNamespace(),
referenceClient, err := getReferenceClient(getManagementClusterClient(), clusterSummary)
if err != nil {
return err
}

err = clusterops.ValidateHealthPolicies(ctx, referenceClient, clusterSummary, getSveltosNamespace(),
remoteRestConfig, clusterSummary.Spec.ClusterProfileSpec.PreDeleteChecks, featureID, true, logger)
if err != nil {
logger.V(logs.LogDebug).Error(err, "delete check failed")
Expand Down
4 changes: 4 additions & 0 deletions controllers/export_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,10 @@ var (
DeployContentOfSecret = deployContentOfSecret
DeployContent = deployContent
GetClusterSummaryAdmin = getClusterSummaryAdmin
GetReferenceClient = getReferenceClient
GetReferencedObject = getReferencedObject
GetValuesFrom = getValuesFrom
ValidateClusterSummaryAdmin = validateClusterSummaryAdmin
CollectContent = collectContent
CollectReferencedObjects = collectReferencedObjects
PartitionCRDsFirst = partitionCRDsFirst
Expand Down
39 changes: 32 additions & 7 deletions controllers/handlers_helm.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,12 @@ func postProcessDeployedHelmCharts(ctx context.Context, clusterSummary *configv1
if err != nil {
return err
}
return clusterops.ValidateHealthPolicies(ctx, c, clusterSummary, getSveltosNamespace(), remoteRestConfig,
referenceClient, err := getReferenceClient(c, clusterSummary)
if err != nil {
return err
}

return clusterops.ValidateHealthPolicies(ctx, referenceClient, clusterSummary, getSveltosNamespace(), remoteRestConfig,
clusterSummary.Spec.ClusterProfileSpec.ValidateHealths, libsveltosv1beta1.FeatureHelm, false, logger)
}

Expand Down Expand Up @@ -1107,6 +1112,11 @@ func getHelmChartHash(ctx context.Context, c client.Client, clusterSummary *conf
hash := sha256.Sum256(raw)
config += hex.EncodeToString((hash[:]))

c, err = getReferenceClient(c, clusterSummary)
if err != nil {
return "", err
}

clusterNamespace := clusterSummary.Spec.ClusterNamespace
clusterName := clusterSummary.Spec.ClusterName
clusterType := clusterSummary.Spec.ClusterType
Expand Down Expand Up @@ -1779,8 +1789,13 @@ func createRegistryClientOptions(ctx context.Context, clusterSummary *configv1be
return nil, err
}

referenceClient, err := getReferenceClient(getManagementClusterClient(), clusterSummary)
if err != nil {
return registryOptions, err
}

secret := &corev1.Secret{}
err = getManagementClusterClient().Get(ctx,
err = referenceClient.Get(ctx,
types.NamespacedName{
Namespace: credentialSecretNamespace,
Name: currentChart.RegistryCredentialsConfig.CredentialsSecretRef.Name,
Expand Down Expand Up @@ -2024,7 +2039,7 @@ func installRelease(ctx context.Context, clusterSummary *configv1beta1.ClusterSu
}

if needsCosignVerification(requestedChart) {
if verifyErr := verifyCosignSignature(ctx, requestedChart, chartName, clusterSummary.Namespace, logger); verifyErr != nil {
if verifyErr := verifyCosignSignature(ctx, requestedChart, chartName, clusterSummary, logger); verifyErr != nil {
return nil, verifyErr
}
}
Expand Down Expand Up @@ -2348,7 +2363,7 @@ func upgradeRelease(ctx context.Context, clusterSummary *configv1beta1.ClusterSu
}

if needsCosignVerification(requestedChart) {
if verifyErr := verifyCosignSignature(ctx, requestedChart, chartName, clusterSummary.Namespace, logger); verifyErr != nil {
if verifyErr := verifyCosignSignature(ctx, requestedChart, chartName, clusterSummary, logger); verifyErr != nil {
return nil, verifyErr
}
}
Expand Down Expand Up @@ -5269,6 +5284,11 @@ func getHelmChartPatchesHash(ctx context.Context, clusterSummary *configv1beta1.
func getCredentialsAndCAFiles(ctx context.Context, c client.Client, clusterSummary *configv1beta1.ClusterSummary,
requestedChart *configv1beta1.HelmChart) (credentialsPath, caPath string, err error) {

c, err = getReferenceClient(c, clusterSummary)
if err != nil {
return "", "", err
}

credentialsPath, err = createFileWithCredentials(ctx, c, clusterSummary, requestedChart)
if err != nil {
return "", "", err
Expand Down Expand Up @@ -5301,7 +5321,7 @@ func createFileWithCredentials(ctx context.Context, c client.Client, clusterSumm
}

secret := &corev1.Secret{}
err = getManagementClusterClient().Get(ctx,
err = c.Get(ctx,
types.NamespacedName{
Namespace: namespace,
Name: credSecretRef.Name,
Expand Down Expand Up @@ -5357,7 +5377,7 @@ func createFileWithCA(ctx context.Context, c client.Client, clusterSummary *conf
}

secret := &corev1.Secret{}
err = getManagementClusterClient().Get(ctx,
err = c.Get(ctx,
types.NamespacedName{
Namespace: namespace,
Name: requestedChart.RegistryCredentialsConfig.CASecretRef.Name,
Expand Down Expand Up @@ -5502,7 +5522,12 @@ func getHelmChartAndRepoName(ctx context.Context, clusterSummary *configv1beta1.
return "", "", "", fmt.Errorf("failed to instantiate name: %w", err)
}

source, err := getSource(ctx, getManagementClusterClient(), namespace, name, sourceRef.Kind)
referenceClient, err := getReferenceClient(getManagementClusterClient(), clusterSummary)
if err != nil {
return "", "", "", err
}

source, err := getSource(ctx, referenceClient, namespace, name, sourceRef.Kind)
if err != nil {
return "", "", "", err
}
Expand Down
37 changes: 35 additions & 2 deletions controllers/handlers_kustomize.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,12 @@ func processKustomizeDeployment(ctx context.Context, remoteRestConfig *rest.Conf
return err
}

return clusterops.ValidateHealthPolicies(ctx, c, clusterSummary, getSveltosNamespace(), remoteRestConfig,
referenceClient, err := getReferenceClient(c, clusterSummary)
if err != nil {
return err
}

return clusterops.ValidateHealthPolicies(ctx, referenceClient, clusterSummary, getSveltosNamespace(), remoteRestConfig,
clusterSummary.Spec.ClusterProfileSpec.ValidateHealths, libsveltosv1beta1.FeatureKustomize, false, logger)
}

Expand Down Expand Up @@ -431,6 +436,11 @@ func getHashFromKustomizationRef(ctx context.Context, c client.Client, clusterSu
return getHashFromRemoteKustomizeURL(ctx, kustomizationRef.RemoteURL, clusterSummary, logger)
}

c, err := getReferenceClient(c, clusterSummary)
if err != nil {
return nil, err
}

var result string
namespace, err := libsveltostemplate.GetReferenceResourceNamespace(ctx, c, clusterSummary.Spec.ClusterNamespace,
clusterSummary.Spec.ClusterName, kustomizationRef.Namespace, clusterSummary.Spec.ClusterType)
Expand Down Expand Up @@ -509,10 +519,15 @@ func getHashFromRemoteKustomizeURL(ctx context.Context, remoteURL *configv1beta1
return nil, nil
}

secretReader, err := getReferenceClient(getManagementClusterClient(), clusterSummary)
if err != nil {
return nil, err
}
opts := remoteFetchOptions{
secretRef: remoteURL.SecretRef,
insecureSkipTLSVerify: remoteURL.InsecureSkipTLSVerify,
plainHTTP: remoteURL.PlainHTTP,
secretReader: secretReader,
}
body, err := fetchContentForHash(ctx, instantiatedURL, opts,
clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName,
Expand Down Expand Up @@ -584,6 +599,11 @@ func getKustomizeSubstituteValues(ctx context.Context, c client.Client, clusterS
func getKustomizeSubstituteValuesFrom(ctx context.Context, c client.Client, clusterSummary *configv1beta1.ClusterSummary,
kustomizationRef *configv1beta1.KustomizationRef, logger logr.Logger) (dynamicValues, staticValues map[string]string, err error) {

c, err = getReferenceClient(c, clusterSummary)
if err != nil {
return nil, nil, err
}

return getKustomizeValuesFrom(ctx, c, clusterSummary, kustomizationRef.ValuesFrom, true, logger)
}

Expand Down Expand Up @@ -843,7 +863,14 @@ func prepareFileSystem(ctx context.Context, c client.Client,

if kustomizationRef.RemoteURL != nil {
return prepareFileSystemWithRemoteURL(ctx, kustomizationRef, clusterSummary, logger)
} else if kustomizationRef.Kind == string(libsveltosv1beta1.ConfigMapReferencedResourceKind) {
}

c, err := getReferenceClient(c, clusterSummary)
if err != nil {
return "", err
}

if kustomizationRef.Kind == string(libsveltosv1beta1.ConfigMapReferencedResourceKind) {
return prepareFileSystemWithConfigMap(ctx, c, kustomizationRef, clusterSummary, logger)
} else if kustomizationRef.Kind == string(libsveltosv1beta1.SecretReferencedResourceKind) {
return prepareFileSystemWithSecret(ctx, c, kustomizationRef, clusterSummary, logger)
Expand Down Expand Up @@ -894,10 +921,16 @@ func prepareFileSystemWithRemoteURL(ctx context.Context, kustomizationRef *confi
return "", fmt.Errorf("tmp dir error: %w", err)
}

secretReader, err := getReferenceClient(getManagementClusterClient(), clusterSummary)
if err != nil {
os.RemoveAll(tmpDir)
return "", err
}
opts := remoteFetchOptions{
secretRef: kustomizationRef.RemoteURL.SecretRef,
insecureSkipTLSVerify: kustomizationRef.RemoteURL.InsecureSkipTLSVerify,
plainHTTP: kustomizationRef.RemoteURL.PlainHTTP,
secretReader: secretReader,
}
err = fetchContentToDir(ctx, instantiatedURL, opts,
clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, clusterSummary.Spec.ClusterType,
Expand Down
Loading