diff --git a/cmd/credentials-migrate/hide.go b/cmd/credentials-migrate/hide.go new file mode 100644 index 000000000..0d7e65bfd --- /dev/null +++ b/cmd/credentials-migrate/hide.go @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "fmt" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + "github.com/cozystack/cozystack/internal/lineagecontrollerwebhook" + "github.com/cozystack/cozystack/internal/shared/appdefowner" + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" +) + +// waitDefinitionHides waits until the ApplicationDefinition of the kind, as +// it stands in the API, no longer selects sec as tenant-visible. An operator +// that rewrites the Secret replaces its labels, and the lineage webhook then +// stamps it again from that definition, so a label written while the old +// definition is in place is undone by the next such write. The definition +// comes from the kind's rd chart, which upgrades only after the operator it +// depends on is Ready: a new operator rewriting the Secret on its first pass +// lands before it. Labelling only once the new definition hides the Secret +// leaves every later rewrite stamped not tenant-visible as well. +func (m *migrator) waitDefinitionHides(ctx context.Context, hr *helmv2.HelmRelease, sec *corev1.Secret) error { + appName := hr.Labels[appsv1alpha1.ApplicationNameLabel] + deadline := m.now().Add(m.o.timeout) + for { + defs := &cozyv1alpha1.ApplicationDefinitionList{} + if err := m.c.List(ctx, defs); err != nil { + return fmt.Errorf("list ApplicationDefinitions: %w", err) + } + owner := appdefowner.Owners(defs.Items)[m.o.kind] + var def *cozyv1alpha1.ApplicationDefinition + for i := range defs.Items { + if defs.Items[i].Name == owner { + def = &defs.Items[i] + } + } + if !lineagecontrollerwebhook.SecretTenantVisible(ctx, def, appName, hr.Namespace, sec.Name, sec.Labels) { + return nil + } + if m.now().After(deadline) { + return fmt.Errorf("ApplicationDefinition %s still selects %s as tenant-visible after %s; it would be stamped visible again at the operator's next write, so it is not labelled yet", owner, sec.Name, m.o.timeout) + } + time.Sleep(10 * time.Second) + } +} diff --git a/cmd/credentials-migrate/hide_test.go b/cmd/credentials-migrate/hide_test.go new file mode 100644 index 000000000..e9aea843b --- /dev/null +++ b/cmd/credentials-migrate/hide_test.go @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "strings" + "testing" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" +) + +// definition is the Postgres ApplicationDefinition with the admin Secret +// either included by name, as before a conversion, or excluded, as after. +func definition(adminVisible bool) *cozyv1alpha1.ApplicationDefinition { + sel := []*cozyv1alpha1.ApplicationDefinitionResourceSelector{{ResourceNames: []string{"postgres-{{ .name }}-default-user"}}} + def := &cozyv1alpha1.ApplicationDefinition{ObjectMeta: metav1.ObjectMeta{Name: "postgres"}} + def.Spec.Application.Kind = "Postgres" + if adminVisible { + def.Spec.Secrets.Include = sel + } else { + def.Spec.Secrets.Exclude = sel + } + return def +} + +func TestHidePlatformSecretsWaitsForTheDefinitionToHideIt(t *testing.T) { + ctx := context.Background() + hr := release(`{}`, "0.2.0", true) + admin := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "postgres-orders-default-user", Namespace: "tenant-foo", Labels: map[string]string{ + corev1alpha1.TenantResourceLabelKey: "true", + }}} + def := definition(true) + m := newMigrator(t, hr, admin, def) + m.o.hideSuffixes = stringFlags{"-default-user"} + + // The old definition still selects it: a label now would be undone by + // the operator's next write, so none is written. + err := m.hidePlatformSecrets(ctx, hr) + if err == nil || !strings.Contains(err.Error(), "still selects postgres-orders-default-user") { + t.Fatalf("hide under the old definition = %v", err) + } + if sec, _ := m.secret(t, "postgres-orders-default-user"); sec.Labels[corev1alpha1.TenantResourceLabelKey] != "true" { + t.Fatal("labelled while the definition still selects the Secret") + } + + // The rd chart upgrades and excludes it: labelled, and the webhook stamps + // every later rewrite the same. + cur := &cozyv1alpha1.ApplicationDefinition{} + if err := m.c.Get(ctx, client.ObjectKeyFromObject(def), cur); err != nil { + t.Fatal(err) + } + cur.Spec.Secrets = definition(false).Spec.Secrets + if err := m.c.Update(ctx, cur); err != nil { + t.Fatal(err) + } + if err := m.hidePlatformSecrets(ctx, hr); err != nil { + t.Fatal(err) + } + if sec, _ := m.secret(t, "postgres-orders-default-user"); sec.Labels[corev1alpha1.TenantResourceLabelKey] != "false" { + t.Fatalf("labels = %v", sec.Labels) + } +} diff --git a/cmd/credentials-migrate/main.go b/cmd/credentials-migrate/main.go index 07004d01a..e648446c8 100644 --- a/cmd/credentials-migrate/main.go +++ b/cmd/credentials-migrate/main.go @@ -34,6 +34,7 @@ import ( ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" "github.com/cozystack/cozystack/pkg/credentials/account" @@ -84,8 +85,10 @@ type options struct { sourceSuffix string sourceKey string sourcePerAccount bool + sourceSelector labelFlags platformKeys stringFlags rotateKeys stringFlags + hideSuffixes stringFlags stateNamespace string actor string timeout time.Duration @@ -146,7 +149,7 @@ func run(args []string) error { return errors.New("usage: credentials-migrate seed|finish [flags]") } cmd := args[0] - o := &options{labels: labelFlags{}} + o := &options{labels: labelFlags{}, sourceSelector: labelFlags{}} fs := flag.NewFlagSet(cmd, flag.ContinueOnError) fs.IntVar(&o.migration, "migration", 0, "number of the platform migration that converts the kind") fs.StringVar(&o.kind, "kind", "", "application kind, as the HelmRelease label names it") @@ -160,7 +163,9 @@ func run(args []string) error { fs.StringVar(&o.sourceSuffix, "source-suffix", "-credentials", "suffix of the chart-generated Secret holding the plaintext passwords, after the release name") fs.StringVar(&o.sourceKey, "source-key", "", "key of the source Secret holding an account's password; empty means the user name") fs.BoolVar(&o.sourcePerAccount, "source-per-account", false, "the chart kept one source Secret per account, named , with the password under --source-key") + fs.Var(o.sourceSelector, "source-selector", "label, key=value, of the chart's per-account source Secrets, found by label and by the Helm release that rendered them rather than by name; each holds the user name under username and the password under --source-key; repeatable") fs.Var(&o.platformKeys, "platform-key", "key of the source Secret that belongs to a platform account and stays; repeatable") + fs.Var(&o.hideSuffixes, "hide-secret-suffix", "finish: suffix, after the release name, of a Secret the chart does not render that holds a platform account; it is labelled not tenant-visible; repeatable") fs.Var(&o.rotateKeys, "rotate-key", "finish: platform key of the source Secret to replace with a new random password once, followed by a forced upgrade of the release; repeatable") fs.StringVar(&o.stateNamespace, "state-namespace", "cozy-system", "namespace of the state ConfigMap") fs.StringVar(&o.actor, "actor", envOr("CREDENTIALS_MIGRATE_ACTOR", defaultActor), "who the record names for the migrated password") @@ -173,8 +178,11 @@ func run(args []string) error { if o.migration == 0 || o.kind == "" || !format.Known(o.formatName) { return errors.New("--migration, --kind and a built-in --format are required") } - if o.sourcePerAccount && o.sourceKey == "" { - return errors.New("--source-per-account needs --source-key: a per-account Secret is not keyed by user name") + if (o.sourcePerAccount || len(o.sourceSelector) > 0) && o.sourceKey == "" { + return errors.New("--source-per-account and --source-selector need --source-key: a per-account Secret is not keyed by user name") + } + if o.sourcePerAccount && len(o.sourceSelector) > 0 { + return errors.New("--source-per-account and --source-selector are two ways to find the same Secrets; pass one") } for _, k := range o.rotateKeys { if !slices.Contains(o.platformKeys, k) { @@ -197,6 +205,9 @@ func run(args []string) error { if err := appsv1.AddToScheme(scheme); err != nil { return err } + if err := cozyv1alpha1.AddToScheme(scheme); err != nil { + return err + } c, err := client.New(ctrl.GetConfigOrDie(), client.Options{Scheme: scheme}) if err != nil { return fmt.Errorf("build client: %w", err) @@ -371,9 +382,47 @@ func (m *migrator) finishRelease(ctx context.Context, hr *helmv2.HelmRelease, re if err := m.retireSource(ctx, hr); err != nil { return err } + if err := m.hidePlatformSecrets(ctx, hr); err != nil { + return err + } return m.rotatePlatformKeys(ctx, hr) } +// hidePlatformSecrets labels the platform Secrets the chart does not render, +// such as one an operator creates, not tenant-visible. The lineage webhook +// decided their visibility at admission and skips them while their lineage +// labels stay, so dropping them from the ApplicationDefinition does not +// reach a Secret that exists until the operator next rewrites it. The label +// goes on only once the definition hides the Secret too, since a rewrite +// before that would stamp it visible again. +func (m *migrator) hidePlatformSecrets(ctx context.Context, hr *helmv2.HelmRelease) error { + for _, suffix := range m.o.hideSuffixes { + sec := &corev1.Secret{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: hr.Name + suffix}, sec); err != nil { + if apierrors.IsNotFound(err) { + continue + } + return err + } + if err := m.waitDefinitionHides(ctx, hr, sec); err != nil { + return err + } + if sec.Labels[corev1alpha1.TenantResourceLabelKey] == "false" { + continue + } + patch := client.MergeFrom(sec.DeepCopy()) + if sec.Labels == nil { + sec.Labels = map[string]string{} + } + sec.Labels[corev1alpha1.TenantResourceLabelKey] = "false" + if err := m.c.Patch(ctx, sec, patch); err != nil { + return fmt.Errorf("hide %s: %w", sec.Name, err) + } + fmt.Printf("%s/%s: labelled %s not tenant-visible\n", hr.Namespace, hr.Name, sec.Name) + } + return nil +} + // seedRelease writes the account Secrets the release lacks, unowned: the // CredentialTemplate controller adopts them once the converted chart renders // the templates. Once every declared account has its Secret, it marks the @@ -391,18 +440,13 @@ func (m *migrator) seedRelease(ctx context.Context, hr *helmv2.HelmRelease) erro if err != nil { return fmt.Errorf("%w: %v", errUnresolvable, err) } - var source *corev1.Secret - if !m.o.sourcePerAccount { - source = &corev1.Secret{} - if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: hr.Name + m.o.sourceSuffix}, source); err != nil { - if !apierrors.IsNotFound(err) { - return err - } - if len(accounts) > 0 { - fmt.Printf("%s/%s: %s%s is gone; its accounts get a Secret at their first mint\n", hr.Namespace, hr.Name, hr.Name, m.o.sourceSuffix) - return nil - } - } + passwords, found, err := m.sourcePasswords(ctx, hr, accounts) + if err != nil { + return err + } + if !found && len(accounts) > 0 { + fmt.Printf("%s/%s: %s is gone; its accounts get a Secret at their first mint\n", hr.Namespace, hr.Name, m.sourceDesc(hr, "")) + return nil } now := metav1.NewTime(m.now()) complete := true @@ -427,10 +471,8 @@ func (m *migrator) seedRelease(ctx context.Context, hr *helmv2.HelmRelease) erro case !apierrors.IsNotFound(err): return err } - plaintext, from, ok, err := m.plaintext(ctx, hr, source, acc.Username) - if err != nil { - return err - } + plaintext, ok := passwords[acc.Username] + from := m.sourceDesc(hr, acc.Username) if !ok { fmt.Printf("%s/%s: no password for %q in %s; the account gets a Secret at its first mint\n", hr.Namespace, hr.Name, acc.Username, from) complete = false @@ -517,31 +559,92 @@ func (m *migrator) addValuesFrom(ctx context.Context, hr *helmv2.HelmRelease, ac return m.c.Patch(ctx, hr, patch) } -// plaintext returns the chart-generated password of one account and the name -// of the Secret it was looked up in: the release's single source Secret or, -// with --source-per-account, the account's own Secret -// , as charts that render one Secret per user -// keep it. The password is under --source-key, or under the user name when -// that is empty. A missing Secret or key is reported as not found. -func (m *migrator) plaintext(ctx context.Context, hr *helmv2.HelmRelease, source *corev1.Secret, user string) ([]byte, string, bool, error) { - key := m.o.sourceKey - if key == "" { - key = user - } - if !m.o.sourcePerAccount { - v, ok := source.Data[key] - return v, source.Name, ok, nil - } - name := m.perAccountSource(hr, user) - sec := &corev1.Secret{} - if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: name}, sec); err != nil { - if apierrors.IsNotFound(err) { - return nil, name, false, nil +// sourcePasswords returns the chart-generated plaintext of the release's +// accounts by user name, and whether any source Secret exists. The chart kept +// either one Secret, , or one Secret per account: +// named with --source-per-account, or found by +// --source-selector and the Helm release that rendered it, for a chart whose +// name mapping is not worth re-deriving. The password is under --source-key, +// or, in the single Secret, under the user name when that is empty. +func (m *migrator) sourcePasswords(ctx context.Context, hr *helmv2.HelmRelease, accounts []account.Account) (map[string][]byte, bool, error) { + passwords := map[string][]byte{} + switch { + case len(m.o.sourceSelector) > 0: + sources, err := m.selectedSources(ctx, hr) + if err != nil { + return nil, false, err } - return nil, name, false, err + for _, sec := range sources { + user := string(sec.Data[account.UsernameKey]) + pw, ok := sec.Data[m.o.sourceKey] + if user == "" || !ok { + continue + } + passwords[user] = pw + } + return passwords, len(sources) > 0, nil + case m.o.sourcePerAccount: + for _, acc := range accounts { + sec := &corev1.Secret{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: m.perAccountSource(hr, acc.Username)}, sec); err != nil { + if apierrors.IsNotFound(err) { + continue + } + return nil, false, err + } + if pw, ok := sec.Data[m.o.sourceKey]; ok { + passwords[acc.Username] = pw + } + } + return passwords, true, nil } - v, ok := sec.Data[key] - return v, name, ok, nil + source := &corev1.Secret{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: hr.Name + m.o.sourceSuffix}, source); err != nil { + if apierrors.IsNotFound(err) { + return nil, false, nil + } + return nil, false, err + } + for _, acc := range accounts { + key := m.o.sourceKey + if key == "" { + key = acc.Username + } + if pw, ok := source.Data[key]; ok { + passwords[acc.Username] = pw + } + } + return passwords, true, nil +} + +// sourceDesc names where the plaintext of user, or of every account when user +// is empty, was looked up. +func (m *migrator) sourceDesc(hr *helmv2.HelmRelease, user string) string { + switch { + case len(m.o.sourceSelector) > 0: + return fmt.Sprintf("the Secrets labelled %s of release %s", m.o.sourceSelector, hr.GetReleaseName()) + case m.o.sourcePerAccount && user != "": + return m.perAccountSource(hr, user) + case m.o.sourcePerAccount: + return hr.Name + m.o.sourceSuffix + "" + } + return hr.Name + m.o.sourceSuffix +} + +// selectedSources lists the per-account source Secrets that carry +// --source-selector and that the release's chart rendered. +func (m *migrator) selectedSources(ctx context.Context, hr *helmv2.HelmRelease) ([]corev1.Secret, error) { + list := &corev1.SecretList{} + if err := m.c.List(ctx, list, client.InNamespace(hr.Namespace), client.MatchingLabels(m.o.sourceSelector)); err != nil { + return nil, err + } + var out []corev1.Secret + for _, sec := range list.Items { + if sec.Annotations[account.ReleaseNameAnnotation] == hr.GetReleaseName() { + out = append(out, sec) + } + } + return out, nil } func (m *migrator) perAccountSource(hr *helmv2.HelmRelease, user string) string { @@ -651,7 +754,7 @@ func (m *migrator) stripPasswords(ctx context.Context, hr *helmv2.HelmRelease) e // stay in its data otherwise, and the Secret itself when no platform key // remains. func (m *migrator) retireSource(ctx context.Context, hr *helmv2.HelmRelease) error { - if m.o.sourcePerAccount { + if m.o.sourcePerAccount || len(m.o.sourceSelector) > 0 { return m.retirePerAccountSources(ctx, hr) } source := &corev1.Secret{} @@ -812,27 +915,39 @@ func (m *migrator) rotatePlatformKeys(ctx context.Context, hr *helmv2.HelmReleas return nil } -// retirePerAccountSources deletes the per-account source Secrets of the -// declared accounts. The converted chart no longer renders them, so Helm has -// usually pruned them at the switch; this removes one Helm left behind. +// retirePerAccountSources deletes the release's per-account source Secrets. +// Each holds one tenant password and nothing else, and the converted chart no +// longer renders them, so Helm has usually pruned them at the switch; this +// removes what a release installed outside Helm, or a failed prune, left. func (m *migrator) retirePerAccountSources(ctx context.Context, hr *helmv2.HelmRelease) error { - accounts, err := m.o.resolveAccounts(hr) - if err != nil { - return err - } - for _, acc := range accounts { - sec := &corev1.Secret{} - name := m.perAccountSource(hr, acc.Username) - if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: name}, sec); err != nil { - if apierrors.IsNotFound(err) { - continue - } + var sources []corev1.Secret + if len(m.o.sourceSelector) > 0 { + var err error + if sources, err = m.selectedSources(ctx, hr); err != nil { return err } + } else { + accounts, err := m.o.resolveAccounts(hr) + if err != nil { + return err + } + for _, acc := range accounts { + sec := &corev1.Secret{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: m.perAccountSource(hr, acc.Username)}, sec); err != nil { + if apierrors.IsNotFound(err) { + continue + } + return err + } + sources = append(sources, *sec) + } + } + for i := range sources { + sec := &sources[i] if err := m.c.Delete(ctx, sec, client.Preconditions{UID: &sec.UID}); err != nil && !apierrors.IsNotFound(err) { return err } - fmt.Printf("%s/%s: deleted %s\n", hr.Namespace, hr.Name, name) + fmt.Printf("%s/%s: deleted %s\n", hr.Namespace, hr.Name, sec.Name) } return nil } diff --git a/cmd/credentials-migrate/main_test.go b/cmd/credentials-migrate/main_test.go index 02ecc618b..f3c8dc8a2 100644 --- a/cmd/credentials-migrate/main_test.go +++ b/cmd/credentials-migrate/main_test.go @@ -21,6 +21,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" "github.com/cozystack/cozystack/pkg/credentials/account" @@ -45,6 +46,9 @@ func newMigratorWith(t *testing.T, funcs *interceptor.Funcs, objs ...client.Obje if err := appsv1.AddToScheme(scheme); err != nil { t.Fatal(err) } + if err := cozyv1alpha1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } b := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objs...).WithStatusSubresource(&helmv2.HelmRelease{}) if funcs != nil { b = b.WithInterceptorFuncs(*funcs) @@ -885,3 +889,137 @@ func TestRunRefusesPerAccountSourcesWithoutAKey(t *testing.T) { t.Fatalf("err = %v", err) } } + +func perAccountSource(name, release, user, password string) *corev1.Secret { + return &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: name, Namespace: "tenant-foo", + Labels: map[string]string{"apps.cozystack.io/user-secret": "true"}, + Annotations: map[string]string{account.ReleaseNameAnnotation: release}, + }, + Data: map[string][]byte{account.UsernameKey: []byte(user), account.PasswordKey: []byte(password)}, + } +} + +// A chart that kept one Secret per account is read by label and by the Helm +// release that rendered it, so a sibling release's Secrets in the same +// namespace never feed this one. +func TestSeedReadsPerAccountSources(t *testing.T) { + ctx := context.Background() + m := newMigrator(t, + release(`{"users":{"web":{},"Api.1":{}}}`, "0.1.0", true), + perAccountSource("postgres-orders-web-credentials", "postgres-orders", "web", "hunter2"), + perAccountSource("postgres-orders-api-1-credentials", "postgres-orders", "Api.1", "secret"), + perAccountSource("postgres-other-web-credentials", "postgres-other", "web", "sibling"), + ) + m.o.formatName = format.Plaintext + m.o.labels = labelFlags{"rabbitmq.com/topology-operator": "true"} + m.o.sourceSelector = labelFlags{"apps.cozystack.io/user-secret": "true"} + m.o.sourceKey = account.PasswordKey + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + for _, c := range []struct{ secret, user, plain string }{{"postgres-orders.web.account", "web", "hunter2"}, {"postgres-orders.api-1.account", "Api.1", "secret"}} { + sec, ok := m.secret(t, c.secret) + if !ok { + t.Fatalf("%s not written", c.secret) + } + if string(sec.Data[account.UsernameKey]) != c.user || string(sec.Data[account.PasswordKey]) != c.plain { + t.Fatalf("%s data = %q", c.secret, sec.Data) + } + if sec.Labels["rabbitmq.com/topology-operator"] != "true" || sec.Annotations[account.FormatAnnotation] != format.Plaintext { + t.Fatalf("%s meta = %+v", c.secret, sec.ObjectMeta) + } + } + hr := &helmv2.HelmRelease{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: "tenant-foo", Name: "postgres-orders"}, hr); err != nil { + t.Fatal(err) + } + if hr.Annotations[account.SeedAnnotation] != "true" { + t.Fatal("a release whose accounts all got a Secret must be marked for seeding") + } +} + +func TestSeedWithoutPerAccountSourcesLeavesTheReleaseUnmarked(t *testing.T) { + ctx := context.Background() + m := newMigrator(t, release(`{"users":{"web":{}}}`, "0.1.0", true)) + m.o.formatName = format.Plaintext + m.o.sourceSelector = labelFlags{"apps.cozystack.io/user-secret": "true"} + m.o.sourceKey = account.PasswordKey + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + if _, ok := m.secret(t, "postgres-orders.web.account"); ok { + t.Fatal("no account Secret can be written without its plaintext") + } + hr := &helmv2.HelmRelease{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: "tenant-foo", Name: "postgres-orders"}, hr); err != nil { + t.Fatal(err) + } + if hr.Annotations[account.SeedAnnotation] == "true" { + t.Fatal("a release whose passwords are gone must not be seeded with random ones") + } +} + +// RabbitMQ's chart default is users: {}, which leaves no source to select. +func TestSeedMarksAReleaseWithoutUsersFromSelectedSources(t *testing.T) { + ctx := context.Background() + m := newMigrator(t, release(`{"users":{}}`, "0.1.0", true)) + m.o.formatName = format.Plaintext + m.o.sourceSelector = labelFlags{"apps.cozystack.io/user-secret": "true"} + m.o.sourceKey = account.PasswordKey + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + hr := &helmv2.HelmRelease{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: "tenant-foo", Name: "postgres-orders"}, hr); err != nil { + t.Fatal(err) + } + if hr.Annotations[account.SeedAnnotation] != "true" { + t.Fatal("a release without users must be marked, or its first user never gets a Secret") + } +} + +func TestRetireSourceDeletesPerAccountSourcesOfThisReleaseOnly(t *testing.T) { + ctx := context.Background() + hr := release(`{"users":{"web":{}}}`, "0.2.0", true) + m := newMigrator(t, hr, + perAccountSource("postgres-orders-web-credentials", "postgres-orders", "web", "hunter2"), + perAccountSource("postgres-other-web-credentials", "postgres-other", "web", "sibling"), + ) + m.o.sourceSelector = labelFlags{"apps.cozystack.io/user-secret": "true"} + m.o.sourceKey = account.PasswordKey + if err := m.retireSource(ctx, hr); err != nil { + t.Fatal(err) + } + if _, ok := m.secret(t, "postgres-orders-web-credentials"); ok { + t.Fatal("the release's per-account source must be deleted") + } + if _, ok := m.secret(t, "postgres-other-web-credentials"); !ok { + t.Fatal("a sibling release's Secret must be left alone") + } +} + +func TestHidePlatformSecretsLabelsAnOperatorSecret(t *testing.T) { + ctx := context.Background() + hr := release(`{}`, "0.2.0", true) + admin := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "postgres-orders-default-user", Namespace: "tenant-foo", Labels: map[string]string{ + corev1alpha1.TenantResourceLabelKey: "true", "app.kubernetes.io/name": "orders", + }}} + m := newMigrator(t, hr, admin) + m.o.hideSuffixes = stringFlags{"-default-user", "-missing"} + if err := m.hidePlatformSecrets(ctx, hr); err != nil { + t.Fatal(err) + } + sec, ok := m.secret(t, "postgres-orders-default-user") + if !ok || sec.Labels[corev1alpha1.TenantResourceLabelKey] != "false" || sec.Labels["app.kubernetes.io/name"] != "orders" { + t.Fatalf("secret = %+v", sec) + } +} + +func TestRunRefusesTwoWaysToFindPerAccountSources(t *testing.T) { + err := run([]string{"seed", "--migration=68", "--kind=RabbitMQ", "--format=plaintext", "--source-key=password", "--source-per-account", "--source-selector=apps.cozystack.io/user-secret=true"}) + if err == nil || !strings.Contains(err.Error(), "pass one") { + t.Fatalf("err = %v", err) + } +}