diff --git a/pkg/registry/apps/application/rest.go b/pkg/registry/apps/application/rest.go index 60816a43d..038ecff17 100644 --- a/pkg/registry/apps/application/rest.go +++ b/pkg/registry/apps/application/rest.go @@ -250,6 +250,7 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation helmRelease.Labels[ApplicationGroupLabel] = r.gvk.Group helmRelease.Labels[ApplicationNameLabel] = app.Name // Note: Annotations from config are not handled as r.releaseConfig.Annotations is undefined + markForSeeding(helmRelease) klog.V(6).Infof("Creating HelmRelease %s in namespace %s", helmRelease.Name, app.Namespace) @@ -611,6 +612,7 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje return nil, false, err } r.applyLiveMetadata(helmRelease, cur, app, previousFinalizers) + keepAccountValuesFrom(helmRelease, cur) // Suspension is not part of the Application, so the rebuilt object always // says suspend=false, and sending it as is resumes a release that an @@ -655,6 +657,7 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje } helmRelease = converted.DeepCopy() r.applyLiveMetadata(helmRelease, cur, app, previousFinalizers) + keepAccountValuesFrom(helmRelease, cur) helmRelease.SetResourceVersion(cur.GetResourceVersion()) helmRelease.Spec.Suspend = cur.Spec.Suspend } @@ -733,6 +736,10 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va options.Preconditions.ResourceVersion = &liveRV } + if err := r.refuseDeleteSuspended(ctx, name, helmRelease); err != nil { + return nil, false, err + } + // Run the genericapiserver-supplied admission chain (validating webhooks // and ValidatingAdmissionPolicies) on the resolved Application before // removing the underlying HelmRelease. Custom REST handlers must invoke diff --git a/pkg/registry/apps/application/rest_credentials.go b/pkg/registry/apps/application/rest_credentials.go new file mode 100644 index 000000000..f875356dd --- /dev/null +++ b/pkg/registry/apps/application/rest_credentials.go @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 + +package application + +import ( + "context" + "fmt" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "sigs.k8s.io/controller-runtime/pkg/client" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + "github.com/cozystack/cozystack/pkg/credentials/account" +) + +// markForSeeding lets the CredentialTemplate controller seed the account +// Secrets of a release the API creates: its accounts are new, so no client +// holds a password a seeded one would replace. A release created before the +// mark existed gets it from the conversion, once the conversion has written +// its Secrets. The mark is outside the apps.cozystack.io- prefix, so an update +// keeps it. +func markForSeeding(hr *helmv2.HelmRelease) { + if hr.Annotations == nil { + hr.Annotations = map[string]string{} + } + hr.Annotations[account.SeedAnnotation] = "true" +} + +// keepAccountValuesFrom carries over the valuesFrom entries the +// CredentialTemplate controller added to the live release: the rebuilt +// release lists only the platform values, and dropping the entries would +// take every account's stored value out of the chart until the controller +// put them back. +func keepAccountValuesFrom(hr, cur *helmv2.HelmRelease) { + for _, ref := range cur.Spec.ValuesFrom { + if account.IsAccountValuesFrom(ref) { + hr.Spec.ValuesFrom = append(hr.Spec.ValuesFrom, ref) + } + } +} + +// refuseDeleteSuspended refuses to delete an application whose release is +// suspended and carries accounts: Flux skips the uninstall of a suspended +// release, so the database would keep running with its last passwords after +// the account Secrets went with the release's templates. +func (r *REST) refuseDeleteSuspended(ctx context.Context, name string, hr *helmv2.HelmRelease) error { + if !hr.Spec.Suspend { + return nil + } + templates := &cozyv1alpha1.CredentialTemplateList{} + if err := r.c.List(ctx, templates, client.InNamespace(hr.Namespace)); err != nil { + return err + } + for _, t := range templates.Items { + if t.Annotations[account.ReleaseNameAnnotation] == hr.Name { + return apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf( + "release %s is suspended, and deleting it would leave the database running after its account Secrets are gone; resume the release first", hr.Name)) + } + } + return nil +} diff --git a/pkg/registry/apps/application/rest_credentials_test.go b/pkg/registry/apps/application/rest_credentials_test.go new file mode 100644 index 000000000..4cc8d42bf --- /dev/null +++ b/pkg/registry/apps/application/rest_credentials_test.go @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: Apache-2.0 + +package application + +import ( + "context" + "testing" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apiserver/pkg/endpoints/request" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" + "github.com/cozystack/cozystack/pkg/config" + "github.com/cozystack/cozystack/pkg/credentials/account" +) + +func newCredentialsTestREST(t *testing.T, objs ...client.Object) (*REST, client.Client) { + t.Helper() + scheme := runtime.NewScheme() + if err := helmv2.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + if err := cozyv1alpha1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + resourceCfg := &config.ResourceConfig{Resources: []config.Resource{{Application: config.ApplicationConfig{Kind: "Postgres"}}}} + if err := appsv1alpha1.RegisterDynamicTypes(scheme, resourceCfg); err != nil { + t.Fatal(err) + } + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objs...).Build() + return &REST{ + c: c, + gvr: schema.GroupVersionResource{Group: appsv1alpha1.GroupName, Version: "v1alpha1", Resource: "postgreses"}, + gvk: schema.GroupVersionKind{Group: appsv1alpha1.GroupName, Version: "v1alpha1", Kind: "Postgres"}, + kindName: "Postgres", + releaseConfig: config.ReleaseConfig{Prefix: "postgres-"}, + }, c +} + +func accountTemplate(release string) *cozyv1alpha1.CredentialTemplate { + return &cozyv1alpha1.CredentialTemplate{ObjectMeta: metav1.ObjectMeta{ + Name: release + ".web", Namespace: "tenant-foo", + Annotations: map[string]string{account.ReleaseNameAnnotation: release}, + }} +} + +// TestUpdate_KeepsAccountValuesFromAndTheSeedMark pins that an Application +// write leaves the CredentialTemplate controller's state on the release: the +// valuesFrom entries that carry each account's stored value into the chart, +// and the mark that lets the controller seed. The rebuilt release lists only +// the platform values, so dropping the entries would take the accounts out of +// the chart until the controller put them back. +func TestUpdate_KeepsAccountValuesFromAndTheSeedMark(t *testing.T) { + hr := suspendTestHelmRelease(false) + hr.Annotations = map[string]string{account.SeedAnnotation: "true"} + entry := account.ValuesFrom("postgres-pg.web.account", "_accounts", "web") + hr.Spec.ValuesFrom = []helmv2.ValuesReference{{Kind: "Secret", Name: "cozystack-values"}, entry} + r, c := newCredentialsTestREST(t, hr) + + ctx := request.WithNamespace(context.Background(), "tenant-foo") + if _, _, err := r.Update(ctx, "pg", newDefaultUpdatedObjectInfo(suspendTestApplication()), nil, nil, false, &metav1.UpdateOptions{}); err != nil { + t.Fatal(err) + } + got := &helmv2.HelmRelease{} + if err := c.Get(ctx, client.ObjectKey{Namespace: "tenant-foo", Name: "postgres-pg"}, got); err != nil { + t.Fatal(err) + } + if len(got.Spec.ValuesFrom) != 2 || got.Spec.ValuesFrom[1] != entry { + t.Errorf("valuesFrom = %+v, want the platform values and the account entry", got.Spec.ValuesFrom) + } + if got.Annotations[account.SeedAnnotation] != "true" { + t.Error("the seed mark was dropped") + } +} + +func TestMarkForSeeding(t *testing.T) { + hr := &helmv2.HelmRelease{} + markForSeeding(hr) + if hr.Annotations[account.SeedAnnotation] != "true" { + t.Errorf("annotations = %v", hr.Annotations) + } +} + +// TestDelete_RefusesASuspendedReleaseWithAccounts: Flux skips the uninstall of +// a suspended release, so deleting it would leave the database running after +// its account Secrets went with the templates. +func TestDelete_RefusesASuspendedReleaseWithAccounts(t *testing.T) { + r, _ := newCredentialsTestREST(t, suspendTestHelmRelease(true), accountTemplate("postgres-pg")) + ctx := request.WithNamespace(context.Background(), "tenant-foo") + if _, _, err := r.Delete(ctx, "pg", nil, &metav1.DeleteOptions{}); !apierrors.IsConflict(err) { + t.Fatalf("err = %v, want a conflict", err) + } +} + +func TestDelete_AllowsASuspendedReleaseWithoutAccounts(t *testing.T) { + r, _ := newCredentialsTestREST(t, suspendTestHelmRelease(true), accountTemplate("postgres-other")) + ctx := request.WithNamespace(context.Background(), "tenant-foo") + if _, _, err := r.Delete(ctx, "pg", nil, &metav1.DeleteOptions{}); apierrors.IsConflict(err) { + t.Fatalf("err = %v, a release without accounts must delete", err) + } +}