diff --git a/cmd/credentials-migrate/main.go b/cmd/credentials-migrate/main.go index 27e532cec..6714b9b56 100644 --- a/cmd/credentials-migrate/main.go +++ b/cmd/credentials-migrate/main.go @@ -15,12 +15,16 @@ import ( "flag" "fmt" "os" + "slices" "sort" + "strconv" "strings" "time" helmv2 "github.com/fluxcd/helm-controller/api/v2" + fluxmeta "github.com/fluxcd/pkg/apis/meta" corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/equality" apierrors "k8s.io/apimachinery/pkg/api/errors" apimeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -52,6 +56,18 @@ const ( incompleteLabel = "credentials.cozystack.io/incomplete" ) +const ( + // RotatedAnnotation on the source Secret records when finish rotated its + // platform passwords. + RotatedAnnotation = "credentials.cozystack.io/rotated" + // ForcedAnnotation on the source Secret holds the RotatedAnnotation + // value of the rotation a forced upgrade was requested for. + ForcedAnnotation = "credentials.cozystack.io/forced" + // SuspendedByAnnotation on a HelmRelease names the migration that + // suspended it for a rotation, so only that suspension is lifted. + SuspendedByAnnotation = "credentials.cozystack.io/suspended-by-migration" +) + // options is the kind's credentials block and the migration's identity, as // the hook and the Job pass them. type options struct { @@ -60,9 +76,12 @@ type options struct { formatName string accountsPath string refuseFlags stringFlags + reservedUsers stringFlags labels labelFlags + valuesPath string sourceSuffix string platformKeys stringFlags + rotateKeys stringFlags stateNamespace string actor string timeout time.Duration @@ -125,9 +144,12 @@ func run(args []string) error { fs.StringVar(&o.formatName, "format", "", "password format of the kind's credentials block") fs.StringVar(&o.accountsPath, "accounts-path", "users", "values map whose keys are the tenant accounts") fs.Var(&o.refuseFlags, "refuse-flag", "user field that leaves a release out when it is true, because the converted chart refuses it; repeatable") + fs.Var(&o.reservedUsers, "reserved-user", "user name that leaves a release out, because the converted chart refuses it as a platform or engine account; repeatable") fs.Var(o.labels, "label", "label every account Secret carries, key=value; repeatable") + fs.StringVar(&o.valuesPath, "values-path", "", "the kind's CredentialTemplate valuesPath: the hook adds the valuesFrom entry of every account to the release, so the first render of the converted chart already carries the stored values") fs.StringVar(&o.sourceSuffix, "source-suffix", "-credentials", "suffix of the chart-generated Secret holding the plaintext passwords, after the release name") fs.Var(&o.platformKeys, "platform-key", "key of the source Secret that belongs to a platform account and stays; 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") fs.DurationVar(&o.timeout, "timeout", 10*time.Minute, "finish: how long to wait per release for the switched chart to be Ready") @@ -137,6 +159,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") } + for _, k := range o.rotateKeys { + if !slices.Contains(o.platformKeys, k) { + return fmt.Errorf("--rotate-key %q is not a --platform-key, and finish would delete it from the source Secret", k) + } + } scheme := runtime.NewScheme() if err := corev1.AddToScheme(scheme); err != nil { @@ -291,10 +318,19 @@ func (m *migrator) finishRelease(ctx context.Context, hr *helmv2.HelmRelease, re return err } } + // Suspend before the values change: patching them starts a render, and + // one that reads the source with lookup before the rotation below would + // write the retired password back after it. + if err := m.suspendForRotation(ctx, hr); err != nil { + return err + } if err := m.stripPasswords(ctx, hr); err != nil { return fmt.Errorf("strip passwords from values: %w", err) } - return m.retireSource(ctx, hr) + if err := m.retireSource(ctx, hr); err != nil { + return err + } + return m.rotatePlatformKeys(ctx, hr) } // seedRelease writes the account Secrets the release lacks, unowned: the @@ -310,7 +346,7 @@ func (m *migrator) finishRelease(ctx context.Context, hr *helmv2.HelmRelease, re // the first user added later would never get a Secret. Every failure other // than unresolvable accounts is an error. func (m *migrator) seedRelease(ctx context.Context, hr *helmv2.HelmRelease) error { - accounts, err := resolveAccounts(hr, m.o.accountsPath, m.o.refuseFlags) + accounts, err := resolveAccounts(hr, m.o.accountsPath, m.o.refuseFlags, m.o.reservedUsers) if err != nil { return fmt.Errorf("%w: %v", errUnresolvable, err) } @@ -384,6 +420,9 @@ func (m *migrator) seedRelease(ctx context.Context, hr *helmv2.HelmRelease) erro } fmt.Printf("%s/%s: migrated account %q into %s\n", hr.Namespace, hr.Name, acc.Username, name) } + if err := m.addValuesFrom(ctx, hr, accounts); err != nil { + return fmt.Errorf("add valuesFrom entries: %w", err) + } if !complete || hr.Annotations[account.SeedAnnotation] == "true" { return nil } @@ -398,11 +437,45 @@ func (m *migrator) seedRelease(ctx context.Context, hr *helmv2.HelmRelease) erro return nil } +// addValuesFrom gives the release the valuesFrom entry of every account, +// as the CredentialTemplate controller builds it, for a kind whose templates +// name a valuesPath. The controller adds them only once the converted chart +// has rendered the templates, so without them that first render would carry +// no stored value, and the chart would leave every account out of the engine +// until the next upgrade. The entries are optional and the old chart ignores +// the values they fill, so adding them ahead of the switch changes nothing for +// it. Non-account entries keep their place, and account entries are replaced +// in template-name order, which is the controller's, so it finds nothing to +// change. +func (m *migrator) addValuesFrom(ctx context.Context, hr *helmv2.HelmRelease, accounts []account.Account) error { + if m.o.valuesPath == "" { + return nil + } + var want []helmv2.ValuesReference + for _, ref := range hr.Spec.ValuesFrom { + if !account.IsAccountValuesFrom(ref) { + want = append(want, ref) + } + } + sorted := slices.Clone(accounts) + sort.Slice(sorted, func(i, j int) bool { return sorted[i].Mapped < sorted[j].Mapped }) + for _, acc := range sorted { + want = append(want, account.ValuesFrom(account.SecretName(hr.Name, acc.Mapped), m.o.valuesPath, acc.Username)) + } + if equality.Semantic.DeepEqual(hr.Spec.ValuesFrom, want) { + return nil + } + patch := client.MergeFrom(hr.DeepCopy()) + hr.Spec.ValuesFrom = want + return m.c.Patch(ctx, hr, patch) +} + // resolveAccounts returns the accounts the release declares: the keys of its // accounts map, in sorted order. Two users mapping to one name, a user whose // name maps to an invalid one, or a user with a refused field set to true, -// which the converted chart would not render, leave the release unresolvable. -func resolveAccounts(hr *helmv2.HelmRelease, path string, refuse []string) ([]account.Account, error) { +// which the converted chart would not render, or a reserved user name leave +// the release unresolvable. +func resolveAccounts(hr *helmv2.HelmRelease, path string, refuse, reserved []string) ([]account.Account, error) { var values map[string]any if hr.Spec.Values != nil && len(hr.Spec.Values.Raw) > 0 { if err := json.Unmarshal(hr.Spec.Values.Raw, &values); err != nil { @@ -418,6 +491,9 @@ func resolveAccounts(hr *helmv2.HelmRelease, path string, refuse []string) ([]ac var accounts []account.Account byMapped := map[string]string{} for _, name := range names { + if slices.Contains(reserved, name) { + return nil, fmt.Errorf("%s.%s is a name the converted chart reserves for a platform or engine account; rename the user", path, name) + } if u, ok := users[name].(map[string]any); ok { for _, field := range refuse { if on, _ := u[field].(bool); on { @@ -529,6 +605,128 @@ func (m *migrator) retireSource(ctx context.Context, hr *helmv2.HelmRelease) err return nil } +// suspendForRotation suspends the release while a rotation is still due, and +// reads it back to confirm the suspension held: an API server that drops +// spec.suspend would let a render write the old password back unnoticed. A +// release already suspended is left as it is, whether an earlier run of this +// migration or someone else suspended it; rotatePlatformKeys tells the two +// apart before it forces the upgrade. +func (m *migrator) suspendForRotation(ctx context.Context, hr *helmv2.HelmRelease) error { + if len(m.o.rotateKeys) == 0 || hr.Spec.Suspend { + return 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 + } + return err + } + if source.Annotations[RotatedAnnotation] != "" { + return nil + } + mark := strconv.Itoa(m.o.migration) + patch := client.MergeFrom(hr.DeepCopy()) + hr.Spec.Suspend = true + if hr.Annotations == nil { + hr.Annotations = map[string]string{} + } + hr.Annotations[SuspendedByAnnotation] = mark + if err := m.c.Patch(ctx, hr, patch); err != nil { + return fmt.Errorf("suspend for rotation: %w", err) + } + if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), hr); err != nil { + return fmt.Errorf("confirm the suspension for rotation: %w", err) + } + if !hr.Spec.Suspend || hr.Annotations[SuspendedByAnnotation] != mark { + return errors.New("the release did not stay suspended for the rotation, so a render could write the old platform password back; check what resets spec.suspend and run the conversion again") + } + return nil +} + +// rotatePlatformKeys replaces, once, the platform passwords tenants could read +// in the source Secret before the conversion, and forces an upgrade of the +// release so the chart, which reads them back with lookup, applies the new +// ones. The release is suspended while the Secret changes, so no render that +// started from the old value writes it back, and only a suspension this +// migration set is lifted. A release someone else suspended is left out +// until they resume it: helm-controller marks a reconcile request handled +// even while the release is suspended, and a force request only counts +// together with an unhandled reconcile request (fluxcd/pkg apis/meta +// HandleAnnotationRequest), so a force requested now would be spent before +// the resume and the new password would never reach the engine. Annotations +// on the Secret record the rotation, so a rerun does not rotate twice, and +// the chart may key a restart of the consumers that read the password at +// start on it, and the forced upgrade, so a rerun does not force twice. +func (m *migrator) rotatePlatformKeys(ctx context.Context, hr *helmv2.HelmRelease) error { + if len(m.o.rotateKeys) == 0 { + return 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) { + // The chart generates a value no tenant has read at its next render. + return nil + } + return err + } + mark := strconv.Itoa(m.o.migration) + if source.Annotations[RotatedAnnotation] == "" { + if err := m.suspendForRotation(ctx, hr); err != nil { + return err + } + patch := client.MergeFrom(source.DeepCopy()) + rotated := 0 + for _, k := range m.o.rotateKeys { + if _, ok := source.Data[k]; !ok { + continue + } + password, err := format.GeneratePassword() + if err != nil { + return err + } + source.Data[k] = []byte(password) + rotated++ + } + if source.Annotations == nil { + source.Annotations = map[string]string{} + } + source.Annotations[RotatedAnnotation] = m.now().UTC().Format(time.RFC3339) + if err := m.c.Patch(ctx, source, patch); err != nil { + return fmt.Errorf("rotate %s: %w", source.Name, err) + } + fmt.Printf("%s/%s: rotated %d platform password(s) in %s\n", hr.Namespace, hr.Name, rotated, source.Name) + } + if source.Annotations[ForcedAnnotation] == source.Annotations[RotatedAnnotation] { + return nil + } + if hr.Spec.Suspend && hr.Annotations[SuspendedByAnnotation] != mark { + return fmt.Errorf("the platform passwords in %s are rotated, but the release is suspended by someone else, and a forced upgrade requested now would be spent while it stays suspended; resume it and run the conversion again", source.Name) + } + // Request a forced upgrade, and lift the suspension this migration set, + // including one left by an interrupted earlier run. + now := m.now().UTC().Format(time.RFC3339Nano) + patch := client.MergeFrom(hr.DeepCopy()) + if hr.Annotations == nil { + hr.Annotations = map[string]string{} + } + hr.Annotations[fluxmeta.ReconcileRequestAnnotation] = now + hr.Annotations[fluxmeta.ForceRequestAnnotation] = now + if hr.Annotations[SuspendedByAnnotation] == mark { + hr.Spec.Suspend = false + delete(hr.Annotations, SuspendedByAnnotation) + } + if err := m.c.Patch(ctx, hr, patch); err != nil { + return fmt.Errorf("force an upgrade after rotation: %w", err) + } + forced := client.MergeFrom(source.DeepCopy()) + source.Annotations[ForcedAnnotation] = source.Annotations[RotatedAnnotation] + if err := m.c.Patch(ctx, source, forced); err != nil { + return fmt.Errorf("record the forced upgrade on %s: %w", source.Name, err) + } + return nil +} + func (m *migrator) releases(ctx context.Context) ([]helmv2.HelmRelease, error) { list := &helmv2.HelmReleaseList{} if err := m.c.List(ctx, list, client.MatchingLabels{ diff --git a/cmd/credentials-migrate/main_test.go b/cmd/credentials-migrate/main_test.go index 016007839..697fc88d6 100644 --- a/cmd/credentials-migrate/main_test.go +++ b/cmd/credentials-migrate/main_test.go @@ -456,3 +456,301 @@ func TestSeedLeavesOutAReleaseWithARefusedFlag(t *testing.T) { t.Fatal("a release the converted chart refuses must not be converted in part") } } + +func TestSeedLeavesOutAReleaseWithAReservedUser(t *testing.T) { + ctx := context.Background() + m := newMigrator(t, release(`{"users":{"web":{},"backup":{}}}`, "0.1.0", true), sourceSecret(map[string]string{"web": "hunter2", "backup": "platform"})) + m.o.reservedUsers = stringFlags{"backup", "default"} + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + st, err := m.loadState(ctx) + if err != nil { + t.Fatal(err) + } + if why, left := st.Skipped["tenant-foo/postgres-orders"]; !left || !strings.Contains(why, "reserves") { + t.Fatalf("state = %+v, want the release left out for the reserved name", st) + } + for _, name := range []string{"postgres-orders.web.account", "postgres-orders.backup.account"} { + if _, ok := m.secret(t, name); ok { + t.Fatalf("%s: a release the converted chart refuses must not be converted in part", name) + } + } +} + +// With a values path, the hook gives the release the controller's valuesFrom +// entries ahead of the switch, so the converted chart's first render already +// carries every stored value; other entries keep their place. +func TestSeedAddsTheAccountValuesFrom(t *testing.T) { + ctx := context.Background() + hr := release(`{"users":{"web":{},"Api.1":{}}}`, "0.1.0", true) + hr.Spec.ValuesFrom = []helmv2.ValuesReference{ + {Kind: "Secret", Name: "cozystack-values"}, + account.ValuesFrom("postgres-orders.gone.account", "_accounts", "gone"), + } + m := newMigrator(t, hr, sourceSecret(map[string]string{"web": "hunter2", "Api.1": "secret"})) + m.o.valuesPath = "_accounts" + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + cur := &helmv2.HelmRelease{} + if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil { + t.Fatal(err) + } + want := []helmv2.ValuesReference{ + {Kind: "Secret", Name: "cozystack-values"}, + account.ValuesFrom("postgres-orders.api-1.account", "_accounts", "Api.1"), + account.ValuesFrom("postgres-orders.web.account", "_accounts", "web"), + } + if len(cur.Spec.ValuesFrom) != len(want) { + t.Fatalf("valuesFrom = %+v", cur.Spec.ValuesFrom) + } + for i := range want { + if cur.Spec.ValuesFrom[i] != want[i] { + t.Fatalf("valuesFrom[%d] = %+v, want %+v", i, cur.Spec.ValuesFrom[i], want[i]) + } + } + if !strings.HasPrefix(want[2].TargetPath, "_accounts.u") || !want[2].Optional { + t.Fatalf("entry = %+v", want[2]) + } + + // Without a values path the release's valuesFrom is left as it is. + hr2 := release(`{"users":{"web":{}}}`, "0.1.0", true) + m = newMigrator(t, hr2, sourceSecret(map[string]string{"web": "hunter2"})) + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr2), cur); err != nil { + t.Fatal(err) + } + if len(cur.Spec.ValuesFrom) != 0 { + t.Fatalf("valuesFrom = %+v, want none", cur.Spec.ValuesFrom) + } +} + +func rotationFixture(t *testing.T, suspended bool, annotations map[string]string) (*migrator, *helmv2.HelmRelease) { + t.Helper() + hr := release(`{"users":{"web":{}}}`, "0.2.0", true) + hr.Spec.Suspend = suspended + hr.Annotations = annotations + m := newMigrator(t, hr, sourceSecret(map[string]string{"backup": "tenant-readable"})) + m.o.platformKeys = stringFlags{"backup"} + m.o.rotateKeys = stringFlags{"backup"} + return m, hr +} + +func TestRotatePlatformKeysOnceAndForcesAnUpgrade(t *testing.T) { + ctx := context.Background() + m, hr := rotationFixture(t, false, nil) + if err := m.rotatePlatformKeys(ctx, hr); err != nil { + t.Fatal(err) + } + sec, _ := m.secret(t, "postgres-orders-credentials") + first := string(sec.Data["backup"]) + if first == "tenant-readable" || len(first) != 32 || sec.Annotations[RotatedAnnotation] == "" { + t.Fatalf("source = %v %v", sec.Annotations, len(first)) + } + cur := &helmv2.HelmRelease{} + if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil { + t.Fatal(err) + } + if cur.Spec.Suspend || cur.Annotations[SuspendedByAnnotation] != "" { + t.Fatalf("the suspension the rotation set must be lifted: %+v", cur.Annotations) + } + if at := cur.Annotations["reconcile.fluxcd.io/forceAt"]; at == "" || at != cur.Annotations["reconcile.fluxcd.io/requestedAt"] { + t.Fatalf("want a forced upgrade, annotations = %v", cur.Annotations) + } + + // A rerun does not rotate twice. + if err := m.rotatePlatformKeys(ctx, cur); err != nil { + t.Fatal(err) + } + sec, _ = m.secret(t, "postgres-orders-credentials") + if string(sec.Data["backup"]) != first { + t.Fatal("a rerun must not rotate again") + } +} + +// A run stopped between the suspension and the Secret write is finished by +// the next one, which also lifts the suspension it left. +func TestRotatePlatformKeysRecoversAnInterruptedRun(t *testing.T) { + ctx := context.Background() + m, hr := rotationFixture(t, true, map[string]string{SuspendedByAnnotation: "64"}) + if err := m.rotatePlatformKeys(ctx, hr); err != nil { + t.Fatal(err) + } + sec, _ := m.secret(t, "postgres-orders-credentials") + if string(sec.Data["backup"]) == "tenant-readable" { + t.Fatal("the rotation must complete") + } + cur := &helmv2.HelmRelease{} + if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil { + t.Fatal(err) + } + if cur.Spec.Suspend { + t.Fatal("the suspension an earlier run set must be lifted") + } +} + +// A release someone else suspended stays suspended and is left out with no +// force request, which helm-controller would spend while it is suspended; the +// rerun after the resume forces the upgrade, once. +func TestRotatePlatformKeysKeepsAForeignSuspension(t *testing.T) { + ctx := context.Background() + m, hr := rotationFixture(t, true, nil) + if err := m.rotatePlatformKeys(ctx, hr); err == nil || !strings.Contains(err.Error(), "suspended by someone else") { + t.Fatalf("err = %v", err) + } + cur := &helmv2.HelmRelease{} + if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil { + t.Fatal(err) + } + if !cur.Spec.Suspend || cur.Annotations["reconcile.fluxcd.io/forceAt"] != "" || cur.Annotations["reconcile.fluxcd.io/requestedAt"] != "" { + t.Fatalf("suspend = %v, annotations = %v", cur.Spec.Suspend, cur.Annotations) + } + sec, _ := m.secret(t, "postgres-orders-credentials") + rotated := string(sec.Data["backup"]) + if rotated == "tenant-readable" || sec.Annotations[ForcedAnnotation] != "" { + t.Fatalf("source = %v", sec.Annotations) + } + + // Resumed: the rerun forces the upgrade without rotating again. + patch := client.MergeFrom(cur.DeepCopy()) + cur.Spec.Suspend = false + if err := m.c.Patch(ctx, cur, patch); err != nil { + t.Fatal(err) + } + if err := m.rotatePlatformKeys(ctx, cur); err != nil { + t.Fatal(err) + } + if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil { + t.Fatal(err) + } + forceAt := cur.Annotations["reconcile.fluxcd.io/forceAt"] + if forceAt == "" || forceAt != cur.Annotations["reconcile.fluxcd.io/requestedAt"] { + t.Fatalf("want a forced upgrade, annotations = %v", cur.Annotations) + } + sec, _ = m.secret(t, "postgres-orders-credentials") + if string(sec.Data["backup"]) != rotated || sec.Annotations[ForcedAnnotation] != sec.Annotations[RotatedAnnotation] { + t.Fatalf("source = %v", sec.Annotations) + } + + // Forced once: a further rerun leaves the request alone. + m.now = func() time.Time { return time.Date(2026, 10, 15, 12, 0, 0, 0, time.UTC) } + if err := m.rotatePlatformKeys(ctx, cur); err != nil { + t.Fatal(err) + } + if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil { + t.Fatal(err) + } + if cur.Annotations["reconcile.fluxcd.io/forceAt"] != forceAt { + t.Fatal("a rerun after the forced upgrade must not force again") + } +} + +// rotationFinishFixture is a seeded release on the converted chart whose +// values still carry a password and whose source holds a platform key due +// for rotation; patches of the release go through onPatch first. +func rotationFinishFixture(t *testing.T, onPatch func(c client.WithWatch, hr *helmv2.HelmRelease, data []byte) error) *migrator { + t.Helper() + funcs := &interceptor.Funcs{Patch: func(ctx context.Context, c client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if hr, ok := obj.(*helmv2.HelmRelease); ok && onPatch != nil { + data, err := patch.Data(obj) + if err != nil { + return err + } + if err := onPatch(c, hr, data); err != nil { + return err + } + } + return c.Patch(ctx, obj, patch, opts...) + }} + hr := release(`{"users":{"web":{"password":"leftover"}}}`, "0.1.0", true) + m := newMigratorWith(t, funcs, hr, sourceSecret(map[string]string{"web": "hunter2", "backup": "tenant-readable"})) + m.o.platformKeys = stringFlags{"backup"} + m.o.rotateKeys = stringFlags{"backup"} + if err := m.seed(context.Background()); err != nil { + t.Fatal(err) + } + m.switchChart(t, "0.2.0", true) + return m +} + +// Stripping the passwords from the values starts a render that reads the +// source with lookup, so the release is suspended before the values change; +// otherwise that render could write the retired backup password back after +// the rotation, and nothing would retry. +func TestFinishSuspendsBeforeTheValuesChange(t *testing.T) { + ctx := context.Background() + valuesPatched, unsuspended := false, false + m := rotationFinishFixture(t, func(c client.WithWatch, hr *helmv2.HelmRelease, data []byte) error { + if !strings.Contains(string(data), `"values"`) { + return nil + } + valuesPatched = true + cur := &helmv2.HelmRelease{} + if err := c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil { + return err + } + if !cur.Spec.Suspend { + unsuspended = true + } + return nil + }) + if err := m.finish(ctx); err != nil { + t.Fatal(err) + } + if !valuesPatched { + t.Fatal("the leftover password must be stripped from the values") + } + if unsuspended { + t.Fatal("the values changed while the release was not suspended for the rotation") + } + cur := &helmv2.HelmRelease{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: "tenant-foo", Name: "postgres-orders"}, cur); err != nil { + t.Fatal(err) + } + if cur.Spec.Suspend || cur.Annotations[SuspendedByAnnotation] != "" || cur.Annotations["reconcile.fluxcd.io/forceAt"] == "" { + t.Fatalf("suspend = %v, annotations = %v", cur.Spec.Suspend, cur.Annotations) + } + sec, _ := m.secret(t, "postgres-orders-credentials") + if string(sec.Data["backup"]) == "tenant-readable" { + t.Fatal("the backup password must be rotated") + } +} + +// A suspension that does not persist leaves the release out before its +// values change or its platform password is rotated. +func TestFinishLeavesOutAReleaseThatDoesNotStaySuspended(t *testing.T) { + ctx := context.Background() + m := rotationFinishFixture(t, func(_ client.WithWatch, hr *helmv2.HelmRelease, _ []byte) error { + hr.Spec.Suspend = false + return nil + }) + err := m.finish(ctx) + if err == nil || !strings.Contains(err.Error(), "did not stay suspended") { + t.Fatalf("err = %v", err) + } + sec, _ := m.secret(t, "postgres-orders-credentials") + if string(sec.Data["backup"]) != "tenant-readable" || sec.Annotations[RotatedAnnotation] != "" { + t.Fatalf("source = %v", sec.Annotations) + } + cur := &helmv2.HelmRelease{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: "tenant-foo", Name: "postgres-orders"}, cur); err != nil { + t.Fatal(err) + } + var values map[string]any + if err := json.Unmarshal(cur.Spec.Values.Raw, &values); err != nil { + t.Fatal(err) + } + if _, has := values["users"].(map[string]any)["web"].(map[string]any)["password"]; !has { + t.Fatal("the values must not change before the suspension holds") + } +} + +func TestRunRefusesARotateKeyThatIsNotAPlatformKey(t *testing.T) { + err := run([]string{"finish", "--migration=65", "--kind=ClickHouse", "--format=sha256", "--rotate-key=backup"}) + if err == nil || !strings.Contains(err.Error(), "not a --platform-key") { + t.Fatalf("err = %v", err) + } +}