diff --git a/api/apps/v1alpha1/clickhouse/types.go b/api/apps/v1alpha1/clickhouse/types.go index a8cda85bd..521f3eef2 100644 --- a/api/apps/v1alpha1/clickhouse/types.go +++ b/api/apps/v1alpha1/clickhouse/types.go @@ -45,7 +45,7 @@ type ConfigSpec struct { // TTL (expiration time) for `query_log` and `query_thread_log`. // +kubebuilder:default:=15 LogTTL int `json:"logTTL"` - // Users configuration map. + // Users configuration map. Passwords are issued through the Cozystack credentials API: a mint on the user's `Credential` (`core.cozystack.io`) returns a new password once and stores only its SHA-256, and a revoke retires the password without issuing one. A user can log in once a password has been minted, after the release has upgraded with it. The names `backup`, `default` and `clickhouse_operator` are reserved for platform accounts. A `password` key here is ignored. // +kubebuilder:default:={} Users map[string]User `json:"users,omitempty"` // Backup configuration. @@ -155,8 +155,6 @@ type S3CredentialsSecret struct { } type User struct { - // Password for the user. - Password string `json:"password,omitempty"` // User is readonly (default: false). Readonly bool `json:"readonly,omitempty"` } diff --git a/cmd/credentials-migrate/hold.go b/cmd/credentials-migrate/hold.go new file mode 100644 index 000000000..8b096ce01 --- /dev/null +++ b/cmd/credentials-migrate/hold.go @@ -0,0 +1,225 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "errors" + "fmt" + "sort" + "strconv" + "strings" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + appsv1 "k8s.io/api/apps/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// HeldByAnnotation on a HelmRelease names the migration that suspended it +// until the components the converted chart relies on have rolled out, so +// only that suspension is lifted. It is not SuspendedByAnnotation: lifting a +// hold must not pass for the forced upgrade a rotation still owes. +const HeldByAnnotation = "credentials.cozystack.io/held-by-migration" + +// Why the hold exists: every application chart is copied out of the one +// cozystack-packages source, so all of them switch to the new version the +// moment the platform chart moves that source, while the components they +// depend on roll out on their own schedule. A Package dependsOn does not +// order this: tenant releases carry no dependsOn, and Flux's dependsOn only +// asks that the dependency be Ready, which a release still on its old +// revision is. A converted chart that the old cozystack-controller or an old +// operator acts on can lock clients out or roll the database the old way, so +// the hook suspends the kind's releases and the finish Job resumes them once +// those components run their new revision. Neither the old controller nor +// the old cozystack-api touches spec.suspend. + +// parseObjectKey reads a namespace/name pair. +func parseObjectKey(s string) (types.NamespacedName, error) { + ns, name, ok := strings.Cut(s, "/") + if !ok || ns == "" || name == "" || strings.Contains(name, "/") { + return types.NamespacedName{}, fmt.Errorf("%q is not namespace/name", s) + } + return types.NamespacedName{Namespace: ns, Name: name}, nil +} + +// templateImages is what a Deployment's pods run: the images of its pod +// template, in order. An upgrade that crosses a conversion always changes the +// image of a component the converted chart needs, so a change of this value +// tells the new revision from the old one without knowing either tag. +func templateImages(d *appsv1.Deployment) string { + var imgs []string + for _, c := range d.Spec.Template.Spec.InitContainers { + imgs = append(imgs, c.Image) + } + for _, c := range d.Spec.Template.Spec.Containers { + imgs = append(imgs, c.Image) + } + return strings.Join(imgs, ",") +} + +// rolledOut reports whether every pod of the Deployment runs its current +// template and none of the previous one is left. +func rolledOut(d *appsv1.Deployment) bool { + want := int32(1) + if d.Spec.Replicas != nil { + want = *d.Spec.Replicas + } + s := d.Status + return s.ObservedGeneration >= d.Generation && + s.UpdatedReplicas == want && s.Replicas == want && s.AvailableReplicas == want +} + +// recordRollouts keeps, for each Deployment the hold waits for, the images it +// runs before the upgrade; an empty value stands for a Deployment that does +// not exist yet. A rerun of the hook keeps the first record, which is the one +// taken before anything switched. +func (m *migrator) recordRollouts(ctx context.Context, st *state) error { + for _, key := range m.o.holdRollouts { + if _, ok := st.Rollouts[key]; ok { + continue + } + nn, err := parseObjectKey(key) + if err != nil { + return err + } + d := &appsv1.Deployment{} + images := "" + if err := m.c.Get(ctx, nn, d); err != nil { + if !apierrors.IsNotFound(err) { + return fmt.Errorf("read Deployment %s: %w", key, err) + } + } else { + images = templateImages(d) + } + if st.Rollouts == nil { + st.Rollouts = map[string]string{} + } + st.Rollouts[key] = images + fmt.Printf("recorded Deployment %s on %q\n", key, images) + } + return nil +} + +// hold suspends a release until the recorded Deployments have rolled out. A +// release already suspended is left as it is: either this hook held it on an +// earlier run, or someone else suspended it, and that is not ours to lift. +func (m *migrator) hold(ctx context.Context, hr *helmv2.HelmRelease) error { + if len(m.o.holdRollouts) == 0 || hr.Spec.Suspend { + return nil + } + patch := client.MergeFrom(hr.DeepCopy()) + hr.Spec.Suspend = true + if hr.Annotations == nil { + hr.Annotations = map[string]string{} + } + hr.Annotations[HeldByAnnotation] = strconv.Itoa(m.o.migration) + if err := m.c.Patch(ctx, hr, patch); err != nil { + return fmt.Errorf("hold until the new components run: %w", err) + } + fmt.Printf("%s/%s: suspended until %s roll out\n", hr.Namespace, hr.Name, strings.Join(m.o.holdRollouts, ", ")) + return nil +} + +// releaseHolds waits for every recorded Deployment to run a new revision, +// then resumes the releases this migration held. Before resuming one it seeds +// it again, which puts back the valuesFrom entries the old controller may +// have stripped, so the first render of the converted chart carries them. If +// a Deployment does not roll out in time the releases stay suspended and are +// reported left out: their workloads keep running on the old chart, which is +// safer than a converted chart the old components would act on. +func (m *migrator) releaseHolds(ctx context.Context, st *state) error { + if len(st.Rollouts) == 0 { + return nil + } + mark := strconv.Itoa(m.o.migration) + keys := make([]string, 0, len(st.Releases)) + for k, rec := range st.Releases { + if !rec.Done { + keys = append(keys, k) + } + } + sort.Strings(keys) + var held []*helmv2.HelmRelease + for _, key := range keys { + ns, name, _ := strings.Cut(key, "/") + hr := &helmv2.HelmRelease{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: ns, Name: name}, hr); err != nil { + if apierrors.IsNotFound(err) { + continue + } + return err + } + if hr.Spec.Suspend && hr.Annotations[HeldByAnnotation] == mark { + held = append(held, hr) + } + } + if len(held) == 0 { + return nil + } + if err := m.waitRollouts(ctx, st); err != nil { + for _, hr := range held { + m.skip(ctx, st, hr, fmt.Errorf("still suspended: %w; resume it by running this Job again once they have, or by removing %s and setting spec.suspend to false", err, HeldByAnnotation)) + } + return errors.Join(err, m.saveState(ctx, st)) + } + for _, hr := range held { + key := hr.Namespace + "/" + hr.Name + if err := m.seedRelease(ctx, hr); err != nil && !errors.Is(err, errUnresolvable) { + return fmt.Errorf("%s: seed before resuming: %w", key, err) + } + patch := client.MergeFrom(hr.DeepCopy()) + hr.Spec.Suspend = false + delete(hr.Annotations, HeldByAnnotation) + if err := m.c.Patch(ctx, hr, patch); err != nil { + return fmt.Errorf("%s: resume: %w", key, err) + } + delete(st.Skipped, key) + fmt.Printf("%s: resumed\n", key) + } + return m.saveState(ctx, st) +} + +// waitRollouts waits until every recorded Deployment runs images other than +// the recorded ones on all of its pods. +func (m *migrator) waitRollouts(ctx context.Context, st *state) error { + keys := make([]string, 0, len(st.Rollouts)) + for k := range st.Rollouts { + keys = append(keys, k) + } + sort.Strings(keys) + deadline := m.now().Add(m.o.holdTimeout) + for { + var pending []string + for _, key := range keys { + nn, err := parseObjectKey(key) + if err != nil { + return err + } + d := &appsv1.Deployment{} + if err := m.c.Get(ctx, nn, d); err != nil { + if !apierrors.IsNotFound(err) { + return fmt.Errorf("read Deployment %s: %w", key, err) + } + pending = append(pending, key+" (absent)") + continue + } + if templateImages(d) == st.Rollouts[key] { + pending = append(pending, key+" (old revision)") + continue + } + if !rolledOut(d) { + pending = append(pending, key+" (rolling out)") + } + } + if len(pending) == 0 { + return nil + } + if m.now().After(deadline) { + return fmt.Errorf("not rolled out to a new revision after %s: %s", m.o.holdTimeout, strings.Join(pending, ", ")) + } + time.Sleep(10 * time.Second) + } +} diff --git a/cmd/credentials-migrate/hold_test.go b/cmd/credentials-migrate/hold_test.go new file mode 100644 index 000000000..60e87e986 --- /dev/null +++ b/cmd/credentials-migrate/hold_test.go @@ -0,0 +1,239 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "strings" + "testing" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + + "github.com/cozystack/cozystack/pkg/credentials/account" +) + +const controllerKey = "cozy-system/cozystack-controller" + +func controllerDeployment(image string, rolled bool) *appsv1.Deployment { + one := int32(1) + d := &appsv1.Deployment{ + ObjectMeta: metav1.ObjectMeta{Name: "cozystack-controller", Namespace: "cozy-system", Generation: 2}, + Spec: appsv1.DeploymentSpec{ + Replicas: &one, + Template: corev1.PodTemplateSpec{Spec: corev1.PodSpec{Containers: []corev1.Container{{Name: "c", Image: image}}}}, + }, + Status: appsv1.DeploymentStatus{ObservedGeneration: 2, Replicas: 1, UpdatedReplicas: 1, AvailableReplicas: 1}, + } + if !rolled { + // The new ReplicaSet is up but the old pod is still there. + d.Status.Replicas = 2 + } + return d +} + +// setDeployment replaces the controller Deployment, as its rollout would. +func setDeployment(t *testing.T, m *migrator, image string, rolled bool) { + t.Helper() + ctx := context.Background() + cur := &appsv1.Deployment{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: "cozy-system", Name: "cozystack-controller"}, cur); err != nil { + t.Fatal(err) + } + want := controllerDeployment(image, rolled) + cur.Spec = want.Spec + if err := m.c.Update(ctx, cur); err != nil { + t.Fatal(err) + } + cur.Status = want.Status + cur.Status.ObservedGeneration = cur.Generation + if err := m.c.Status().Update(ctx, cur); err != nil { + t.Fatal(err) + } +} + +func getRelease(t *testing.T, m *migrator, name string) *helmv2.HelmRelease { + t.Helper() + hr := &helmv2.HelmRelease{} + if err := m.c.Get(context.Background(), types.NamespacedName{Namespace: "tenant-foo", Name: name}, hr); err != nil { + t.Fatal(err) + } + return hr +} + +func TestSeedHoldsTheKindsReleasesAndRecordsTheRollout(t *testing.T) { + ctx := context.Background() + hr := release(`{"users":{"web":{}}}`, "0.1.0", true) + foreign := release(`{"users":{"web":{}}}`, "0.1.0", true) + foreign.Name = "postgres-paused" + foreign.Spec.Suspend = true + m := newMigrator(t, hr, foreign, sourceSecret(map[string]string{"web": "hunter2"}), controllerDeployment("controller:v1.7.1", true)) + m.o.holdRollouts = stringFlags{controllerKey} + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + cur := getRelease(t, m, "postgres-orders") + if !cur.Spec.Suspend || cur.Annotations[HeldByAnnotation] != "64" { + t.Fatalf("release not held: suspend=%v annotations=%v", cur.Spec.Suspend, cur.Annotations) + } + if cur.Annotations[SuspendedByAnnotation] != "" { + t.Fatal("a hold must not pass for a rotation's suspension") + } + // Someone else's suspension is neither claimed nor lifted later. + if f := getRelease(t, m, "postgres-paused"); !f.Spec.Suspend || f.Annotations[HeldByAnnotation] != "" { + t.Fatalf("foreign suspension changed: %+v", f.ObjectMeta.Annotations) + } + st, err := m.loadState(ctx) + if err != nil { + t.Fatal(err) + } + if st.Rollouts[controllerKey] != "controller:v1.7.1" { + t.Fatalf("rollouts = %v", st.Rollouts) + } + + // A rerun of the hook keeps the record taken before anything switched. + setDeployment(t, m, "controller:v1.8.0", false) + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + if st, _ = m.loadState(ctx); st.Rollouts[controllerKey] != "controller:v1.7.1" { + t.Fatalf("rollouts after rerun = %v", st.Rollouts) + } +} + +func TestSeedWithoutAHoldLeavesReleasesRunning(t *testing.T) { + ctx := context.Background() + hr := release(`{"users":{"web":{}}}`, "0.1.0", true) + m := newMigrator(t, hr, sourceSecret(map[string]string{"web": "hunter2"})) + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + if cur := getRelease(t, m, "postgres-orders"); cur.Spec.Suspend { + t.Fatal("a kind without --hold-until-rollout must not be suspended") + } + if st, _ := m.loadState(ctx); len(st.Rollouts) != 0 { + t.Fatalf("rollouts = %v", st.Rollouts) + } +} + +func TestFinishKeepsReleasesHeldUntilTheNewRevisionRollsOut(t *testing.T) { + ctx := context.Background() + hr := release(`{"users":{"web":{}}}`, "0.1.0", true) + m := newMigrator(t, hr, sourceSecret(map[string]string{"web": "hunter2"}), controllerDeployment("controller:v1.7.1", true)) + m.o.holdRollouts = stringFlags{controllerKey} + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + for _, c := range []struct { + name string + image string + rolled bool + want string + }{ + {"still the old revision", "controller:v1.7.1", true, "old revision"}, + {"the old pod is still running", "controller:v1.8.0", false, "rolling out"}, + } { + setDeployment(t, m, c.image, c.rolled) + err := m.finish(ctx) + if err == nil || !strings.Contains(err.Error(), c.want) { + t.Fatalf("%s: finish = %v, want an error naming %q", c.name, err, c.want) + } + if cur := getRelease(t, m, "postgres-orders"); !cur.Spec.Suspend || cur.Annotations[HeldByAnnotation] != "64" { + t.Fatalf("%s: the release must stay held", c.name) + } + st, _ := m.loadState(ctx) + if why := st.Skipped["tenant-foo/postgres-orders"]; !strings.Contains(why, "still suspended") { + t.Fatalf("%s: skipped = %v", c.name, st.Skipped) + } + cm := &corev1.ConfigMap{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: "cozy-system", Name: "credentials-migration-64"}, cm); err != nil { + t.Fatal(err) + } + if cm.Labels[incompleteLabel] != "true" { + t.Fatalf("%s: a held release must fire the incomplete alert", c.name) + } + if _, ok := m.secret(t, "postgres-orders-credentials"); !ok { + t.Fatalf("%s: nothing may be retired while the release is held", c.name) + } + } +} + +func TestFinishResumesHeldReleasesWithTheirValuesFromOnceRolledOut(t *testing.T) { + ctx := context.Background() + hr := release(`{"users":{"web":{}}}`, "0.1.0", true) + m := newMigrator(t, hr, sourceSecret(map[string]string{"web": "hunter2"}), controllerDeployment("controller:v1.7.1", true)) + m.o.valuesPath = "_accounts" + m.o.holdRollouts = stringFlags{controllerKey} + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + // The old controller rebuilds valuesFrom and drops the account entries. + cur := getRelease(t, m, "postgres-orders") + patch := client.MergeFrom(cur.DeepCopy()) + cur.Spec.ValuesFrom = []helmv2.ValuesReference{{Kind: "Secret", Name: "cozystack-values"}} + if err := m.c.Patch(ctx, cur, patch); err != nil { + t.Fatal(err) + } + + setDeployment(t, m, "controller:v1.8.0", true) + // Resumed, but the chart has not switched yet: the release itself is + // left out by the existing wait, not by the hold. + err := m.finish(ctx) + if err == nil || strings.Contains(err.Error(), "still suspended") { + t.Fatalf("finish = %v", err) + } + cur = getRelease(t, m, "postgres-orders") + if cur.Spec.Suspend || cur.Annotations[HeldByAnnotation] != "" { + t.Fatalf("not resumed: suspend=%v annotations=%v", cur.Spec.Suspend, cur.Annotations) + } + want := account.ValuesFrom("postgres-orders.web.account", "_accounts", "web") + if len(cur.Spec.ValuesFrom) != 2 || cur.Spec.ValuesFrom[1] != want { + t.Fatalf("valuesFrom = %+v: the entries must be back before the first render", cur.Spec.ValuesFrom) + } + + // The chart switches; the conversion completes as before. + cur.Status.History = helmv2.Snapshots{{Version: 2, ChartVersion: "0.2.0", Status: "deployed"}} + if err := m.c.Status().Update(ctx, cur); err != nil { + t.Fatal(err) + } + if err := m.finish(ctx); err != nil { + t.Fatal(err) + } + if st, _ := m.loadState(ctx); !st.Releases["tenant-foo/postgres-orders"].Done || len(st.Skipped) != 0 { + t.Fatalf("state = %+v", st) + } +} + +func TestFinishWaitsForADeploymentAbsentAtTheHook(t *testing.T) { + ctx := context.Background() + hr := release(`{"users":{"web":{}}}`, "0.1.0", true) + m := newMigrator(t, hr, sourceSecret(map[string]string{"web": "hunter2"})) + m.o.holdRollouts = stringFlags{controllerKey} + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + if st, _ := m.loadState(ctx); st.Rollouts[controllerKey] != "" { + t.Fatalf("rollouts = %v", st.Rollouts) + } + if err := m.finish(ctx); err == nil || !strings.Contains(err.Error(), "absent") { + t.Fatalf("finish = %v", err) + } + if err := m.c.Create(ctx, controllerDeployment("controller:v1.8.0", true)); err != nil { + t.Fatal(err) + } + _ = m.finish(ctx) + if cur := getRelease(t, m, "postgres-orders"); cur.Spec.Suspend { + t.Fatal("the release must be resumed once the Deployment exists and rolled out") + } +} + +func TestRunRefusesAMalformedHoldRollout(t *testing.T) { + err := run([]string{"seed", "--migration=65", "--kind=ClickHouse", "--format=sha256", "--hold-until-rollout=cozystack-controller"}) + if err == nil || !strings.Contains(err.Error(), "--hold-until-rollout") { + t.Fatalf("run = %v", err) + } +} diff --git a/cmd/credentials-migrate/main.go b/cmd/credentials-migrate/main.go index 27e532cec..54d15ef7d 100644 --- a/cmd/credentials-migrate/main.go +++ b/cmd/credentials-migrate/main.go @@ -15,12 +15,17 @@ import ( "flag" "fmt" "os" + "slices" "sort" + "strconv" "strings" "time" helmv2 "github.com/fluxcd/helm-controller/api/v2" + fluxmeta "github.com/fluxcd/pkg/apis/meta" + appsv1 "k8s.io/api/apps/v1" 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 +57,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,12 +77,17 @@ 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 + holdRollouts stringFlags + holdTimeout time.Duration } type labelFlags map[string]string @@ -97,6 +119,9 @@ type state struct { // Skipped maps namespace/name to the reason and time it was left out on // the last run. A release leaves the map once a later run finishes it. Skipped map[string]string `json:"skipped,omitempty"` + // Rollouts maps namespace/name of each Deployment the held releases wait + // for to the images it ran when the hook recorded it. + Rollouts map[string]string `json:"rollouts,omitempty"` } type releaseState struct { @@ -125,18 +150,33 @@ 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") + fs.Var(&o.holdRollouts, "hold-until-rollout", "seed: Deployment, namespace/name, whose new revision the converted chart needs; the hook suspends every release of the kind and the finish Job resumes them once each such Deployment runs images other than the ones recorded now; repeatable") + fs.DurationVar(&o.holdTimeout, "hold-timeout", time.Hour, "finish: how long to wait for the --hold-until-rollout Deployments before reporting the held releases left out") if err := fs.Parse(args[1:]); err != nil { return err } 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) + } + } + for _, d := range o.holdRollouts { + if _, err := parseObjectKey(d); err != nil { + return fmt.Errorf("--hold-until-rollout: %w", err) + } + } scheme := runtime.NewScheme() if err := corev1.AddToScheme(scheme); err != nil { @@ -145,6 +185,9 @@ func run(args []string) error { if err := helmv2.AddToScheme(scheme); err != nil { return err } + if err := appsv1.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) @@ -187,6 +230,16 @@ func (m *migrator) seed(ctx context.Context) error { if err != nil { return err } + if len(releases) > 0 { + // Saved before any release is held, so the finish Job always knows + // what it waits for before it resumes them. + if err := m.recordRollouts(ctx, st); err != nil { + return err + } + if err := m.saveState(ctx, st); err != nil { + return err + } + } for i := range releases { hr := &releases[i] key := hr.Namespace + "/" + hr.Name @@ -203,10 +256,13 @@ func (m *migrator) seed(ctx context.Context) error { return fmt.Errorf("%s: %w", key, err) } m.skip(ctx, st, hr, err) - continue + } else { + delete(st.Skipped, key) + fmt.Printf("%s: recorded chart version %q\n", key, rec.ChartVersion) + } + if err := m.hold(ctx, hr); err != nil { + return errors.Join(fmt.Errorf("%s: %w", key, err), m.saveState(ctx, st)) } - delete(st.Skipped, key) - fmt.Printf("%s: recorded chart version %q\n", key, rec.ChartVersion) } return m.saveState(ctx, st) } @@ -218,6 +274,9 @@ func (m *migrator) finish(ctx context.Context) error { if err != nil { return err } + if err := m.releaseHolds(ctx, st); err != nil { + return err + } keys := make([]string, 0, len(st.Releases)) for k := range st.Releases { keys = append(keys, k) @@ -291,10 +350,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 +378,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 +452,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 +469,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 +523,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 +637,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..2051e94aa 100644 --- a/cmd/credentials-migrate/main_test.go +++ b/cmd/credentials-migrate/main_test.go @@ -10,6 +10,7 @@ import ( "time" helmv2 "github.com/fluxcd/helm-controller/api/v2" + appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -41,6 +42,9 @@ func newMigratorWith(t *testing.T, funcs *interceptor.Funcs, objs ...client.Obje if err := helmv2.AddToScheme(scheme); err != nil { t.Fatal(err) } + if err := appsv1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } b := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objs...).WithStatusSubresource(&helmv2.HelmRelease{}) if funcs != nil { b = b.WithInterceptorFuncs(*funcs) @@ -49,7 +53,7 @@ func newMigratorWith(t *testing.T, funcs *interceptor.Funcs, objs ...client.Obje o := &options{ migration: 64, kind: "Postgres", formatName: format.ScramSHA256, accountsPath: "users", labels: labelFlags{"cnpg.io/reload": "true"}, sourceSuffix: "-credentials", - stateNamespace: "cozy-system", actor: "migration", timeout: -time.Second, + stateNamespace: "cozy-system", actor: "migration", timeout: -time.Second, holdTimeout: -time.Second, } return &migrator{c: c, o: o, now: func() time.Time { return time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC) }} } @@ -456,3 +460,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) + } +} diff --git a/hack/e2e-chainsaw/clickhouse/clickhouse-backup.yaml b/hack/e2e-chainsaw/clickhouse/clickhouse-backup.yaml index fb0979146..0e85a2ac4 100644 --- a/hack/e2e-chainsaw/clickhouse/clickhouse-backup.yaml +++ b/hack/e2e-chainsaw/clickhouse/clickhouse-backup.yaml @@ -29,8 +29,7 @@ spec: resourcesPreset: nano resources: {} users: - testuser: - password: xai7Wepo + testuser: {} backup: enabled: true useSystemBucket: false diff --git a/hack/e2e-chainsaw/clickhouse/clickhouse.yaml b/hack/e2e-chainsaw/clickhouse/clickhouse.yaml index 86b9b4e01..2d84e5bbd 100644 --- a/hack/e2e-chainsaw/clickhouse/clickhouse.yaml +++ b/hack/e2e-chainsaw/clickhouse/clickhouse.yaml @@ -10,8 +10,7 @@ spec: storageClass: "" logTTL: 15 users: - testuser: - password: xai7Wepo + testuser: {} backup: enabled: false s3Region: us-east-1 diff --git a/hack/migration-65-clickhouse-credentials.bats b/hack/migration-65-clickhouse-credentials.bats new file mode 100755 index 000000000..2b9d03dbb --- /dev/null +++ b/hack/migration-65-clickhouse-credentials.bats @@ -0,0 +1,234 @@ +#!/usr/bin/env bats +# ----------------------------------------------------------------------------- +# Unit tests for platform migration 65 --> 66 (convert ClickHouse accounts to +# platform-minted credentials, first part). +# +# The migration seeds the account Secrets of every ClickHouse release, then +# creates the cozystack-credentials-migration-65 finish Job directly (rather +# than rendering it from the platform chart) so a changing migrations image +# never collides with an immutable pod template and helm-controller waits on no +# long-running Job. See packages/core/platform/images/migrations/migrations/65. +# +# FAIL CLOSED is pinned for each path: a failed seed, a pod whose image cannot +# be read, and a failed apply of the Job must stop the migration before it +# stamps the version, because migrations never re-run. +# +# The harness (docker, the migrations image base, fake kubectl and +# credentials-migrate on PATH) is the one hack/migration-58-http-cache-freeze.bats +# describes; see there for why each piece is load-bearing. +# +# Run with: hack/cozytest.sh hack/migration-65-clickhouse-credentials.bats +# ----------------------------------------------------------------------------- + +load test_helper + +FAKEBIN="$PWD/hack/testdata/migration-65-clickhouse-credentials" +MIG_DIR="$PWD/packages/core/platform/images/migrations/migrations" +ALPINE=$(sed -n 's/^FROM \(alpine:[^ ]*\).*$/\1/p' \ + "$PWD/packages/core/platform/images/migrations/Dockerfile" | head -1) +TESTIMG="cozystack-migration65-test:$(printf '%s' "$ALPINE" | sed 's/[^a-zA-Z0-9]/-/g')" +WORKROOT="${TMPDIR:-/tmp}/cozy-migration-65-$$" +IMAGE=registry.example.org/cozystack/cozystack:v1.7.0 + +cozy_cleanup() { + rm -rf "$WORKROOT" + return 0 +} + +cmdlog_line() { + grep -nE -- "$1" "$FAKE_CMDLOG" | head -1 | cut -d: -f1 +} + +run_migration() { + _run_migration_rc=0 + docker run --rm --network none \ + --user "$(id -u):$(id -g)" \ + -v "$MIG_DIR:/migrations:ro" \ + -v "$FAKEBIN:/fakebin:ro" \ + -v "$WORK:/work" \ + -e PATH=/fakebin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + -e FAKE_CMDLOG=/work/cmdlog \ + -e NAMESPACE="${NAMESPACE-}" \ + -e FAKE_IMAGE="${FAKE_IMAGE-}" \ + -e FAKE_IMAGE_EMPTY="${FAKE_IMAGE_EMPTY-}" \ + -e FAKE_GETPOD_FAIL="${FAKE_GETPOD_FAIL-}" \ + -e FAKE_APPLY_FAIL="${FAKE_APPLY_FAIL-}" \ + -e FAKE_SEED_FAIL="${FAKE_SEED_FAIL-}" \ + -e FAKE_GETJOB_FAIL="${FAKE_GETJOB_FAIL-}" \ + -e FAKE_JOBUID_EMPTY="${FAKE_JOBUID_EMPTY-}" \ + -e FAKE_PATCH_FAIL="${FAKE_PATCH_FAIL-}" \ + "$TESTIMG" "/migrations/$1" || _run_migration_rc=$? + return "$_run_migration_rc" +} + +prep() { + docker info >/dev/null 2>&1 || { + echo "docker is required: these tests run migration 65 inside a build of" >&2 + echo "$ALPINE, the migrations image's base." >&2 + return 1 + } + docker build -q -t "$TESTIMG" - >/dev/null < "$FAKE_CMDLOG" + export NAMESPACE=cozy-system + export FAKE_IMAGE="$IMAGE" + unset FAKE_IMAGE_EMPTY FAKE_GETPOD_FAIL FAKE_APPLY_FAIL FAKE_SEED_FAIL FAKE_GETJOB_FAIL FAKE_JOBUID_EMPTY FAKE_PATCH_FAIL || true + return 0 +} + +@test "it seeds, creates the finish Job on its own image, and stamps" { + prep + rc=0 + run_migration 65 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -eq 0 ] + + # The seed runs for migration 65. + grep -qE "^CREDMIGRATE seed --migration 65 " "$FAKE_CMDLOG" + + # The finish Job carries its least-privilege ClusterRole (never cluster-admin), + # ServiceAccount and binding, the migration number, and the image this hook + # runs as, read from its own pod rather than values. + grep -qE "^APPLY-FINISH role=1 sa=1 crb=1 admin=0 jobname=1 migration=1 image=1 serviceaccount=1 rotate=1 platform=1 deployments=1$" "$FAKE_CMDLOG" + + # The seed refuses the reserved names, keeps backup as a platform key and + # adds the valuesFrom entries ahead of the switch. + grep -qE "^CREDMIGRATE seed .*--reserved-user backup --reserved-user default --reserved-user clickhouse_operator .*--values-path _accounts .*--platform-key backup" "$FAKE_CMDLOG" + + # The seed holds the releases until the new cozystack-controller and + # cozystack-api run: both old ones drop the account valuesFrom entries. + grep -qE "^CREDMIGRATE seed .*--hold-until-rollout cozy-system/cozystack-controller --hold-until-rollout cozy-system/cozystack-api$" "$FAKE_CMDLOG" + + # The Job owns its ServiceAccount, so the cluster-admin identity is collected + # with the Job and does not stand indefinitely. + grep -qE "^PATCH-SA-OWNER owner=1$" "$FAKE_CMDLOG" + + # A stale Job from an earlier run is deleted before the apply, so a rerun on a + # newer image does not fault on the immutable pod template; the ownership is + # set after the Job exists; and only then, after the Job is created and owned, + # the version is stamped. A stamp before the Job would mark the migration done + # with no finisher. + _del=$(cmdlog_line "^DELETE-JOB$") + _apply=$(cmdlog_line "^APPLY-FINISH ") + _own=$(cmdlog_line "^PATCH-SA-OWNER ") + _stamp=$(cmdlog_line "^STAMP 66$") + [ -n "$_del" ] && [ "$_del" -lt "$_apply" ] + [ -n "$_own" ] && [ "$_apply" -lt "$_own" ] + [ -n "$_stamp" ] && [ "$_own" -lt "$_stamp" ] + rm -rf "$WORK" +} + +@test "a pod whose image cannot be read, as a failed get, stops before the Job and the stamp" { + prep + export FAKE_GETPOD_FAIL="the server could not find the requested resource" + rc=0 + run_migration 65 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + grep -qE "^CREDMIGRATE seed --migration 65 " "$FAKE_CMDLOG" + if grep -qE "^APPLY-FINISH" "$FAKE_CMDLOG"; then echo "created the Job after a failed image read" >&2; return 1; fi + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after a failed image read" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "a failed seed stops before the Job and before stamping" { + prep + export FAKE_SEED_FAIL="apiserver is unavailable" + rc=0 + run_migration 65 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + if grep -qE "^APPLY-FINISH" "$FAKE_CMDLOG"; then echo "created the Job after a failed seed" >&2; return 1; fi + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after a failed seed" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "a pod whose image cannot be read stops after the seed, before the Job and the stamp" { + prep + export FAKE_IMAGE_EMPTY=1 + rc=0 + run_migration 65 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + grep -qE "^CREDMIGRATE seed --migration 65 " "$FAKE_CMDLOG" + if grep -qE "^APPLY-FINISH" "$FAKE_CMDLOG"; then echo "created the Job with no image to run" >&2; return 1; fi + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped with no image to run" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "a failed apply of the Job stops before stamping" { + prep + export FAKE_APPLY_FAIL="admission webhook denied the request" + rc=0 + run_migration 65 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after the Job failed to apply" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "a Job whose uid cannot be read stops before owning the SA and before stamping" { + prep + export FAKE_GETJOB_FAIL="the server was unable to return a response" + rc=0 + run_migration 65 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + if grep -qE "^PATCH-SA-OWNER" "$FAKE_CMDLOG"; then echo "patched ownership with no uid" >&2; return 1; fi + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped without owning the SA" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "an empty Job uid stops before owning the SA and before stamping" { + prep + export FAKE_JOBUID_EMPTY=1 + rc=0 + run_migration 65 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + if grep -qE "^PATCH-SA-OWNER" "$FAKE_CMDLOG"; then echo "patched ownership with an empty uid" >&2; return 1; fi + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped with an empty uid" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "a failed ownership patch stops before stamping" { + prep + export FAKE_PATCH_FAIL="serviceaccounts \"cozystack-credentials-migration-65\" not found" + rc=0 + run_migration 65 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after the ownership patch failed" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "a seed that fails to hold a release stops before the Job and the stamp" { + prep + # A release suspended with no finish Job to resume it would stay frozen, + # and one left running would switch under the old controller. + export FAKE_SEED_FAIL="tenant-a/clickhouse-x: hold until the new components run: the object has been modified" + rc=0 + run_migration 65 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + grep -qF "hold until the new components run" "$WORK/out" + if grep -qE "^APPLY-FINISH" "$FAKE_CMDLOG"; then echo "created the Job after a failed hold" >&2; return 1; fi + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after a failed hold" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "the hold waits for the components in the hook's own namespace" { + prep + export NAMESPACE=cozy-platform + rc=0 + run_migration 65 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -eq 0 ] + grep -qE "^CREDMIGRATE seed .*--hold-until-rollout cozy-platform/cozystack-controller --hold-until-rollout cozy-platform/cozystack-api$" "$FAKE_CMDLOG" + rm -rf "$WORK" +} diff --git a/hack/testdata/migration-65-clickhouse-credentials/credentials-migrate b/hack/testdata/migration-65-clickhouse-credentials/credentials-migrate new file mode 100755 index 000000000..340800b9d --- /dev/null +++ b/hack/testdata/migration-65-clickhouse-credentials/credentials-migrate @@ -0,0 +1,22 @@ +#!/bin/sh +# Fake credentials-migrate for hack/migration-65-clickhouse-credentials.bats. +# Migration 65 runs `credentials-migrate seed` in the hook; the real binary is +# exercised by cmd/credentials-migrate's Go tests, so this fake only records the +# call and fails on demand to pin the hook's fail-closed behaviour. +# +# FAKE_CMDLOG file to append a one-line record of each call to +# FAKE_SEED_FAIL non-empty => `seed` exits 1 with this stderr +set -u + +[ -n "${FAKE_CMDLOG:-}" ] && printf 'CREDMIGRATE %s\n' "$*" >> "$FAKE_CMDLOG" + +case "${1:-}" in + seed) + if [ -n "${FAKE_SEED_FAIL:-}" ]; then + printf '%s\n' "$FAKE_SEED_FAIL" >&2 + exit 1 + fi + exit 0 + ;; +esac +exit 0 diff --git a/hack/testdata/migration-65-clickhouse-credentials/kubectl b/hack/testdata/migration-65-clickhouse-credentials/kubectl new file mode 100755 index 000000000..92ac19db7 --- /dev/null +++ b/hack/testdata/migration-65-clickhouse-credentials/kubectl @@ -0,0 +1,114 @@ +#!/bin/sh +# Fake kubectl for hack/migration-65-clickhouse-credentials.bats, modelled on +# hack/testdata/migration-58-http-cache/kubectl. It serves only the calls +# migration 65 and lib/cozystack-version.sh make, and logs each one to +# $FAKE_CMDLOG. +# +# Migration 65 reads its own pod's image, applies the finish Job (with its +# ServiceAccount and ClusterRoleBinding), and stamps the version. The Job +# manifest and the version stamp both arrive as `apply --filename -`, so this +# fake reads stdin and branches on the manifest's kind. +# +# FAKE_CMDLOG file to append a one-line record of each call to +# FAKE_IMAGE image the `get pod` call returns (default a test ref) +# FAKE_IMAGE_EMPTY non-empty => `get pod` returns an empty image +# FAKE_GETPOD_FAIL non-empty => `get pod` exits 1 with this stderr +# FAKE_APPLY_FAIL non-empty => applying the Job exits 1 with this stderr +set -u + +log() { [ -n "${FAKE_CMDLOG:-}" ] && printf '%s\n' "$*" >> "$FAKE_CMDLOG"; } +log "KUBECTL $*" + +args="$*" +IMAGE="${FAKE_IMAGE:-registry.example.org/cozystack/cozystack:v1.7.0}" + +case "$args" in + *"get pod"*jsonpath*) + if [ -n "${FAKE_GETPOD_FAIL:-}" ]; then + printf '%s\n' "$FAKE_GETPOD_FAIL" >&2 + exit 1 + fi + [ -n "${FAKE_IMAGE_EMPTY:-}" ] || printf '%s' "$IMAGE" + exit 0 + ;; + + *"delete job cozystack-credentials-migration-65"*) + # The hook deletes a Job left by an earlier run before recreating it. + log "DELETE-JOB" + exit 0 + ;; + + *"delete serviceaccount cozystack-credentials-migration-65"*) + # The hook deletes a ServiceAccount left owned by the Job it just deleted, + # so the apply recreates a fresh, owner-less one. + log "DELETE-SA" + exit 0 + ;; + + *"get job cozystack-credentials-migration-65"*jsonpath*) + # The hook reads the Job's uid to own its ServiceAccount. + if [ -n "${FAKE_GETJOB_FAIL:-}" ]; then + printf '%s\n' "$FAKE_GETJOB_FAIL" >&2 + exit 1 + fi + [ -n "${FAKE_JOBUID_EMPTY:-}" ] || printf '%s' "11111111-2222-3333-4444-555555555555" + exit 0 + ;; + + *"patch serviceaccount cozystack-credentials-migration-65"*) + # The ownerReference tying the ServiceAccount to the Job. + if [ -n "${FAKE_PATCH_FAIL:-}" ]; then + printf '%s\n' "$FAKE_PATCH_FAIL" >&2 + exit 1 + fi + owner=$(printf '%s' "$args" | grep -c 'cozystack-credentials-migration-65') + log "PATCH-SA-OWNER owner=$owner" + exit 0 + ;; + + *"apply --filename -"*) + manifest=$(cat) + case "$manifest" in + *"kind: ConfigMap"*) + v=$(printf '%s\n' "$manifest" | sed -n 's/^ version: "\{0,1\}\([0-9]\{1,\}\)"\{0,1\}$/\1/p' | head -1) + log "STAMP ${v:-unknown}" + exit 0 + ;; + *"kind: Job"*) + if [ -n "${FAKE_APPLY_FAIL:-}" ]; then + printf '%s\n' "$FAKE_APPLY_FAIL" >&2 + exit 1 + fi + # Record the fields the Job must carry, so a copy that drops the + # ServiceAccount, names the wrong migration, or renders the wrong image + # is caught. + role=$(printf '%s\n' "$manifest" | grep -c '^kind: ClusterRole$') + sa=$(printf '%s\n' "$manifest" | grep -c '^kind: ServiceAccount$') + crb=$(printf '%s\n' "$manifest" | grep -c '^kind: ClusterRoleBinding$') + # The binding must grant the least-privilege role, never cluster-admin. + admin=$(printf '%s\n' "$manifest" | grep -c 'cluster-admin') + jobname=$(printf "%s\n" "$manifest" | sed -n "/^kind: Job$/,/^spec:$/p" | grep -c "^ name: cozystack-credentials-migration-65$") + mig=$(printf '%s\n' "$manifest" | grep -c -- '--migration=65') + img=$(printf '%s\n' "$manifest" | grep -c "^ image: ${IMAGE}$") + sacc=$(printf '%s\n' "$manifest" | grep -c '^ serviceAccountName: cozystack-credentials-migration-65$') + # The Job keeps backup as a platform key and rotates it, refuses the + # reserved names and carries the values path. + rotate=$(printf '%s\n' "$manifest" | grep -c -- '--rotate-key=backup') + platform=$(printf '%s\n' "$manifest" | grep -c -- '--platform-key=backup') + # It reads Deployments to resume the held releases after their rollout. + deploy=$(printf '%s\n' "$manifest" | grep -c '^ resources: \["deployments"\]$') + log "APPLY-FINISH role=$role sa=$sa crb=$crb admin=$admin jobname=$jobname migration=$mig image=$img serviceaccount=$sacc rotate=$rotate platform=$platform deployments=$deploy" + exit 0 + ;; + *) + log "APPLY-UNKNOWN" + printf 'fake kubectl: unmodelled apply\n' >&2 + exit 1 + ;; + esac + ;; +esac + +log "UNHANDLED $args" +printf 'fake kubectl: unmodelled call: %s\n' "$args" >&2 +exit 1 diff --git a/packages/apps/clickhouse/README.md b/packages/apps/clickhouse/README.md index a74c91b98..9a67e8747 100644 --- a/packages/apps/clickhouse/README.md +++ b/packages/apps/clickhouse/README.md @@ -123,13 +123,12 @@ chart-emitted CronJob renders only when `backup.schedule` is non-empty. ### Application-specific parameters -| Name | Description | Type | Value | -| ---------------------- | ------------------------------------------------------------- | ------------------- | ------- | -| `logStorageSize` | Size of Persistent Volume for logs. | `quantity` | `2Gi` | -| `logTTL` | TTL (expiration time) for `query_log` and `query_thread_log`. | `int` | `15` | -| `users` | Users configuration map. | `map[string]object` | `{}` | -| `users[name].password` | Password for the user. | `string` | `""` | -| `users[name].readonly` | User is readonly (default: false). | `bool` | `false` | +| Name | Description | Type | Value | +| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ------- | +| `logStorageSize` | Size of Persistent Volume for logs. | `quantity` | `2Gi` | +| `logTTL` | TTL (expiration time) for `query_log` and `query_thread_log`. | `int` | `15` | +| `users` | Users configuration map. Passwords are issued through the Cozystack credentials API: a mint on the user's `Credential` (`core.cozystack.io`) returns a new password once and stores only its SHA-256, and a revoke retires the password without issuing one. A user can log in once a password has been minted, after the release has upgraded with it. The names `backup`, `default` and `clickhouse_operator` are reserved for platform accounts. A `password` key here is ignored. | `map[string]object` | `{}` | +| `users[name].readonly` | User is readonly (default: false). | `bool` | `false` | ### Backup parameters diff --git a/packages/apps/clickhouse/templates/_accounts.tpl b/packages/apps/clickhouse/templates/_accounts.tpl new file mode 100644 index 000000000..6572e7248 --- /dev/null +++ b/packages/apps/clickhouse/templates/_accounts.tpl @@ -0,0 +1,48 @@ +{{/* + Account naming, which must match pkg/credentials/account.MapName: the + template is . and its Secret ..account, + where is the user name lowercased with every character outside + [a-z0-9-] replaced by "-". +*/}} +{{- define "clickhouse.accountName" -}} +{{- regexReplaceAll "[^a-z0-9-]" (lower .) "-" -}} +{{- end -}} + +{{/* + The stored SHA-256 of a user's password, which the HelmRelease pulls from + the account Secret into _accounts.u through the + valuesFrom entry cozystack-controller adds for the template. Empty until the + Secret exists, and for anything but a SHA-256 hex, so a value in another + format leaves the account out rather than giving the engine a broken one. +*/}} +{{- define "clickhouse.accountVerifier" -}} +{{- $root := index . 0 -}} +{{- $user := index . 1 -}} +{{- $v := get ($root.Values._accounts | default dict) (printf "u%s" (sha256sum $user)) | toString | trim | lower -}} +{{- if regexMatch "^[0-9a-f]{64}$" $v -}} +{{- $v -}} +{{- end -}} +{{- end -}} + +{{/* + Refusals for user names. backup is the platform account the backup jobs log + in with, default is the account the replicas talk to each other with, and + clickhouse_operator the one the operator logs in with: a tenant account + under any of them would take over or expose a platform login. +*/}} +{{- define "clickhouse.accountsGuard" -}} +{{- $seen := dict -}} +{{- range $user, $_ := .Values.users -}} + {{- if has $user (list "backup" "default" "clickhouse_operator") -}} + {{- fail (printf "user %q is reserved: backup, default and clickhouse_operator are platform accounts; rename the user" $user) -}} + {{- end -}} + {{- $mapped := include "clickhouse.accountName" $user -}} + {{- if or (gt (len $mapped) 63) (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $mapped)) -}} + {{- fail (printf "user %q maps to the account name %q, which must be at most 63 characters and start and end with a letter or a digit; rename the user" $user $mapped) -}} + {{- end -}} + {{- with index $seen $mapped -}} + {{- fail (printf "users %q and %q both map to the account name %q; rename one of them" . $user $mapped) -}} + {{- end -}} + {{- $_ := set $seen $mapped $user -}} +{{- end -}} +{{- end -}} diff --git a/packages/apps/clickhouse/templates/clickhouse.yaml b/packages/apps/clickhouse/templates/clickhouse.yaml index b9badef4b..05cb9e14c 100644 --- a/packages/apps/clickhouse/templates/clickhouse.yaml +++ b/packages/apps/clickhouse/templates/clickhouse.yaml @@ -1,31 +1,32 @@ {{- $clusterDomain := (index .Values._cluster "cluster-domain") | default "cozy.local" }} +{{- include "clickhouse.accountsGuard" $ }} +{{- /* + -credentials holds only the platform's backup account, which the + backup sidecar and the legacy CronJob log in with. It stays chart-generated + and is kept from tenants: no ApplicationDefinition selects it, no Role + grants it, and the label keeps the lineage webhook from marking it tenant + visible. Tenant accounts live in their account Secrets (credentials.yaml). +*/}} {{- $existingSecret := lookup "v1" "Secret" .Release.Namespace (printf "%s-credentials" .Release.Name) }} -{{- $passwords := dict }} -{{- $users := .Values.users }} -{{- $_ := set $users "backup" dict }} - +{{- $backupPassword := "" }} {{- with (index $existingSecret "data") }} - {{- range $k, $v := . }} - {{- $_ := set $passwords $k (b64dec $v) }} + {{- with .backup }} + {{- $backupPassword = b64dec . }} {{- end }} {{- end }} - -{{- range $user, $u := $users }} - {{- if $u.password }} - {{- $_ := set $passwords $user $u.password }} - {{- else if not (index $passwords $user) }} - {{- $_ := set $passwords $user (randAlphaNum 16) }} - {{- end }} +{{- if not $backupPassword }} + {{- $backupPassword = randAlphaNum 16 }} {{- end }} +{{- $backupRotated := dig "metadata" "annotations" "credentials.cozystack.io/rotated" "" ($existingSecret | default dict) }} apiVersion: v1 kind: Secret metadata: name: {{ .Release.Name }}-credentials + labels: + internal.cozystack.io/tenantresource: "false" stringData: - {{- range $user, $u := .Values.users }} - {{ quote $user }}: {{ quote (index $passwords $user) }} - {{- end }} + backup: {{ quote $backupPassword }} --- apiVersion: "clickhouse.altinity.com/v1" @@ -40,14 +41,23 @@ spec: podTemplate: clickhouse-per-host serviceTemplate: svc-template configuration: - {{- with $users }} users: - {{- range $name, $u := . }} - {{ $name }}/password_sha256_hex: {{ sha256sum (index $passwords $name) }} + {{- /* + A tenant account with no verifier in the values yet, as before + cozystack-controller has seeded its Secret, is left out: without a + password the operator would give it the password "default". + */}} + {{- range $name, $u := .Values.users }} + {{- $verifier := include "clickhouse.accountVerifier" (list $ $name) }} + {{- if $verifier }} + {{ $name }}/password_sha256_hex: {{ $verifier | quote }} {{ $name }}/profile: {{ ternary "readonly" "default" (index $u "readonly" | default false) }} {{ $name }}/networks/ip: ["::/0"] {{- end }} - {{- end }} + {{- end }} + backup/password_sha256_hex: {{ sha256sum $backupPassword | quote }} + backup/profile: default + backup/networks/ip: ["::/0"] files: config.d/z_log_disable.xml: | @@ -128,6 +138,14 @@ spec: metadata: labels: app.kubernetes.io/instance: {{ .Release.Name }} + {{- if and .Values.backup.enabled $backupRotated }} + {{- /* + The backup sidecar reads the backup password from its environment + at start, so a rotation of it restarts the pods once. + */}} + annotations: + credentials.cozystack.io/backup-rotated: {{ $backupRotated | quote }} + {{- end }} spec: affinity: podAntiAffinity: diff --git a/packages/apps/clickhouse/templates/credentials.yaml b/packages/apps/clickhouse/templates/credentials.yaml new file mode 100644 index 000000000..5d1007a0a --- /dev/null +++ b/packages/apps/clickhouse/templates/credentials.yaml @@ -0,0 +1,25 @@ +{{- /* + One CredentialTemplate per user: the account the Cozystack credentials API + mints and revokes through. The operator reads no Secret, so the template + asks for a valuesPath: cozystack-controller adds a valuesFrom entry that + pulls the account Secret's SHA-256 into the release values, and the label + makes Flux upgrade the release when a mint or a revoke changes the Secret. + clickhouse.yaml renders the verifier into the ClickHouseInstallation. The + chart renders no tenant password. +*/ -}} +{{- include "clickhouse.accountsGuard" $ }} +{{- range $user, $_ := .Values.users }} +--- +apiVersion: cozystack.io/v1alpha1 +kind: CredentialTemplate +metadata: + name: {{ printf "%s.%s" $.Release.Name (include "clickhouse.accountName" $user) | quote }} +spec: + username: {{ $user | quote }} + format: + name: sha256 + secret: + labels: + reconcile.fluxcd.io/watch: Enabled + valuesPath: _accounts +{{- end }} diff --git a/packages/apps/clickhouse/tests/credential_templates_test.yaml b/packages/apps/clickhouse/tests/credential_templates_test.yaml new file mode 100644 index 000000000..86ffb8526 --- /dev/null +++ b/packages/apps/clickhouse/tests/credential_templates_test.yaml @@ -0,0 +1,113 @@ +suite: one CredentialTemplate per user, with the verifier delivered through values + +# The template is the account the credentials API mints through. The operator +# reads no Secret, so the template asks for a valuesPath, and the chart reads +# the stored SHA-256 back from _accounts.u. + +templates: + - templates/credentials.yaml + +release: + name: ch-test + namespace: tenant-test + +set: + _cluster: {} + +tests: + - it: renders nothing without users + asserts: + - hasDocuments: + count: 0 + + - it: renders a template per user, named for the account Secret's mapping + set: + users: + web: {} + Bob.Smith: + readonly: true + asserts: + - hasDocuments: + count: 2 + - isKind: + of: CredentialTemplate + - equal: + path: apiVersion + value: cozystack.io/v1alpha1 + - equal: + path: metadata.name + value: ch-test.bob-smith + documentIndex: 0 + - equal: + path: spec.username + value: Bob.Smith + documentIndex: 0 + - equal: + path: metadata.name + value: ch-test.web + documentIndex: 1 + + - it: stores SHA-256 verifiers, asks for the Flux watch label and a values path + set: + users: + web: {} + asserts: + - equal: + path: spec.format.name + value: sha256 + - equal: + path: spec.secret.labels + value: + reconcile.fluxcd.io/watch: Enabled + - equal: + path: spec.valuesPath + value: _accounts + + - it: refuses two users that map to one account + set: + users: + web: {} + Web: {} + asserts: + - failedTemplate: + errorPattern: map to + + - it: refuses a user whose name maps to no valid account name + set: + users: + "-web": {} + asserts: + - failedTemplate: + errorPattern: start and end with a letter or a digit + + - it: refuses a user whose account name is longer than a DNS label + set: + users: + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: {} + asserts: + - failedTemplate: + errorPattern: at most 63 characters + + - it: refuses the backup platform account as a tenant user + set: + users: + backup: {} + asserts: + - failedTemplate: + errorPattern: reserved + + - it: refuses the default user + set: + users: + default: {} + asserts: + - failedTemplate: + errorPattern: reserved + + - it: refuses the operator's user + set: + users: + clickhouse_operator: {} + asserts: + - failedTemplate: + errorPattern: reserved diff --git a/packages/apps/clickhouse/tests/no_tenant_password_test.yaml b/packages/apps/clickhouse/tests/no_tenant_password_test.yaml new file mode 100644 index 000000000..c2a37b63e --- /dev/null +++ b/packages/apps/clickhouse/tests/no_tenant_password_test.yaml @@ -0,0 +1,153 @@ +suite: tenant passwords stay out of the chart; backup stays a hidden platform account + +# The ClickHouseInstallation gets each tenant user's SHA-256 from the values +# the HelmRelease pulls from the account Secret, and leaves out a user with no +# verifier yet, since the operator would give it the password "default". +# -credentials keeps only the platform's backup account and is never +# tenant visible. + +templates: + - templates/clickhouse.yaml + +release: + name: ch-test + namespace: tenant-test + +set: + _cluster: {} + +tests: + - it: renders the verifier a user has in values and leaves out one without + template: templates/clickhouse.yaml + documentSelector: + path: kind + value: ClickHouseInstallation + set: + users: + web: + readonly: true + reports: {} + _accounts: + u4b5e57f6eb2f42b9039b3d1e13929295f231749c510cbe341cd68036d9af97e2: ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb + asserts: + - equal: + path: spec.configuration.users["web/password_sha256_hex"] + value: ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb + - equal: + path: spec.configuration.users["web/profile"] + value: readonly + - notExists: + path: spec.configuration.users["reports/password_sha256_hex"] + - notExists: + path: spec.configuration.users["reports/profile"] + - notExists: + path: spec.configuration.users["reports/networks/ip"] + - exists: + path: spec.configuration.users["backup/password_sha256_hex"] + + - it: ignores a leftover users..password + template: templates/clickhouse.yaml + set: + users: + web: + password: leftover-plaintext + asserts: + - notExists: + path: spec.configuration.users["web/password_sha256_hex"] + documentSelector: + path: kind + value: ClickHouseInstallation + - notExists: + path: stringData.web + documentSelector: + path: kind + value: Secret + + - it: leaves out a value that is not a SHA-256 hex + template: templates/clickhouse.yaml + documentSelector: + path: kind + value: ClickHouseInstallation + set: + users: + web: {} + _accounts: + u4b5e57f6eb2f42b9039b3d1e13929295f231749c510cbe341cd68036d9af97e2: "*0123456789ABCDEF0123456789ABCDEF01234567" + asserts: + - notExists: + path: spec.configuration.users["web/password_sha256_hex"] + + - it: keeps only backup in -credentials, labelled not tenant visible + template: templates/clickhouse.yaml + documentSelector: + path: kind + value: Secret + set: + users: + web: {} + asserts: + - equal: + path: metadata.name + value: ch-test-credentials + - equal: + path: metadata.labels["internal.cozystack.io/tenantresource"] + value: "false" + - exists: + path: stringData.backup + - notExists: + path: stringData.web + + - it: preserves the backup password and keys a sidecar restart on its rotation + template: templates/clickhouse.yaml + set: + backup: + enabled: true + kubernetesProvider: + scheme: + "v1/Secret": + gvr: + version: "v1" + resource: "secrets" + namespaced: true + objects: + - kind: Secret + apiVersion: v1 + metadata: + name: ch-test-credentials + namespace: tenant-test + annotations: + credentials.cozystack.io/rotated: "2026-11-21T00:00:00Z" + data: + # base64 of "platform-backup" + backup: cGxhdGZvcm0tYmFja3Vw + asserts: + - equal: + path: stringData.backup + value: platform-backup + documentSelector: + path: kind + value: Secret + - equal: + path: spec.configuration.users["backup/password_sha256_hex"] + value: dde39b6ad76cd9704ad0f6c554950b313995547e4df6513f909ed693d5c73450 + documentSelector: + path: kind + value: ClickHouseInstallation + - equal: + path: spec.templates.podTemplates[0].metadata.annotations["credentials.cozystack.io/backup-rotated"] + value: "2026-11-21T00:00:00Z" + documentSelector: + path: kind + value: ClickHouseInstallation + + - it: adds no restart annotation before a rotation + template: templates/clickhouse.yaml + documentSelector: + path: kind + value: ClickHouseInstallation + set: + backup: + enabled: true + asserts: + - notExists: + path: spec.templates.podTemplates[0].metadata.annotations diff --git a/packages/apps/clickhouse/values.schema.json b/packages/apps/clickhouse/values.schema.json index 46f84a497..6fe521ed4 100644 --- a/packages/apps/clickhouse/values.schema.json +++ b/packages/apps/clickhouse/values.schema.json @@ -157,16 +157,12 @@ "default": 15 }, "users": { - "description": "Users configuration map.", + "description": "Users configuration map. Passwords are issued through the Cozystack credentials API: a mint on the user's `Credential` (`core.cozystack.io`) returns a new password once and stores only its SHA-256, and a revoke retires the password without issuing one. A user can log in once a password has been minted, after the release has upgraded with it. The names `backup`, `default` and `clickhouse_operator` are reserved for platform accounts. A `password` key here is ignored.", "type": "object", "default": {}, "additionalProperties": { "type": "object", "properties": { - "password": { - "description": "Password for the user.", - "type": "string" - }, "readonly": { "description": "User is readonly (default: false).", "type": "boolean" diff --git a/packages/apps/clickhouse/values.yaml b/packages/apps/clickhouse/values.yaml index 07891079b..e4e749df9 100644 --- a/packages/apps/clickhouse/values.yaml +++ b/packages/apps/clickhouse/values.yaml @@ -94,18 +94,15 @@ logStorageSize: 2Gi logTTL: 15 ## @typedef {struct} User - User configuration. -## @field {string} [password] - Password for the user. ## @field {bool} [readonly] - User is readonly (default: false). -## @param {map[string]User} users - Users configuration map. +## @param {map[string]User} users - Users configuration map. Passwords are issued through the Cozystack credentials API: a mint on the user's `Credential` (`core.cozystack.io`) returns a new password once and stores only its SHA-256, and a revoke retires the password without issuing one. A user can log in once a password has been minted, after the release has upgraded with it. The names `backup`, `default` and `clickhouse_operator` are reserved for platform accounts. A `password` key here is ignored. users: {} ## Example: ## users: -## user1: -## password: strongpassword +## user1: {} ## user2: ## readonly: true -## password: hackme ## ## diff --git a/packages/core/platform/images/migrations/migrations/65 b/packages/core/platform/images/migrations/migrations/65 new file mode 100755 index 000000000..704c3b97b --- /dev/null +++ b/packages/core/platform/images/migrations/migrations/65 @@ -0,0 +1,203 @@ +#!/bin/sh +# Migration 65 --> 66 +# Convert ClickHouse accounts to platform-minted credentials, first part. +# +# The converted clickhouse chart renders a CredentialTemplate per user and +# takes each user's SHA-256 from the release values, which the HelmRelease +# pulls from the template's account Secret through a valuesFrom entry; +# cozystack-controller seeds those Secrets with a random password only on a +# release marked for seeding. This hook runs before any component chart +# changes version and writes the Secrets, unowned, for every existing +# ClickHouse release from the passwords in -credentials, and adds the +# valuesFrom entries itself: the controller adds them only once the templates +# exist, and without them the converted chart's first render would leave every +# user out of the ClickHouseInstallation, locking clients out until the next +# upgrade. The old chart ignores those values. A release whose every account +# got its Secret is marked for seeding, so users added later are seeded too. +# A release with a user named backup, default or clickhouse_operator, which +# the converted chart refuses, is left out. +# +# The hook also suspends every ClickHouse release until cozystack-controller +# and cozystack-api run their new revision. Every application chart switches +# the moment the platform chart moves the packages source, while those two +# roll out later, and both old ones rebuild a release's valuesFrom without +# the account entries: the controller on any ApplicationDefinition change, +# the API on any tenant write. A converted chart rendered in between leaves +# every user out of the ClickHouseInstallation. Neither touches +# spec.suspend, so the finish Job resumes the releases, with their entries +# put back, once both Deployments have rolled out. +# +# The second part is the cozystack-credentials-migration-65 Job, which waits +# per release for its chart to switch, strips leftover users.*.password from +# the values, removes the tenant keys from -credentials while keeping +# the platform's backup password there, and rotates that password once, since +# tenants could read it: with the release suspended it writes a new value and +# then forces an upgrade, which applies its hash and restarts the pods of a +# release with backups enabled once, for the backup sidecar. The hook creates +# that Job directly rather than rendering it from the platform chart, for the +# reasons migration 64 gives, and deletes and recreates it on a rerun. +# +# The Job and its ServiceAccount, ClusterRole and ClusterRoleBinding are all +# named cozystack-credentials-migration-65; the RBAC is least-privilege, not +# cluster-admin: finish needs only CRUD on Secrets, get/list/patch on +# HelmReleases (the rotation suspends, resumes and annotates them), create on +# Events, its state ConfigMap, and get on Deployments to see the rollout it +# resumes the releases after. The ServiceAccount, ClusterRole and +# ClusterRoleBinding carry this migration's number, so this hook never deletes +# or rebinds the identity migration 64's Job may still be running as. The +# ServiceAccount is owned by the Job, so the garbage collector removes it with +# the Job; the ClusterRoleBinding is left and grants to no subject that exists +# once the ServiceAccount is gone. While any release is left out, +# credentials-migrate labels its state ConfigMap +# credentials.cozystack.io/incomplete=true, which the +# CredentialsMigrationIncomplete alert fires on. To rerun it by hand, delete +# the Job and re-apply the manifest below. +# +# Fail-closed: migrations never re-run, so an error here stops the upgrade +# rather than stamping the version past a release that was not recorded. + +set -euo pipefail + +# shellcheck source=lib/cozystack-version.sh +. "$(dirname "$0")/lib/cozystack-version.sh" + +NAMESPACE="${NAMESPACE:-cozy-system}" + +credentials-migrate seed \ + --migration 65 \ + --kind ClickHouse \ + --format sha256 \ + --accounts-path users \ + --reserved-user backup \ + --reserved-user default \ + --reserved-user clickhouse_operator \ + --values-path _accounts \ + --platform-key backup \ + --label 'reconcile.fluxcd.io/watch=Enabled' \ + --hold-until-rollout "${NAMESPACE}/cozystack-controller" \ + --hold-until-rollout "${NAMESPACE}/cozystack-api" + +# The finish Job runs the same image as this hook, so a release and its +# conversion share the credentials-migrate build. Read it from this pod's own +# container by name rather than render it from values, which the hook does not +# carry, and rather than by position, which a webhook-injected container shifts. +image=$(kubectl get pod "$(hostname)" \ + --namespace "$NAMESPACE" \ + --output 'jsonpath={.spec.containers[?(@.name=="migration")].image}') +if [ -z "$image" ]; then + echo "cannot read this pod's image to run the finish Job" >&2 + exit 1 +fi + +# Delete any Job left by an earlier run of this hook: its pod template is +# immutable, so a rerun on a newer image would fault on apply. finish recovers +# its progress from the state ConfigMap, so recreating the Job loses nothing. +# Delete the ServiceAccount with it: an earlier run may have left it owned by +# the Job just deleted, and the apply below does not touch ownerReferences, so +# without this the garbage collector could remove the re-applied ServiceAccount +# out from under the ownerReference patch. A fresh, owner-less ServiceAccount is +# never collected before the patch names the new Job. +kubectl delete job cozystack-credentials-migration-65 \ + --namespace "$NAMESPACE" \ + --ignore-not-found +kubectl delete serviceaccount cozystack-credentials-migration-65 \ + --namespace "$NAMESPACE" \ + --ignore-not-found + +kubectl apply --filename - <&2 + exit 1 +fi +kubectl patch serviceaccount cozystack-credentials-migration-65 \ + --namespace "$NAMESPACE" \ + --type merge \ + --patch "{\"metadata\":{\"ownerReferences\":[{\"apiVersion\":\"batch/v1\",\"kind\":\"Job\",\"name\":\"cozystack-credentials-migration-65\",\"uid\":\"${job_uid}\"}]}}" + +stamp_cozystack_version 66 diff --git a/packages/core/platform/values.yaml b/packages/core/platform/values.yaml index 8bde66819..2d963cb2c 100644 --- a/packages/core/platform/values.yaml +++ b/packages/core/platform/values.yaml @@ -89,7 +89,7 @@ migrations: # refuses to advance past a migration file missing from the image (exit 1), so # a stale pin fails loudly rather than silently skipping the etcd adoption. image: ghcr.io/cozystack/cozystack/platform-migrations:v1.6.0@sha256:6777042e3e9c6bad76e7d96fb64baa115061975f39061cb3ede84e21d0e2213f - targetVersion: 65 + targetVersion: 66 # Adopt legacy etcd clusters onto the v1alpha2 operator WITHOUT the mandatory # pre-adoption safety snapshot (migration 50). Leave false unless migration 50 # has actually refused to proceed and you accept the risk: adoption rewires diff --git a/packages/system/clickhouse-rd/cozyrds/clickhouse.yaml b/packages/system/clickhouse-rd/cozyrds/clickhouse.yaml index fd23668d9..ed13761c4 100644 --- a/packages/system/clickhouse-rd/cozyrds/clickhouse.yaml +++ b/packages/system/clickhouse-rd/cozyrds/clickhouse.yaml @@ -8,7 +8,7 @@ spec: singular: clickhouse plural: clickhouses openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of ClickHouse replicas.","type":"integer","default":2},"shards":{"description":"Number of ClickHouse shards.","type":"integer","default":1},"resources":{"description":"Explicit CPU and memory configuration for each ClickHouse replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"version":{"description":"ClickHouse major.minor version to deploy. Applies to both the ClickHouse server and ClickHouse Keeper images. Downgrading to an older major is unsafe (ClickHouse cannot read data written by a newer server and Keeper snapshots are not backward compatible) — only increase this value.","type":"string","default":"v24.9","enum":["v25.8","v25.3","v24.9"]},"logStorageSize":{"description":"Size of Persistent Volume for logs.","default":"2Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"logTTL":{"description":"TTL (expiration time) for `query_log` and `query_thread_log`.","type":"integer","default":15},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user.","type":"string"},"readonly":{"description":"User is readonly (default: false).","type":"boolean"}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"cleanupStrategy":{"description":"Legacy. Restic retention policy passed to the legacy CronJob (`restic forget …`). Unused by the Altinity strategy.","type":"string","default":"--keep-last=3 --keep-daily=3 --keep-within-weekly=1m"},"enabled":{"description":"Enable backup integration. Materialises the chart-emitted `-backup-s3` Secret consumed by the Altinity backup strategy and, when `schedule` is non-empty, also renders the legacy chart-managed CronJob.","type":"boolean","default":false},"endpoint":{"description":"DEPRECATED. S3 endpoint URL for the legacy chart-emitted sidecar.","type":"string","default":""},"endpointCA":{"description":"CA bundle the sidecar trusts when the S3 endpoint's certificate is signed by a private CA (e.g. Cozystack's in-cluster SeaweedFS). Applies to both the per-tenant and the `useSystemBucket` flow, and to the `clickhouse-backup` sidecar only — the legacy `schedule` CronJob writes to S3 through restic and does not consume it, so a private-CA endpoint combined with `schedule` still fails TLS. Use the BackupClass flow for such an endpoint.","type":"object","default":{},"properties":{"key":{"description":"Key inside the Secret holding the PEM CA bundle. Defaults to `ca.crt`.","type":"string","default":"ca.crt"},"name":{"description":"Name of the Secret in the application namespace. Empty (default) mounts nothing and leaves the sidecar on the system trust store only.","type":"string","default":""}}},"resticPassword":{"description":"Legacy. Password for Restic backup encryption used by the legacy CronJob. Unused by the Altinity strategy.","type":"string","default":""},"s3AccessKey":{"description":"DEPRECATED. Tenants no longer supply S3 keys; the platform-managed Bucket Secret is the source of truth. Optional now so `useSystemBucket: true` tenants can omit it.","type":"string","default":""},"s3Bucket":{"description":"DEPRECATED. Optional; see `s3Region`.","type":"string","default":"s3.example.org/clickhouse-backups"},"s3CredentialsSecret":{"description":"DEPRECATED. Pre-existing Secret reference for the legacy chart-emitted sidecar. The platform flow projects `cozy-backups-creds` instead.","type":"object","default":{},"properties":{"accessKeyIDKey":{"description":"Key in the Secret holding the access key ID. Defaults to `accessKey`.","type":"string","default":""},"bucketKey":{"description":"Key in the Secret holding the bucket name. Defaults to `bucketName`.","type":"string","default":""},"endpointKey":{"description":"Key in the Secret holding the S3 endpoint URL. Defaults to `endpoint`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means the chart materialises `-backup-s3` from the legacy `s3*` fields.","type":"string","default":""},"regionKey":{"description":"Key in the Secret holding the S3 region. Defaults to `region`.","type":"string","default":""},"secretAccessKeyKey":{"description":"Key in the Secret holding the secret access key. Defaults to `secretKey`.","type":"string","default":""}}},"s3PathOverride":{"description":"DEPRECATED. Object-key prefix inside the legacy `s3Bucket`; the new platform flow scopes by namespace automatically.","type":"string","default":""},"s3Region":{"description":"DEPRECATED. Per-tenant S3 configuration is being phased out in favour of the platform-managed `cozy-default` BackupClass. Optional now so tenants on `useSystemBucket: true` can omit it.","type":"string","default":"us-east-1"},"s3SecretKey":{"description":"DEPRECATED. Optional; see `s3AccessKey`.","type":"string","default":""},"schedule":{"description":"Legacy. Cron schedule for the chart-emitted CronJob that runs the dump+restic backup. Empty (default) skips the legacy CronJob; recommended when a `BackupClass` + `Plan` from `backups.cozystack.io` already drives backup orchestration via the Altinity strategy.","type":"string","default":""},"useSystemBucket":{"description":"Opt-in: when true, the chart-emitted `-backup-s3` Secret is skipped and the `clickhouse-backup` sidecar reads bucket coordinates + S3 credentials from the platform-projected `cozy-backups-creds` Secret. `S3_PATH` is set to `/` for cross-tenant isolation. Use together with the platform `cozy-default` BackupClass — tenants do not need to fill any `s3*` field below.","type":"boolean","default":false}}},"clickhouseKeeper":{"description":"ClickHouse Keeper configuration.","type":"object","default":{},"properties":{"enabled":{"description":"Deploy ClickHouse Keeper for cluster coordination.","type":"boolean","default":true},"replicas":{"description":"Number of Keeper replicas.","type":"integer","default":3},"resourcesPreset":{"description":"Default sizing preset.","type":"string","default":"t1.micro","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"1Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of ClickHouse replicas.","type":"integer","default":2},"shards":{"description":"Number of ClickHouse shards.","type":"integer","default":1},"resources":{"description":"Explicit CPU and memory configuration for each ClickHouse replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.small","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"version":{"description":"ClickHouse major.minor version to deploy. Applies to both the ClickHouse server and ClickHouse Keeper images. Downgrading to an older major is unsafe (ClickHouse cannot read data written by a newer server and Keeper snapshots are not backward compatible) — only increase this value.","type":"string","default":"v24.9","enum":["v25.8","v25.3","v24.9"]},"logStorageSize":{"description":"Size of Persistent Volume for logs.","default":"2Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"logTTL":{"description":"TTL (expiration time) for `query_log` and `query_thread_log`.","type":"integer","default":15},"users":{"description":"Users configuration map. Passwords are issued through the Cozystack credentials API: a mint on the user's `Credential` (`core.cozystack.io`) returns a new password once and stores only its SHA-256, and a revoke retires the password without issuing one. A user can log in once a password has been minted, after the release has upgraded with it. The names `backup`, `default` and `clickhouse_operator` are reserved for platform accounts. A `password` key here is ignored.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"readonly":{"description":"User is readonly (default: false).","type":"boolean"}}}},"backup":{"description":"Backup configuration.","type":"object","default":{},"required":["enabled"],"properties":{"cleanupStrategy":{"description":"Legacy. Restic retention policy passed to the legacy CronJob (`restic forget …`). Unused by the Altinity strategy.","type":"string","default":"--keep-last=3 --keep-daily=3 --keep-within-weekly=1m"},"enabled":{"description":"Enable backup integration. Materialises the chart-emitted `-backup-s3` Secret consumed by the Altinity backup strategy and, when `schedule` is non-empty, also renders the legacy chart-managed CronJob.","type":"boolean","default":false},"endpoint":{"description":"DEPRECATED. S3 endpoint URL for the legacy chart-emitted sidecar.","type":"string","default":""},"endpointCA":{"description":"CA bundle the sidecar trusts when the S3 endpoint's certificate is signed by a private CA (e.g. Cozystack's in-cluster SeaweedFS). Applies to both the per-tenant and the `useSystemBucket` flow, and to the `clickhouse-backup` sidecar only — the legacy `schedule` CronJob writes to S3 through restic and does not consume it, so a private-CA endpoint combined with `schedule` still fails TLS. Use the BackupClass flow for such an endpoint.","type":"object","default":{},"properties":{"key":{"description":"Key inside the Secret holding the PEM CA bundle. Defaults to `ca.crt`.","type":"string","default":"ca.crt"},"name":{"description":"Name of the Secret in the application namespace. Empty (default) mounts nothing and leaves the sidecar on the system trust store only.","type":"string","default":""}}},"resticPassword":{"description":"Legacy. Password for Restic backup encryption used by the legacy CronJob. Unused by the Altinity strategy.","type":"string","default":""},"s3AccessKey":{"description":"DEPRECATED. Tenants no longer supply S3 keys; the platform-managed Bucket Secret is the source of truth. Optional now so `useSystemBucket: true` tenants can omit it.","type":"string","default":""},"s3Bucket":{"description":"DEPRECATED. Optional; see `s3Region`.","type":"string","default":"s3.example.org/clickhouse-backups"},"s3CredentialsSecret":{"description":"DEPRECATED. Pre-existing Secret reference for the legacy chart-emitted sidecar. The platform flow projects `cozy-backups-creds` instead.","type":"object","default":{},"properties":{"accessKeyIDKey":{"description":"Key in the Secret holding the access key ID. Defaults to `accessKey`.","type":"string","default":""},"bucketKey":{"description":"Key in the Secret holding the bucket name. Defaults to `bucketName`.","type":"string","default":""},"endpointKey":{"description":"Key in the Secret holding the S3 endpoint URL. Defaults to `endpoint`.","type":"string","default":""},"name":{"description":"Name of the Secret in the application namespace. Empty means the chart materialises `-backup-s3` from the legacy `s3*` fields.","type":"string","default":""},"regionKey":{"description":"Key in the Secret holding the S3 region. Defaults to `region`.","type":"string","default":""},"secretAccessKeyKey":{"description":"Key in the Secret holding the secret access key. Defaults to `secretKey`.","type":"string","default":""}}},"s3PathOverride":{"description":"DEPRECATED. Object-key prefix inside the legacy `s3Bucket`; the new platform flow scopes by namespace automatically.","type":"string","default":""},"s3Region":{"description":"DEPRECATED. Per-tenant S3 configuration is being phased out in favour of the platform-managed `cozy-default` BackupClass. Optional now so tenants on `useSystemBucket: true` can omit it.","type":"string","default":"us-east-1"},"s3SecretKey":{"description":"DEPRECATED. Optional; see `s3AccessKey`.","type":"string","default":""},"schedule":{"description":"Legacy. Cron schedule for the chart-emitted CronJob that runs the dump+restic backup. Empty (default) skips the legacy CronJob; recommended when a `BackupClass` + `Plan` from `backups.cozystack.io` already drives backup orchestration via the Altinity strategy.","type":"string","default":""},"useSystemBucket":{"description":"Opt-in: when true, the chart-emitted `-backup-s3` Secret is skipped and the `clickhouse-backup` sidecar reads bucket coordinates + S3 credentials from the platform-projected `cozy-backups-creds` Secret. `S3_PATH` is set to `/` for cross-tenant isolation. Use together with the platform `cozy-default` BackupClass — tenants do not need to fill any `s3*` field below.","type":"boolean","default":false}}},"clickhouseKeeper":{"description":"ClickHouse Keeper configuration.","type":"object","default":{},"properties":{"enabled":{"description":"Deploy ClickHouse Keeper for cluster coordination.","type":"boolean","default":true},"replicas":{"description":"Number of Keeper replicas.","type":"integer","default":3},"resourcesPreset":{"description":"Default sizing preset.","type":"string","default":"t1.micro","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"1Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63}}} release: prefix: clickhouse- labels: @@ -27,9 +27,7 @@ spec: keysOrder: [["apiVersion"], ["appVersion"], ["kind"], ["metadata"], ["metadata", "name"], ["spec", "replicas"], ["spec", "shards"], ["spec", "resources"], ["spec", "resourcesPreset"], ["spec", "size"], ["spec", "storageClass"], ["spec", "version"], ["spec", "logStorageSize"], ["spec", "logTTL"], ["spec", "users"], ["spec", "backup"], ["spec", "backup", "enabled"], ["spec", "backup", "useSystemBucket"], ["spec", "backup", "s3Region"], ["spec", "backup", "s3Bucket"], ["spec", "backup", "endpoint"], ["spec", "backup", "s3PathOverride"], ["spec", "backup", "schedule"], ["spec", "backup", "cleanupStrategy"], ["spec", "backup", "s3AccessKey"], ["spec", "backup", "s3SecretKey"], ["spec", "backup", "resticPassword"], ["spec", "backup", "s3CredentialsSecret"], ["spec", "backup", "s3CredentialsSecret", "name"], ["spec", "backup", "s3CredentialsSecret", "bucketKey"], ["spec", "backup", "s3CredentialsSecret", "endpointKey"], ["spec", "backup", "s3CredentialsSecret", "regionKey"], ["spec", "backup", "s3CredentialsSecret", "accessKeyIDKey"], ["spec", "backup", "s3CredentialsSecret", "secretAccessKeyKey"], ["spec", "backup", "endpointCA"], ["spec", "backup", "endpointCA", "name"], ["spec", "backup", "endpointCA", "key"], ["spec", "clickhouseKeeper"], ["spec", "clickhouseKeeper", "enabled"], ["spec", "clickhouseKeeper", "size"], ["spec", "clickhouseKeeper", "resourcesPreset"], ["spec", "clickhouseKeeper", "replicas"], ["spec", "schedulingClass"]] secrets: exclude: [] - include: - - resourceNames: - - clickhouse-{{ .name }}-credentials + include: [] services: exclude: [] include: diff --git a/pkg/registry/apps/application/rest.go b/pkg/registry/apps/application/rest.go index 3c7c96097..60bf004c7 100644 --- a/pkg/registry/apps/application/rest.go +++ b/pkg/registry/apps/application/rest.go @@ -2365,8 +2365,9 @@ func (r *REST) warnRemovedKubernetesFields(ctx context.Context, app *appsv1alpha // change it. Warn so an operator editing it is told it has no effect instead of // getting a silent 200, and where the password comes from now. var removedUserPasswordKinds = map[string]string{ - postgresKind: mintedPasswordWarning, - mariadbKind: "spec.users[%q].password is ignored: passwords are auto-generated into the -credentials Secret and cannot be set from values. Read the current password from that Secret; editing this field has no effect.", + postgresKind: mintedPasswordWarning, + mariadbKind: "spec.users[%q].password is ignored: passwords are auto-generated into the -credentials Secret and cannot be set from values. Read the current password from that Secret; editing this field has no effect.", + clickhouseKind: mintedPasswordWarning, } // mintedPasswordWarning is the warning of a kind whose user passwords the @@ -2375,8 +2376,9 @@ var removedUserPasswordKinds = map[string]string{ const mintedPasswordWarning = "spec.users[%q].password is ignored: passwords are issued through the credentials API and cannot be set from values. Mint a new password on the user's Credential (credentials.core.cozystack.io, mint subresource); editing this field has no effect." const ( - postgresKind = "Postgres" - mariadbKind = "MariaDB" + clickhouseKind = "ClickHouse" + postgresKind = "Postgres" + mariadbKind = "MariaDB" ) // warnRemovedUserPasswords emits a client-facing admission warning for every diff --git a/pkg/registry/apps/application/rest_warn_removed_password_callsite_test.go b/pkg/registry/apps/application/rest_warn_removed_password_callsite_test.go index 1c65a2b54..ddf5d87b0 100644 --- a/pkg/registry/apps/application/rest_warn_removed_password_callsite_test.go +++ b/pkg/registry/apps/application/rest_warn_removed_password_callsite_test.go @@ -164,6 +164,7 @@ func TestWarnRemovedUserPasswords(t *testing.T) { }{ {"postgres warns", postgresKind, rawWithPassword, true}, {"mariadb warns", mariadbKind, rawWithPassword, true}, + {"clickhouse warns", clickhouseKind, rawWithPassword, true}, {"other kind stays quiet", "Redis", rawWithPassword, false}, {"no password stays quiet", postgresKind, `{"users":{"app":{}}}`, false}, {"warns on a good user despite a non-object user", postgresKind, `{"users":{"good":{"password":"x"},"bad":"str"}}`, true}, @@ -195,7 +196,7 @@ func TestWarnRemovedUserPasswords(t *testing.T) { // mint on the user's Credential: its -credentials Secret holds no user // password a tenant can read, so naming it sends the reader to a dead end. func TestWarnRemovedUserPasswords_PointsAtMint(t *testing.T) { - for _, kind := range []string{postgresKind} { + for _, kind := range []string{postgresKind, clickhouseKind} { t.Run(kind, func(t *testing.T) { r := &REST{kindName: kind} app := &appsv1alpha1.Application{Spec: &apiextv1.JSON{Raw: []byte(`{"users":{"app":{"password":"hackme"}}}`)}}