From d4f1381bda6969de5476c5cc9a42f923805076ff Mon Sep 17 00:00:00 2001 From: Andrei Kvapil Date: Mon, 23 Nov 2026 16:27:00 +0100 Subject: [PATCH] feat(controller): seed account Secrets from CredentialTemplates The account list now comes from the chart, so something has to turn a rendered CredentialTemplate into an account Secret. The controller seeds a missing Secret, but only on a release marked for seeding: the mark says no client holds a password a seeded one would replace, which is true for a release the API created and, after the conversion, for a converted one. It seeds again when the template's format changes, adopts an unowned Secret the conversion wrote, leaves any other Secret at the name alone, and mirrors the Secret's record into the template's status. A second reconciler adds a valuesFrom entry per template that names a valuesPath, for an engine whose operator reads no Secret. A template reaches it one event at a time, and a conversion writes the Secrets and their entries before the converted chart renders the templates, so an entry whose Secret still exists is kept until its template is seen; it goes once the Secret is gone. The ApplicationDefinition reconciler keeps these entries rather than resetting valuesFrom to the platform values. HelmReleases are watched for the seed mark appearing or going, filtered so helm-controller's status writes do not wake the controller. Without that, a template the chart rendered before the release carried the mark stayed unseeded until the next resync, which on MariaDB turned into a ten-minute Helm timeout on the unready User. Account Secrets are read through the uncached reader and watched as metadata, because an account Secret may hold a plaintext that has no business in a cache. Assisted-by: LLM Signed-off-by: Andrei Kvapil --- cmd/cozystack-controller/main.go | 20 + .../applicationdefinition_helmreconciler.go | 10 +- ...plicationdefinition_helmreconciler_test.go | 44 ++ .../credentialtemplate_controller.go | 485 ++++++++++++++++++ .../credentialtemplate_controller_test.go | 324 ++++++++++++ 5 files changed, 882 insertions(+), 1 deletion(-) create mode 100644 internal/controller/credentialtemplate_controller.go create mode 100644 internal/controller/credentialtemplate_controller_test.go diff --git a/cmd/cozystack-controller/main.go b/cmd/cozystack-controller/main.go index 59ba3b515..df9c408a7 100644 --- a/cmd/cozystack-controller/main.go +++ b/cmd/cozystack-controller/main.go @@ -337,6 +337,26 @@ func main() { os.Exit(1) } + // Account Secrets are watched as metadata on the same unscoped metadata + // cache, for the reason the CA-extraction reconciler gives above, and read + // uncached: an account Secret may hold a plaintext. + if err = (&controller.CredentialTemplateReconciler{ + Client: mgr.GetClient(), + Reader: mgr.GetAPIReader(), + Scheme: mgr.GetScheme(), + Recorder: mgr.GetEventRecorderFor("credentialtemplate-controller"), + }).SetupWithManager(mgr, caSecretCluster.GetCache()); err != nil { + setupLog.Error(err, "unable to create controller", "controller", "CredentialTemplate") + os.Exit(1) + } + if err = (&controller.CredentialValuesReconciler{ + Client: mgr.GetClient(), + Reader: mgr.GetAPIReader(), + }).SetupWithManager(mgr); err != nil { + setupLog.Error(err, "unable to create controller", "controller", "CredentialValues") + os.Exit(1) + } + // +kubebuilder:scaffold:builder if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { diff --git a/internal/controller/applicationdefinition_helmreconciler.go b/internal/controller/applicationdefinition_helmreconciler.go index 91011500e..b370e18fc 100644 --- a/internal/controller/applicationdefinition_helmreconciler.go +++ b/internal/controller/applicationdefinition_helmreconciler.go @@ -8,6 +8,7 @@ import ( cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" "github.com/cozystack/cozystack/internal/shared/appdefowner" "github.com/cozystack/cozystack/pkg/config" + "github.com/cozystack/cozystack/pkg/credentials/account" helmv2 "github.com/fluxcd/helm-controller/api/v2" corev1 "k8s.io/api/core/v1" @@ -210,8 +211,15 @@ func (r *ApplicationDefinitionHelmReconciler) updateHelmReleaseChart(ctx context updated = true } - // Check and update valuesFrom configuration + // Check and update valuesFrom configuration. The entries that carry an + // account's stored value into the chart belong to the CredentialTemplate + // controller, so they are kept as they are. expected := expectedValuesFrom() + for _, ref := range hrCopy.Spec.ValuesFrom { + if account.IsAccountValuesFrom(ref) { + expected = append(expected, ref) + } + } if !valuesFromEqual(hrCopy.Spec.ValuesFrom, expected) { logger.V(4).Info("Updating HelmRelease valuesFrom", "name", hr.Name, "namespace", hr.Namespace) hrCopy.Spec.ValuesFrom = expected diff --git a/internal/controller/applicationdefinition_helmreconciler_test.go b/internal/controller/applicationdefinition_helmreconciler_test.go index 33fc871b4..fa293f073 100644 --- a/internal/controller/applicationdefinition_helmreconciler_test.go +++ b/internal/controller/applicationdefinition_helmreconciler_test.go @@ -10,6 +10,7 @@ import ( cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" "github.com/cozystack/cozystack/pkg/config" + "github.com/cozystack/cozystack/pkg/credentials/account" helmv2 "github.com/fluxcd/helm-controller/api/v2" "github.com/fluxcd/pkg/apis/kustomize" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -959,3 +960,46 @@ func TestAppDefHelm_UpdateFailureRequeues(t *testing.T) { t.Fatalf("expected %s synced past the failed %s, got %+v", written, failed, got.Spec.HealthCheckExprs) } } + +// TestAppDefHelm_KeepsAccountValuesFrom pins that the canonical valuesFrom +// leaves the entries the CredentialTemplate controller owns in place: they +// carry each account's stored value into the chart, and stripping them on +// every definition change would take the accounts out of the release. +func TestAppDefHelm_KeepsAccountValuesFrom(t *testing.T) { + scheme := newAppDefHelmScheme(t) + chartRef := &helmv2.CrossNamespaceSourceReference{Kind: "OCIRepository", Name: "clickhouse-app", Namespace: "cozy-public"} + appDef := &cozyv1alpha1.ApplicationDefinition{ + ObjectMeta: metav1.ObjectMeta{Name: "clickhouse"}, + Spec: cozyv1alpha1.ApplicationDefinitionSpec{ + Application: cozyv1alpha1.ApplicationDefinitionApplication{Kind: "ClickHouse"}, + Release: cozyv1alpha1.ApplicationDefinitionRelease{ChartRef: chartRef}, + }, + } + entry := account.ValuesFrom("clickhouse-logs.web.account", "_accounts", "web") + hr := &helmv2.HelmRelease{ + ObjectMeta: metav1.ObjectMeta{ + Name: "clickhouse-logs", + Namespace: "tenant-foo", + Labels: map[string]string{ + "apps.cozystack.io/application.kind": "ClickHouse", + "apps.cozystack.io/application.group": "apps.cozystack.io", + }, + }, + Spec: helmv2.HelmReleaseSpec{ + ChartRef: chartRef, + ValuesFrom: []helmv2.ValuesReference{{Kind: "ConfigMap", Name: "wrong"}, entry}, + }, + } + fakeClient := fake.NewClientBuilder().WithScheme(scheme).WithObjects(appDef, hr).Build() + r := &ApplicationDefinitionHelmReconciler{Client: fakeClient, Scheme: scheme} + if _, err := r.Reconcile(context.TODO(), reconcile.Request{NamespacedName: types.NamespacedName{Name: "clickhouse"}}); err != nil { + t.Fatalf("unexpected error: %v", err) + } + got := &helmv2.HelmRelease{} + if err := fakeClient.Get(context.TODO(), types.NamespacedName{Name: "clickhouse-logs", Namespace: "tenant-foo"}, got); err != nil { + t.Fatal(err) + } + if len(got.Spec.ValuesFrom) != 2 || got.Spec.ValuesFrom[0].Name != "cozystack-values" || got.Spec.ValuesFrom[1] != entry { + t.Fatalf("valuesFrom = %+v, want the platform values and the account entry", got.Spec.ValuesFrom) + } +} diff --git a/internal/controller/credentialtemplate_controller.go b/internal/controller/credentialtemplate_controller.go new file mode 100644 index 000000000..36e7e6fdc --- /dev/null +++ b/internal/controller/credentialtemplate_controller.go @@ -0,0 +1,485 @@ +// SPDX-License-Identifier: Apache-2.0 + +package controller + +import ( + "context" + "fmt" + "sort" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/equality" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/tools/record" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/builder" + "sigs.k8s.io/controller-runtime/pkg/cache" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + "sigs.k8s.io/controller-runtime/pkg/event" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/predicate" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + "sigs.k8s.io/controller-runtime/pkg/source" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" + "github.com/cozystack/cozystack/pkg/credentials/account" + "github.com/cozystack/cozystack/pkg/credentials/format" +) + +// +kubebuilder:rbac:groups=cozystack.io,resources=credentialtemplates,verbs=get;list;watch +// +kubebuilder:rbac:groups=cozystack.io,resources=credentialtemplates/status,verbs=get;update;patch +// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;create;update;patch +// +kubebuilder:rbac:groups=helm.toolkit.fluxcd.io,resources=helmreleases,verbs=get;list;watch;update;patch + +// CredentialControllerActor is who the record names for the operations the +// controller performs: seeding a Secret, or seeding it again after a format +// change. +const CredentialControllerActor = "system:serviceaccount:cozy-system:cozystack-controller" + +// Event reasons the controller records on a CredentialTemplate. +const ( + reasonCredentialReset = "CredentialReset" + reasonCredentialAdopted = "CredentialAdopted" +) + +// CredentialTemplateReconciler keeps each CredentialTemplate and its account +// Secret in step: it seeds a missing Secret on a release marked for seeding, +// seeds it again when the template's format changes, adopts an unowned Secret +// the conversion wrote, leaves any other Secret at the name alone, and mirrors +// the Secret's record into the template's status. See +// design-proposals/user-secrets-api in cozystack/community. +// +// Secrets are read through Reader, uncached: the manager's Secret cache is +// scoped to other reconcilers, and an account Secret may hold a plaintext +// that has no business in a cache. Their changes reach the controller through +// a metadata-only watch. +type CredentialTemplateReconciler struct { + client.Client + Reader client.Reader + Scheme *runtime.Scheme + Recorder record.EventRecorder + Now func() time.Time +} + +func (r *CredentialTemplateReconciler) now() metav1.Time { + if r.Now != nil { + return metav1.NewTime(r.Now()) + } + return metav1.Now() +} + +func (r *CredentialTemplateReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + logger := log.FromContext(ctx) + + tmpl := &cozyv1alpha1.CredentialTemplate{} + if err := r.Get(ctx, req.NamespacedName, tmpl); err != nil { + return ctrl.Result{}, client.IgnoreNotFound(err) + } + if !tmpl.DeletionTimestamp.IsZero() { + return ctrl.Result{}, nil + } + status := tmpl.Status.DeepCopy() + status.ObservedGeneration = tmpl.Generation + + if !format.Known(tmpl.Spec.Format.Name) { + meta.SetStatusCondition(&status.Conditions, metav1.Condition{ + Type: cozyv1alpha1.CredentialTemplateUnknownFormat, + Status: metav1.ConditionTrue, + Reason: "NotBuiltIn", + Message: fmt.Sprintf("format %q is not a built-in format", tmpl.Spec.Format.Name), + }) + return ctrl.Result{}, r.writeStatus(ctx, tmpl, status) + } + meta.RemoveStatusCondition(&status.Conditions, cozyv1alpha1.CredentialTemplateUnknownFormat) + + sec, err := r.secret(ctx, tmpl) + if err != nil { + return ctrl.Result{}, err + } + + switch { + case sec == nil: + seed, err := r.seedAllowed(ctx, tmpl) + if err != nil { + return ctrl.Result{}, err + } + if seed { + if sec, err = r.seed(ctx, tmpl); err != nil { + return ctrl.Result{}, err + } + } + case metav1.IsControlledBy(sec, tmpl): + if sec.Annotations[account.FormatAnnotation] != tmpl.Spec.Format.Name { + if sec, err = r.reseed(ctx, tmpl, sec); err != nil { + return ctrl.Result{}, err + } + } else if sec, err = r.alignLabels(ctx, tmpl, sec); err != nil { + return ctrl.Result{}, err + } + case adoptable(sec, tmpl): + if sec, err = r.adopt(ctx, tmpl, sec); err != nil { + return ctrl.Result{}, err + } + default: + logger.Info("leaving a Secret the controller did not create alone", "secret", sec.Name) + meta.SetStatusCondition(&status.Conditions, metav1.Condition{ + Type: cozyv1alpha1.CredentialTemplateSecretConflict, + Status: metav1.ConditionTrue, + Reason: "ForeignSecret", + Message: fmt.Sprintf("Secret %s exists and was not created for this template; remove it to let the account be seeded", sec.Name), + }) + mirror(status, nil) + return ctrl.Result{}, r.writeStatus(ctx, tmpl, status) + } + meta.RemoveStatusCondition(&status.Conditions, cozyv1alpha1.CredentialTemplateSecretConflict) + mirror(status, sec) + return ctrl.Result{}, r.writeStatus(ctx, tmpl, status) +} + +// secret reads the template's account Secret, nil when it does not exist. +func (r *CredentialTemplateReconciler) secret(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate) (*corev1.Secret, error) { + sec := &corev1.Secret{} + err := r.Reader.Get(ctx, types.NamespacedName{Namespace: tmpl.Namespace, Name: tmpl.Name + account.SecretSuffix}, sec) + switch { + case apierrors.IsNotFound(err): + return nil, nil + case err != nil: + return nil, err + } + return sec, nil +} + +// seedAllowed reports whether the template's release is marked for seeding. +// A release without the mark keeps passwords the platform never saw, which a +// seeded random password would replace under its clients. +func (r *CredentialTemplateReconciler) seedAllowed(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate) (bool, error) { + release := tmpl.Annotations[account.ReleaseNameAnnotation] + if release == "" { + return false, nil + } + hr := &helmv2.HelmRelease{} + if err := r.Get(ctx, types.NamespacedName{Namespace: tmpl.Namespace, Name: release}, hr); err != nil { + return false, client.IgnoreNotFound(err) + } + return hr.Annotations[account.SeedAnnotation] == "true", nil +} + +// newSecret builds the account Secret of a template holding the stored form of +// a random password that is discarded here. +func (r *CredentialTemplateReconciler) newSecret(tmpl *cozyv1alpha1.CredentialTemplate, rec account.Record) (*corev1.Secret, error) { + password, err := format.GeneratePassword() + if err != nil { + return nil, err + } + stored, err := format.Encode(tmpl.Spec.Format.Name, password) + if err != nil { + return nil, err + } + sec := &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: tmpl.Name + account.SecretSuffix, + Namespace: tmpl.Namespace, + Labels: account.Labels(tmpl.Spec.Secret.Labels), + Annotations: map[string]string{account.FormatAnnotation: tmpl.Spec.Format.Name}, + }, + Type: corev1.SecretTypeBasicAuth, + Data: map[string][]byte{ + account.UsernameKey: []byte(tmpl.Spec.Username), + account.PasswordKey: []byte(stored), + }, + } + account.WriteRecord(sec, rec.Apply(corev1alpha1.CredentialOperationCreate, r.now(), CredentialControllerActor)) + if err := controllerutil.SetControllerReference(tmpl, sec, r.Scheme); err != nil { + return nil, err + } + return sec, nil +} + +func (r *CredentialTemplateReconciler) seed(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate) (*corev1.Secret, error) { + sec, err := r.newSecret(tmpl, account.Record{}) + if err != nil { + return nil, err + } + if err := r.Create(ctx, sec); err != nil { + if apierrors.IsAlreadyExists(err) { + // A mint created it in between; the next reconcile mirrors it. + return r.secret(ctx, tmpl) + } + return nil, err + } + return sec, nil +} + +// reseed replaces a Secret whose value is stored in another format than the +// template now names: a stored value cannot be converted without the +// password, so the account starts over as NotIssued. +func (r *CredentialTemplateReconciler) reseed(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate, cur *corev1.Secret) (*corev1.Secret, error) { + sec, err := r.newSecret(tmpl, account.ReadRecord(cur)) + if err != nil { + return nil, err + } + sec.ResourceVersion = cur.ResourceVersion + if err := r.Update(ctx, sec); err != nil { + return nil, err + } + if r.Recorder != nil { + r.Recorder.Eventf(tmpl, corev1.EventTypeWarning, reasonCredentialReset, + "format changed from %q to %q; the account was given a new password nobody holds, mint one", cur.Annotations[account.FormatAnnotation], tmpl.Spec.Format.Name) + } + return sec, nil +} + +// alignLabels brings the Secret's labels in line with the template's, without +// touching its value or record. +func (r *CredentialTemplateReconciler) alignLabels(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate, sec *corev1.Secret) (*corev1.Secret, error) { + want := account.Labels(tmpl.Spec.Secret.Labels) + if equality.Semantic.DeepEqual(sec.Labels, want) { + return sec, nil + } + updated := sec.DeepCopy() + updated.Labels = want + if err := r.Update(ctx, updated); err != nil { + return nil, err + } + return updated, nil +} + +// adoptable reports whether an unowned Secret at the template's name is one +// the conversion wrote for this account: the account marker, no controller, +// and the same username. +func adoptable(sec *corev1.Secret, tmpl *cozyv1alpha1.CredentialTemplate) bool { + return account.IsAccountSecret(sec) && + metav1.GetControllerOf(sec) == nil && + string(sec.Data[account.UsernameKey]) == tmpl.Spec.Username +} + +// adopt takes over a Secret the conversion wrote, keeping its value and +// record. A Secret without a format annotation was written in the format its +// kind converted to, which the template names. +func (r *CredentialTemplateReconciler) adopt(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate, cur *corev1.Secret) (*corev1.Secret, error) { + sec := cur.DeepCopy() + if err := controllerutil.SetControllerReference(tmpl, sec, r.Scheme); err != nil { + return nil, err + } + if sec.Annotations == nil { + sec.Annotations = map[string]string{} + } + if sec.Annotations[account.FormatAnnotation] == "" { + sec.Annotations[account.FormatAnnotation] = tmpl.Spec.Format.Name + } + sec.Labels = account.Labels(tmpl.Spec.Secret.Labels) + if err := r.Update(ctx, sec); err != nil { + return nil, err + } + if r.Recorder != nil { + r.Recorder.Event(tmpl, corev1.EventTypeNormal, reasonCredentialAdopted, "adopted the account Secret the conversion wrote") + } + return sec, nil +} + +// mirror copies the record of the account Secret into the template's status; +// nil clears it. +func mirror(status *cozyv1alpha1.CredentialTemplateStatus, sec *corev1.Secret) { + if sec == nil { + status.SecretResourceVersion = "" + status.Password = cozyv1alpha1.CredentialTemplatePasswordState{Origin: string(corev1alpha1.CredentialOriginNotIssued)} + status.History = nil + return + } + rec := account.ReadRecord(sec) + status.SecretResourceVersion = sec.ResourceVersion + status.Password = cozyv1alpha1.CredentialTemplatePasswordState{Origin: string(rec.Origin), By: rec.By} + if rec.Origin == "" { + status.Password.Origin = string(corev1alpha1.CredentialOriginNotIssued) + } + if !rec.At.IsZero() { + at := rec.At + status.Password.At = &at + } + status.History = nil + for _, h := range rec.History { + status.History = append(status.History, cozyv1alpha1.CredentialTemplateHistoryEntry{Operation: string(h.Operation), At: h.At, By: h.By}) + } +} + +func (r *CredentialTemplateReconciler) writeStatus(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate, status *cozyv1alpha1.CredentialTemplateStatus) error { + if equality.Semantic.DeepEqual(&tmpl.Status, status) { + return nil + } + updated := tmpl.DeepCopy() + updated.Status = *status + return r.Status().Update(ctx, updated) +} + +// SetupWithManager registers the reconciler. accountSecrets is a metadata +// cache of Secrets, so a change to an account Secret (a mint, a revoke) +// reaches the template that owns it without any Secret data being cached. +func (r *CredentialTemplateReconciler) SetupWithManager(mgr ctrl.Manager, accountSecrets cache.Cache) error { + secretMeta := &metav1.PartialObjectMetadata{} + secretMeta.SetGroupVersionKind(corev1.SchemeGroupVersion.WithKind("Secret")) + isAccount := predicate.NewTypedPredicateFuncs(func(o *metav1.PartialObjectMetadata) bool { + return o.GetLabels()[account.AccountLabel] == "true" + }) + owner := handler.TypedEnqueueRequestForOwner[*metav1.PartialObjectMetadata]( + mgr.GetScheme(), mgr.GetRESTMapper(), &cozyv1alpha1.CredentialTemplate{}, handler.OnlyControllerOwner()) + return ctrl.NewControllerManagedBy(mgr). + Named("credentialtemplate"). + For(&cozyv1alpha1.CredentialTemplate{}, builder.WithPredicates(predicate.GenerationChangedPredicate{})). + WatchesRawSource(source.Kind(accountSecrets, secretMeta, owner, isAccount)). + Watches(&helmv2.HelmRelease{}, handler.EnqueueRequestsFromMapFunc(r.templatesOfRelease), builder.WithPredicates(seedMarkChanged)). + Complete(r) +} + +// seedMarkChanged passes only a HelmRelease whose seed mark appeared or +// went, so helm-controller's status writes do not wake the reconciler. A +// template rendered before its release was marked, as when the conversion +// marks a release whose chart has already switched, is seeded as soon as +// the mark lands rather than at the next resync. +var seedMarkChanged = predicate.Funcs{ + CreateFunc: func(e event.CreateEvent) bool { return e.Object.GetAnnotations()[account.SeedAnnotation] == "true" }, + DeleteFunc: func(event.DeleteEvent) bool { return false }, + GenericFunc: func(event.GenericEvent) bool { return false }, + UpdateFunc: func(e event.UpdateEvent) bool { + return e.ObjectOld.GetAnnotations()[account.SeedAnnotation] != e.ObjectNew.GetAnnotations()[account.SeedAnnotation] + }, +} + +// templatesOfRelease maps a HelmRelease to the templates it rendered. +func (r *CredentialTemplateReconciler) templatesOfRelease(ctx context.Context, o client.Object) []reconcile.Request { + list := &cozyv1alpha1.CredentialTemplateList{} + if err := r.List(ctx, list, client.InNamespace(o.GetNamespace())); err != nil { + log.FromContext(ctx).Error(err, "listing CredentialTemplates for a seed mark change", "release", o.GetName()) + return nil + } + var reqs []reconcile.Request + for _, t := range list.Items { + if t.Annotations[account.ReleaseNameAnnotation] == o.GetName() { + reqs = append(reqs, reconcile.Request{NamespacedName: types.NamespacedName{Namespace: t.Namespace, Name: t.Name}}) + } + } + return reqs +} + +// CredentialValuesReconciler keeps the valuesFrom entries of a HelmRelease in +// step with the templates of its release that name a valuesPath, for an +// engine whose operator reads no Secret. It is keyed by the HelmRelease but +// watches only templates, so helm-controller's status writes do not wake it. +type CredentialValuesReconciler struct { + client.Client + // Reader checks Secrets uncached, for the reason + // CredentialTemplateReconciler gives. + Reader client.Reader +} + +// valuesRecheck is how soon a release whose entries were kept for a template +// not seen yet is looked at again. +const valuesRecheck = 30 * time.Second + +// +kubebuilder:rbac:groups=helm.toolkit.fluxcd.io,resources=helmreleases,verbs=get;list;watch;update;patch + +func (r *CredentialValuesReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + hr := &helmv2.HelmRelease{} + if err := r.Get(ctx, req.NamespacedName, hr); err != nil { + return ctrl.Result{}, client.IgnoreNotFound(err) + } + templates := &cozyv1alpha1.CredentialTemplateList{} + if err := r.List(ctx, templates, client.InNamespace(hr.Namespace)); err != nil { + return ctrl.Result{}, err + } + want := DesiredValuesFrom(hr, templates.Items) + kept, err := r.keepPending(ctx, hr, want) + if err != nil { + return ctrl.Result{}, err + } + want = append(want, kept...) + result := ctrl.Result{} + if len(kept) > 0 { + result.RequeueAfter = valuesRecheck + } + if equality.Semantic.DeepEqual(hr.Spec.ValuesFrom, want) { + return result, nil + } + updated := hr.DeepCopy() + updated.Spec.ValuesFrom = want + return result, r.Update(ctx, updated) +} + +// keepPending returns the account entries of the live release that no +// template accounts for yet but whose Secret exists: the conversion writes +// both before the converted chart renders the templates, and the templates +// of one release reach this controller one event at a time. Dropping such an +// entry would take the account out of the chart until its template appears. +// An entry goes once its Secret is gone, which the garbage collector does +// after the template is removed. +func (r *CredentialValuesReconciler) keepPending(ctx context.Context, hr *helmv2.HelmRelease, want []helmv2.ValuesReference) ([]helmv2.ValuesReference, error) { + present := map[string]bool{} + for _, ref := range want { + if account.IsAccountValuesFrom(ref) { + present[ref.Name] = true + } + } + var kept []helmv2.ValuesReference + for _, ref := range hr.Spec.ValuesFrom { + if !account.IsAccountValuesFrom(ref) || present[ref.Name] { + continue + } + sec := &metav1.PartialObjectMetadata{} + sec.SetGroupVersionKind(corev1.SchemeGroupVersion.WithKind("Secret")) + err := r.Reader.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: ref.Name}, sec) + switch { + case apierrors.IsNotFound(err): + continue + case err != nil: + return nil, err + } + kept = append(kept, ref) + } + return kept, nil +} + +// DesiredValuesFrom returns the valuesFrom of a HelmRelease with its account +// entries replaced by one per live template of the release that names a +// valuesPath, ordered by template name; every other entry stays where it is. +func DesiredValuesFrom(hr *helmv2.HelmRelease, templates []cozyv1alpha1.CredentialTemplate) []helmv2.ValuesReference { + var out []helmv2.ValuesReference + for _, ref := range hr.Spec.ValuesFrom { + if !account.IsAccountValuesFrom(ref) { + out = append(out, ref) + } + } + var mine []cozyv1alpha1.CredentialTemplate + for _, t := range templates { + if t.Annotations[account.ReleaseNameAnnotation] == hr.Name && t.Spec.ValuesPath != "" && t.DeletionTimestamp.IsZero() { + mine = append(mine, t) + } + } + sort.Slice(mine, func(i, j int) bool { return mine[i].Name < mine[j].Name }) + for _, t := range mine { + out = append(out, account.ValuesFrom(t.Name+account.SecretSuffix, t.Spec.ValuesPath, t.Spec.Username)) + } + return out +} + +// SetupWithManager registers the reconciler. +func (r *CredentialValuesReconciler) SetupWithManager(mgr ctrl.Manager) error { + toRelease := handler.EnqueueRequestsFromMapFunc(func(_ context.Context, o client.Object) []reconcile.Request { + release := o.GetAnnotations()[account.ReleaseNameAnnotation] + if release == "" { + return nil + } + return []reconcile.Request{{NamespacedName: types.NamespacedName{Namespace: o.GetNamespace(), Name: release}}} + }) + return ctrl.NewControllerManagedBy(mgr). + Named("credentialvalues"). + Watches(&cozyv1alpha1.CredentialTemplate{}, toRelease). + Complete(r) +} diff --git a/internal/controller/credentialtemplate_controller_test.go b/internal/controller/credentialtemplate_controller_test.go new file mode 100644 index 000000000..df5af9518 --- /dev/null +++ b/internal/controller/credentialtemplate_controller_test.go @@ -0,0 +1,324 @@ +// SPDX-License-Identifier: Apache-2.0 + +package controller + +import ( + "context" + "testing" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/tools/record" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/event" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" + "github.com/cozystack/cozystack/pkg/credentials/account" +) + +const ( + ctNamespace = "tenant-foo" + ctRelease = "postgres-orders" + ctName = ctRelease + ".web" +) + +type ctFixture struct { + c client.Client + r *CredentialTemplateReconciler + recorder *record.FakeRecorder +} + +func newCTFixture(t *testing.T, seed bool, objs ...client.Object) *ctFixture { + t.Helper() + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, helmv2.AddToScheme, cozyv1alpha1.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + hr := &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: ctRelease, Namespace: ctNamespace}} + if seed { + hr.Annotations = map[string]string{account.SeedAnnotation: "true"} + } + c := fake.NewClientBuilder().WithScheme(scheme). + WithObjects(append(objs, hr)...). + WithStatusSubresource(&cozyv1alpha1.CredentialTemplate{}). + Build() + rec := record.NewFakeRecorder(10) + return &ctFixture{ + c: c, + recorder: rec, + r: &CredentialTemplateReconciler{ + Client: c, Reader: c, Scheme: scheme, Recorder: rec, + Now: func() time.Time { return time.Date(2026, 11, 21, 9, 0, 0, 0, time.UTC) }, + }, + } +} + +func ctTemplate(formatName string) *cozyv1alpha1.CredentialTemplate { + return &cozyv1alpha1.CredentialTemplate{ + ObjectMeta: metav1.ObjectMeta{ + Name: ctName, Namespace: ctNamespace, UID: "tmpl-uid", + Annotations: map[string]string{account.ReleaseNameAnnotation: ctRelease}, + }, + Spec: cozyv1alpha1.CredentialTemplateSpec{ + Username: "web", + Format: cozyv1alpha1.CredentialTemplateFormat{Name: formatName}, + Secret: cozyv1alpha1.CredentialTemplateSecret{Labels: map[string]string{"cnpg.io/reload": "true"}}, + }, + } +} + +func (f *ctFixture) reconcile(t *testing.T) { + t.Helper() + if _, err := f.r.Reconcile(context.Background(), reconcile.Request{NamespacedName: types.NamespacedName{Namespace: ctNamespace, Name: ctName}}); err != nil { + t.Fatal(err) + } +} + +func (f *ctFixture) secret(t *testing.T) *corev1.Secret { + t.Helper() + sec := &corev1.Secret{} + err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: ctName + account.SecretSuffix}, sec) + if apierrors.IsNotFound(err) { + return nil + } + if err != nil { + t.Fatal(err) + } + return sec +} + +func (f *ctFixture) template(t *testing.T) *cozyv1alpha1.CredentialTemplate { + t.Helper() + tmpl := &cozyv1alpha1.CredentialTemplate{} + if err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: ctName}, tmpl); err != nil { + t.Fatal(err) + } + return tmpl +} + +func TestCredentialTemplateSeedsAMarkedRelease(t *testing.T) { + f := newCTFixture(t, true, ctTemplate("scram-sha-256")) + f.reconcile(t) + sec := f.secret(t) + if sec == nil { + t.Fatal("no Secret seeded") + } + if ref := metav1.GetControllerOf(sec); ref == nil || ref.Name != ctName { + t.Errorf("controller = %v, want the template", ref) + } + if string(sec.Data[account.UsernameKey]) != "web" || len(sec.Data[account.PasswordKey]) == 0 { + t.Errorf("data = %v", sec.Data) + } + if sec.Labels["cnpg.io/reload"] != "true" || sec.Labels[account.AccountLabel] != "true" || sec.Annotations[account.FormatAnnotation] != "scram-sha-256" { + t.Errorf("labels %v annotations %v", sec.Labels, sec.Annotations) + } + if rec := account.ReadRecord(sec); rec.Origin != corev1alpha1.CredentialOriginNotIssued || rec.By != CredentialControllerActor { + t.Errorf("record = %+v", rec) + } + st := f.template(t).Status + if st.SecretResourceVersion != sec.ResourceVersion || st.Password.Origin != "NotIssued" || len(st.History) != 1 { + t.Errorf("status = %+v, want the Secret's record mirrored", st) + } +} + +func TestCredentialTemplateLeavesAnUnmarkedReleaseToAMint(t *testing.T) { + f := newCTFixture(t, false, ctTemplate("scram-sha-256")) + f.reconcile(t) + if f.secret(t) != nil { + t.Fatal("a Secret was seeded on a release whose clients may hold the old password") + } + if st := f.template(t).Status; st.SecretResourceVersion != "" || st.Password.Origin != "NotIssued" { + t.Errorf("status = %+v", st) + } +} + +func TestCredentialTemplateReseedsWhenTheFormatChanges(t *testing.T) { + f := newCTFixture(t, true, ctTemplate("scram-sha-256")) + f.reconcile(t) + before := f.secret(t) + + tmpl := f.template(t) + tmpl.Spec.Format.Name = "sha256" + if err := f.c.Update(context.Background(), tmpl); err != nil { + t.Fatal(err) + } + f.reconcile(t) + after := f.secret(t) + if after.Annotations[account.FormatAnnotation] != "sha256" || string(after.Data[account.PasswordKey]) == string(before.Data[account.PasswordKey]) { + t.Errorf("Secret not seeded again in the new format: %v", after.Annotations) + } + if rec := account.ReadRecord(after); rec.Origin != corev1alpha1.CredentialOriginNotIssued || len(rec.History) != 2 { + t.Errorf("record = %+v, want a second Create on top of the first", rec) + } + select { + case ev := <-f.recorder.Events: + if ev == "" { + t.Error("empty event") + } + default: + t.Error("no event recorded for the reset") + } +} + +func TestCredentialTemplateAdoptsAMigratedSecret(t *testing.T) { + migrated := &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: ctName + account.SecretSuffix, Namespace: ctNamespace, + Labels: map[string]string{account.AccountLabel: "true"}, + }, + Data: map[string][]byte{account.UsernameKey: []byte("web"), account.PasswordKey: []byte("SCRAM-SHA-256$migrated")}, + } + account.WriteRecord(migrated, account.Record{}.Apply(corev1alpha1.CredentialOperationMigrate, metav1.Now(), "migration")) + f := newCTFixture(t, true, ctTemplate("scram-sha-256"), migrated) + f.reconcile(t) + sec := f.secret(t) + if ref := metav1.GetControllerOf(sec); ref == nil || ref.Name != ctName { + t.Fatalf("controller = %v, want the template", ref) + } + if string(sec.Data[account.PasswordKey]) != "SCRAM-SHA-256$migrated" { + t.Error("the migrated verifier was replaced") + } + if sec.Labels["cnpg.io/reload"] != "true" || sec.Annotations[account.FormatAnnotation] != "scram-sha-256" { + t.Errorf("labels %v annotations %v", sec.Labels, sec.Annotations) + } + if st := f.template(t).Status; st.Password.Origin != "Migrated" { + t.Errorf("origin = %q, want Migrated", st.Password.Origin) + } +} + +func TestCredentialTemplateLeavesAForeignSecretAlone(t *testing.T) { + foreign := &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: ctName + account.SecretSuffix, Namespace: ctNamespace}, + Data: map[string][]byte{"key": []byte("value")}, + } + f := newCTFixture(t, true, ctTemplate("scram-sha-256"), foreign) + f.reconcile(t) + sec := f.secret(t) + if metav1.GetControllerOf(sec) != nil || string(sec.Data["key"]) != "value" { + t.Error("the controller touched a Secret it did not create") + } + if !meta.IsStatusConditionTrue(f.template(t).Status.Conditions, cozyv1alpha1.CredentialTemplateSecretConflict) { + t.Error("no SecretConflict condition") + } +} + +func TestCredentialTemplateReportsAnUnknownFormat(t *testing.T) { + f := newCTFixture(t, true, ctTemplate("apr1")) + f.reconcile(t) + if f.secret(t) != nil { + t.Error("a Secret was seeded in a format the controller does not have") + } + if !meta.IsStatusConditionTrue(f.template(t).Status.Conditions, cozyv1alpha1.CredentialTemplateUnknownFormat) { + t.Error("no UnknownFormat condition") + } +} + +func TestCredentialTemplateMirrorsAMint(t *testing.T) { + f := newCTFixture(t, true, ctTemplate("scram-sha-256")) + f.reconcile(t) + sec := f.secret(t) + account.WriteRecord(sec, account.ReadRecord(sec).Apply(corev1alpha1.CredentialOperationMint, metav1.Now(), "jane")) + if err := f.c.Update(context.Background(), sec); err != nil { + t.Fatal(err) + } + f.reconcile(t) + st := f.template(t).Status + if st.Password.Origin != "Minted" || st.Password.By != "jane" || st.SecretResourceVersion != f.secret(t).ResourceVersion { + t.Errorf("status = %+v, want the mint mirrored", st) + } +} + +func TestDesiredValuesFrom(t *testing.T) { + hr := &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: "clickhouse-logs"}} + hr.Spec.ValuesFrom = []helmv2.ValuesReference{ + {Kind: "Secret", Name: "cozystack-values"}, + account.ValuesFrom("clickhouse-logs.gone.account", "_accounts", "gone"), + } + mk := func(name, user, path, release string) cozyv1alpha1.CredentialTemplate { + return cozyv1alpha1.CredentialTemplate{ + ObjectMeta: metav1.ObjectMeta{Name: name, Annotations: map[string]string{account.ReleaseNameAnnotation: release}}, + Spec: cozyv1alpha1.CredentialTemplateSpec{Username: user, ValuesPath: path}, + } + } + got := DesiredValuesFrom(hr, []cozyv1alpha1.CredentialTemplate{ + mk("clickhouse-logs.web", "web", "_accounts", "clickhouse-logs"), + mk("clickhouse-logs.api", "api", "_accounts", "clickhouse-logs"), + mk("clickhouse-logs.nopath", "nopath", "", "clickhouse-logs"), + mk("other.web", "web", "_accounts", "other"), + }) + if len(got) != 3 || got[0].Name != "cozystack-values" || got[1].Name != "clickhouse-logs.api.account" || got[2].Name != "clickhouse-logs.web.account" { + t.Errorf("valuesFrom = %+v, want the platform values, then api and web, and no entry for a removed account", got) + } +} + +func TestCredentialValuesKeepsAnEntryWhoseSecretExists(t *testing.T) { + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, helmv2.AddToScheme, cozyv1alpha1.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + pending := account.ValuesFrom("clickhouse-logs.api.account", "_accounts", "api") + gone := account.ValuesFrom("clickhouse-logs.gone.account", "_accounts", "gone") + hr := &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: "clickhouse-logs", Namespace: ctNamespace}} + hr.Spec.ValuesFrom = []helmv2.ValuesReference{{Kind: "Secret", Name: "cozystack-values"}, pending, gone} + tmpl := &cozyv1alpha1.CredentialTemplate{ + ObjectMeta: metav1.ObjectMeta{Name: "clickhouse-logs.web", Namespace: ctNamespace, Annotations: map[string]string{account.ReleaseNameAnnotation: "clickhouse-logs"}}, + Spec: cozyv1alpha1.CredentialTemplateSpec{Username: "web", ValuesPath: "_accounts"}, + } + // The conversion wrote api's Secret before the chart rendered its template. + sec := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "clickhouse-logs.api.account", Namespace: ctNamespace}} + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(hr, tmpl, sec).Build() + r := &CredentialValuesReconciler{Client: c, Reader: c} + res, err := r.Reconcile(context.Background(), reconcile.Request{NamespacedName: types.NamespacedName{Namespace: ctNamespace, Name: "clickhouse-logs"}}) + if err != nil { + t.Fatal(err) + } + if res.RequeueAfter == 0 { + t.Error("a kept entry must be looked at again") + } + got := &helmv2.HelmRelease{} + if err := c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: "clickhouse-logs"}, got); err != nil { + t.Fatal(err) + } + names := map[string]bool{} + for _, ref := range got.Spec.ValuesFrom { + names[ref.Name] = true + } + if !names["clickhouse-logs.web.account"] || !names["clickhouse-logs.api.account"] || names["clickhouse-logs.gone.account"] { + t.Errorf("valuesFrom = %+v, want web (template), api (Secret, template pending), and no gone", got.Spec.ValuesFrom) + } +} + +func TestSeedMarkChangedPassesOnlyAMarkChange(t *testing.T) { + marked := &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: "r", Annotations: map[string]string{account.SeedAnnotation: "true"}}} + plain := &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: "r"}} + if !seedMarkChanged.Update(event.UpdateEvent{ObjectOld: plain, ObjectNew: marked}) { + t.Error("a release that gained the mark must wake the templates") + } + if seedMarkChanged.Update(event.UpdateEvent{ObjectOld: marked, ObjectNew: marked.DeepCopy()}) { + t.Error("a status write must not wake the templates") + } +} + +func TestTemplatesOfReleaseMapsOnlyItsTemplates(t *testing.T) { + other := ctTemplate("scram-sha-256") + other.Name = "postgres-other.web" + other.Annotations = map[string]string{account.ReleaseNameAnnotation: "postgres-other"} + f := newCTFixture(t, true, ctTemplate("scram-sha-256"), other) + reqs := f.r.templatesOfRelease(context.Background(), &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: ctRelease, Namespace: ctNamespace}}) + if len(reqs) != 1 || reqs[0].Name != ctName { + t.Errorf("requests = %v, want only %s", reqs, ctName) + } +}