From b4f2f13ce31d08ce8e01cba6c3c46f3028f6a09b Mon Sep 17 00:00:00 2001 From: IvanHunters Date: Mon, 23 Nov 2026 16:31:35 +0100 Subject: [PATCH 1/7] feat(credentials): tell whether a legacy password survives login PostgreSQL applies SASLprep to the presented password at login, and ALTER ROLE ... PASSWORD did the same when it stored the old verifier, so a SCRAM verifier built from the raw bytes of a legacy password silently fails to authenticate any password SASLprep changes, such as one carrying a soft hyphen. CarriesOver tells the conversion which passwords it may keep, so the rest are left to their first mint. pg_saslprep returns every all-ASCII input unchanged through its pg_is_ascii fast path before the prohibited-character step runs, so an all-ASCII password, ASCII controls included, carries over. Every format other than scram-sha-256 stores or hashes the raw bytes and always carries over. Assisted-by: LLM Signed-off-by: IvanHunters Signed-off-by: Andrei Kvapil --- pkg/credentials/format/format.go | 24 ++++++++++++++++++++++++ pkg/credentials/format/format_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/pkg/credentials/format/format.go b/pkg/credentials/format/format.go index 7f7592cac..4c445c0f8 100644 --- a/pkg/credentials/format/format.go +++ b/pkg/credentials/format/format.go @@ -57,6 +57,30 @@ func Known(name string) bool { return false } +// CarriesOver reports whether a legacy plaintext password encoded under name +// still authenticates that same plaintext at login. For scram-sha-256, +// PostgreSQL runs the password through SASLprep (RFC 4013) before it builds or +// checks a SCRAM verifier, but pg_saslprep returns an all-ASCII input unchanged +// through an ASCII fast path (pg_is_ascii) before its mapping and +// prohibited-character steps run, so every all-ASCII password, ASCII controls +// included, is hashed over its raw bytes at both ALTER ROLE and login, and a +// verifier built here from the same bytes matches. A password with any +// non-ASCII byte reaches SASLprep's mapping and may come out as different bytes +// (a soft hyphen U+00AD, say, maps to nothing), so it is re-minted rather than +// stored as a verifier that would silently fail login. Every other format +// hashes or stores the raw bytes, which authenticate as they are. +func CarriesOver(name, password string) bool { + if name != ScramSHA256 { + return true + } + for i := 0; i < len(password); i++ { + if password[i] > 0x7f { + return false + } + } + return true +} + // GeneratePassword draws PasswordLength characters uniformly from the // alphabet with crypto/rand. Rejection sampling keeps the draw unbiased: a // byte is accepted only below the largest multiple of the alphabet size. diff --git a/pkg/credentials/format/format_test.go b/pkg/credentials/format/format_test.go index 63d76d253..a526093a4 100644 --- a/pkg/credentials/format/format_test.go +++ b/pkg/credentials/format/format_test.go @@ -107,6 +107,32 @@ func TestEncodeFixedVectors(t *testing.T) { } } +func TestCarriesOver(t *testing.T) { + tests := []struct { + name, format, password string + want bool + }{ + // PostgreSQL returns an all-ASCII password unchanged through pg_saslprep's + // ASCII fast path, so every all-ASCII password, ASCII controls included, + // carries over; a non-ASCII byte reaches SASLprep's mapping and may be + // rewritten, so it does not. + {"scram printable ASCII", ScramSHA256, "pa55-word_ABC xyz", true}, + {"scram space is printable", ScramSHA256, "two words", true}, + {"scram ASCII control is still ASCII", ScramSHA256, "tab\there", true}, + {"scram soft hyphen rewritten by SASLprep", ScramSHA256, "I­X", false}, + {"scram non-ASCII", ScramSHA256, "café", false}, + // Other formats hash or store the raw bytes, which authenticate as is. + {"sha256 non-ASCII", SHA256, "café", true}, + {"mysql-native soft hyphen", MySQLNative, "I­X", true}, + {"plaintext non-ASCII", Plaintext, "café", true}, + } + for _, tt := range tests { + if got := CarriesOver(tt.format, tt.password); got != tt.want { + t.Errorf("%s: CarriesOver(%q, %q) = %v, want %v", tt.name, tt.format, tt.password, got, tt.want) + } + } +} + func TestEncodeUnknownFormat(t *testing.T) { if _, err := Encode("apr1", "x"); err == nil { t.Fatal("expected an error for an unknown format") From 780a3580832bd959e267a3ee7990aafebd468a2c Mon Sep 17 00:00:00 2001 From: Timofei Larkin Date: Mon, 23 Nov 2026 16:31:37 +0100 Subject: [PATCH 2/7] feat(credentials-migrate): convert accounts to minted credentials A converted chart reads each account's stored value from an account Secret the platform keeps, and nothing writes those Secrets for the applications that exist before the chart switches. Without a conversion every existing account would stop logging in at the switch. The command has two halves. seed runs from the platform's pre-upgrade hook, before any component chart changes version: it writes the account Secrets unowned, with the stored form of the password the tenant could read until now and origin Migrated, records each release's chart version, and marks a release for seeding only when every account got its Secret, so the CredentialTemplate controller never seeds a random password over one the release's clients still use. It takes the kind's format and accounts path from flags, because the hook runs before the converted chart renders any template. finish runs from a Job once the charts have switched: per release it waits for the converted chart to be Ready, strips any password left in the values and deletes the old source Secret. seed fails closed. Only a release whose accounts cannot be resolved from its values is left out; any other error fails the hook and the upgrade retries, since a left-out release whose source Helm then deletes would keep neither an account Secret nor the plaintext. finish holds a release recorded without a chart version rather than retiring it as soon as it renders, old chart included. A transient API or connection error is retried on the same release a few times. If it persists, the release is recorded for the incomplete alert but announced with CredentialsMigrationRetrying, a Normal event, since the Job's restart retries it; only an error no retry fixes records the Warning CredentialsMigrationSkipped "left this release out", which reads as a release that needs a person. While any release is left out, the state ConfigMap carries credentials.cozystack.io/incomplete=true. The stored form comes from the platform's own format package, so a migrated release and a mint store the same value. Co-authored-by: IvanHunters Co-authored-by: Andrei Kvapil Assisted-by: LLM Signed-off-by: Timofei Larkin Signed-off-by: Andrei Kvapil --- cmd/credentials-migrate/main.go | 623 ++++++++++++++++++++++++++ cmd/credentials-migrate/main_test.go | 458 +++++++++++++++++++ cmd/credentials-migrate/retry.go | 99 ++++ cmd/credentials-migrate/retry_test.go | 126 ++++++ 4 files changed, 1306 insertions(+) create mode 100644 cmd/credentials-migrate/main.go create mode 100644 cmd/credentials-migrate/main_test.go create mode 100644 cmd/credentials-migrate/retry.go create mode 100644 cmd/credentials-migrate/retry_test.go diff --git a/cmd/credentials-migrate/main.go b/cmd/credentials-migrate/main.go new file mode 100644 index 000000000..27e532cec --- /dev/null +++ b/cmd/credentials-migrate/main.go @@ -0,0 +1,623 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Command credentials-migrate converts the accounts of an application kind +// to platform-minted credentials: "seed" from the pre-upgrade hook, "finish" +// from a Job once the charts have switched. Both take the kind's format and +// accounts map from flags, because the hook runs before the converted chart +// renders the CredentialTemplates. See design-proposals/user-secrets-api in +// cozystack/community. +package main + +import ( + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "os" + "sort" + "strings" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" + "github.com/cozystack/cozystack/pkg/credentials/account" + "github.com/cozystack/cozystack/pkg/credentials/format" +) + +// errUnresolvable marks a release whose accounts cannot be resolved from its +// values: the one cause the hook leaves a release out for. Every other error +// fails the hook, so the upgrade retries instead of switching a release whose +// Secrets were not written. +var errUnresolvable = errors.New("accounts cannot be resolved") + +const ( + reasonSkipped = "CredentialsMigrationSkipped" + defaultActor = "system:serviceaccount:cozy-system:cozystack-migration-hook" + // incompleteLabel on the state ConfigMap is the durable signal behind the + // CredentialsMigrationIncomplete alert: the ConfigMap outlives the finish + // Job, so an alert keyed on this label fires until the conversion is + // finished, not only for the Job's TTL. "true" while any release is left + // out, "false" once none is. + incompleteLabel = "credentials.cozystack.io/incomplete" +) + +// options is the kind's credentials block and the migration's identity, as +// the hook and the Job pass them. +type options struct { + migration int + kind string + formatName string + accountsPath string + refuseFlags stringFlags + labels labelFlags + sourceSuffix string + platformKeys stringFlags + stateNamespace string + actor string + timeout time.Duration +} + +type labelFlags map[string]string + +func (l labelFlags) String() string { return fmt.Sprint(map[string]string(l)) } +func (l labelFlags) Set(v string) error { + k, val, ok := strings.Cut(v, "=") + if !ok || k == "" { + return fmt.Errorf("label %q is not key=value", v) + } + l[k] = val + return nil +} + +type stringFlags []string + +func (s *stringFlags) String() string { return strings.Join(*s, ",") } +func (s *stringFlags) Set(v string) error { *s = append(*s, v); return nil } + +func (o *options) stateName() string { + return fmt.Sprintf("credentials-migration-%d", o.migration) +} + +// state is what the migration keeps between the hook and the Job, in a +// ConfigMap in cozy-system named for the migration. +type state struct { + // Releases maps namespace/name to the record of the release. + Releases map[string]*releaseState `json:"releases"` + // 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"` +} + +type releaseState struct { + // ChartVersion the release rendered when the hook recorded it; the Job + // acts once the release is Ready on another one. + ChartVersion string `json:"chartVersion"` + Done bool `json:"done,omitempty"` +} + +func main() { + if err := run(os.Args[1:]); err != nil { + fmt.Fprintln(os.Stderr, "credentials-migrate:", err) + os.Exit(1) + } +} + +func run(args []string) error { + if len(args) < 1 { + return errors.New("usage: credentials-migrate seed|finish [flags]") + } + cmd := args[0] + o := &options{labels: labelFlags{}} + fs := flag.NewFlagSet(cmd, flag.ContinueOnError) + fs.IntVar(&o.migration, "migration", 0, "number of the platform migration that converts the kind") + fs.StringVar(&o.kind, "kind", "", "application kind, as the HelmRelease label names it") + 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.labels, "label", "label every account Secret carries, key=value; repeatable") + 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.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") + 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") + } + + scheme := runtime.NewScheme() + if err := corev1.AddToScheme(scheme); err != nil { + return err + } + if err := helmv2.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) + } + m := &migrator{c: c, o: o, now: time.Now} + ctx := context.Background() + switch cmd { + case "seed": + return m.seed(ctx) + case "finish": + return m.finish(ctx) + } + return fmt.Errorf("unknown command %q: want seed or finish", cmd) +} + +func envOr(key, def string) string { + if v := os.Getenv(key); v != "" { + return v + } + return def +} + +type migrator struct { + c client.Client + o *options + now func() time.Time +} + +// seed records every release of the kind and writes the account Secrets it +// still lacks from the chart-generated passwords. A release whose accounts +// cannot be resolved is left out with an Event; one whose source Secret is +// gone is recorded, since the Job still has to switch it, and its accounts +// get their Secrets from the first mint. +func (m *migrator) seed(ctx context.Context) error { + st, err := m.loadState(ctx) + if err != nil { + return err + } + releases, err := m.releases(ctx) + if err != nil { + return err + } + for i := range releases { + hr := &releases[i] + key := hr.Namespace + "/" + hr.Name + rec, known := st.Releases[key] + if !known { + rec = &releaseState{ChartVersion: chartVersion(hr)} + st.Releases[key] = rec + } + if err := m.seedRelease(ctx, hr); err != nil { + if !errors.Is(err, errUnresolvable) { + if serr := m.saveState(ctx, st); serr != nil { + return errors.Join(fmt.Errorf("%s: %w", key, err), serr) + } + return fmt.Errorf("%s: %w", key, err) + } + m.skip(ctx, st, hr, err) + continue + } + delete(st.Skipped, key) + fmt.Printf("%s: recorded chart version %q\n", key, rec.ChartVersion) + } + return m.saveState(ctx, st) +} + +// finish converts every recorded release once its chart has switched, and +// exits non-zero while any is left out, so one place shows what remains. +func (m *migrator) finish(ctx context.Context) error { + st, err := m.loadState(ctx) + if err != nil { + return err + } + keys := make([]string, 0, len(st.Releases)) + for k := range st.Releases { + keys = append(keys, k) + } + sort.Strings(keys) + for _, key := range keys { + rec := st.Releases[key] + if rec.Done { + continue + } + 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) { + // Deleted since the hook: nothing left to convert. + rec.Done = true + delete(st.Skipped, key) + continue + } + return err + } + if err := m.finishReleaseRetrying(ctx, hr, rec); err != nil { + m.leaveOut(ctx, st, hr, err) + if err := m.saveState(ctx, st); err != nil { + return err + } + continue + } + rec.Done = true + delete(st.Skipped, key) + fmt.Printf("%s: converted\n", key) + if err := m.saveState(ctx, st); err != nil { + return err + } + } + if err := m.saveState(ctx, st); err != nil { + return err + } + if len(st.Skipped) > 0 { + var left []string + for k, why := range st.Skipped { + left = append(left, k+": "+why) + } + sort.Strings(left) + return fmt.Errorf("%d release(s) left out:\n %s", len(left), strings.Join(left, "\n ")) + } + return nil +} + +func (m *migrator) finishRelease(ctx context.Context, hr *helmv2.HelmRelease, rec *releaseState) error { + // Seed again first: an account whose Secret is still missing, as after an + // interrupted hook, gets it here while the plaintext still exists. + if err := m.seedRelease(ctx, hr); err != nil { + return err + } + // Without a recorded version nothing tells the old chart from the new + // one, and retiring the source under the old chart takes its passwords. + if rec.ChartVersion == "" { + return errors.New("no chart version was recorded before the upgrade, so the switch cannot be confirmed; check that the release renders the converted chart and finish it by hand") + } + deadline := m.now().Add(m.o.timeout) + for { + if apimeta.IsStatusConditionTrue(hr.Status.Conditions, "Ready") && chartVersion(hr) != "" && chartVersion(hr) != rec.ChartVersion { + break + } + if m.now().After(deadline) { + return fmt.Errorf("not Ready on a chart version other than %q after %s (current %q)", rec.ChartVersion, m.o.timeout, chartVersion(hr)) + } + time.Sleep(10 * time.Second) + if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), 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) +} + +// seedRelease writes the account Secrets the release lacks, unowned: the +// CredentialTemplate controller adopts them once the converted chart renders +// the templates. Once every declared account has its Secret, it marks the +// release for seeding, so accounts added later get theirs from the +// controller. A release where an account is left without a Secret, its +// plaintext missing or one that would not carry over, stays unmarked: a seeded +// random password would lock out the clients that use the old one, so that +// account waits for a mint. A release that declares no account has no +// plaintext to lose, so it is marked whether or not its source exists: the +// chart renders the source only once there is a user, and without the mark +// 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) + if err != nil { + return fmt.Errorf("%w: %v", errUnresolvable, err) + } + source := &corev1.Secret{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: hr.Name + m.o.sourceSuffix}, source); err != nil { + if !apierrors.IsNotFound(err) { + return err + } + if len(accounts) > 0 { + fmt.Printf("%s/%s: %s%s is gone; its accounts get a Secret at their first mint\n", hr.Namespace, hr.Name, hr.Name, m.o.sourceSuffix) + return nil + } + } + now := metav1.NewTime(m.now()) + complete := true + for _, acc := range accounts { + name := account.SecretName(hr.Name, acc.Mapped) + cur := &corev1.Secret{} + err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: name}, cur) + switch { + case err == nil && account.IsAccountSecret(cur) && string(cur.Data[account.UsernameKey]) == acc.Username: + continue + case err == nil && metav1.GetControllerOf(cur) == nil: + // Left from a deleted application of the same name, or not an + // account Secret at all: the operator would apply whatever it + // holds, so this one replaces it. + if err := m.c.Delete(ctx, cur, client.Preconditions{UID: &cur.UID}); err != nil && !apierrors.IsNotFound(err) { + return fmt.Errorf("replace stale %s: %w", name, err) + } + case err == nil: + fmt.Printf("%s/%s: %s exists and is not an account Secret this conversion wrote; leaving it and the account %q alone\n", hr.Namespace, hr.Name, name, acc.Username) + complete = false + continue + case !apierrors.IsNotFound(err): + return err + } + plaintext, ok := source.Data[acc.Username] + if !ok { + fmt.Printf("%s/%s: no password for %q in %s%s; the account gets a Secret at its first mint\n", hr.Namespace, hr.Name, acc.Username, hr.Name, m.o.sourceSuffix) + complete = false + continue + } + if !format.CarriesOver(m.o.formatName, string(plaintext)) { + // A verifier built from this password would not authenticate it + // after the engine's login-time normalization, so the account is + // re-minted instead of carried over with a Secret nobody can use. + fmt.Printf("%s/%s: the password for %q in %s%s does not carry into a %s verifier unchanged; the account gets a Secret at its first mint\n", hr.Namespace, hr.Name, acc.Username, hr.Name, m.o.sourceSuffix, m.o.formatName) + complete = false + continue + } + stored, err := format.Encode(m.o.formatName, string(plaintext)) + if err != nil { + return err + } + sec := &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: name, + Namespace: hr.Namespace, + Labels: account.Labels(m.o.labels), + Annotations: map[string]string{account.FormatAnnotation: m.o.formatName}, + }, + Type: corev1.SecretTypeBasicAuth, + Data: map[string][]byte{ + account.UsernameKey: []byte(acc.Username), + account.PasswordKey: []byte(stored), + }, + } + account.WriteRecord(sec, account.Record{}.Apply(corev1alpha1.CredentialOperationMigrate, now, m.o.actor)) + if err := m.c.Create(ctx, sec); err != nil { + return fmt.Errorf("create %s: %w", name, err) + } + fmt.Printf("%s/%s: migrated account %q into %s\n", hr.Namespace, hr.Name, acc.Username, name) + } + if !complete || hr.Annotations[account.SeedAnnotation] == "true" { + return nil + } + patch := client.MergeFrom(hr.DeepCopy()) + if hr.Annotations == nil { + hr.Annotations = map[string]string{} + } + hr.Annotations[account.SeedAnnotation] = "true" + if err := m.c.Patch(ctx, hr, patch); err != nil { + return fmt.Errorf("mark for seeding: %w", err) + } + return nil +} + +// 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) { + 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 { + return nil, err + } + } + users, _ := lookup(values, path).(map[string]any) + names := make([]string, 0, len(users)) + for name := range users { + names = append(names, name) + } + sort.Strings(names) + var accounts []account.Account + byMapped := map[string]string{} + for _, name := range names { + if u, ok := users[name].(map[string]any); ok { + for _, field := range refuse { + if on, _ := u[field].(bool); on { + return nil, fmt.Errorf("%s.%s.%s is true, which the converted chart refuses; set it to false", path, name, field) + } + } + } + mapped, err := account.MapName(name) + if err != nil { + return nil, err + } + if other, dup := byMapped[mapped]; dup { + return nil, fmt.Errorf("users %q and %q both map to the name %q", other, name, mapped) + } + byMapped[mapped] = name + accounts = append(accounts, account.Account{Username: name, Mapped: mapped}) + } + return accounts, nil +} + +// lookup walks a dotted path through nested maps. +func lookup(values map[string]any, path string) any { + var cur any = values + for _, key := range strings.Split(path, ".") { + m, ok := cur.(map[string]any) + if !ok { + return nil + } + cur, ok = m[key] + if !ok { + return nil + } + } + return cur +} + +// stripPasswords removes a password left under any key of the accounts map in +// the release's values. +func (m *migrator) stripPasswords(ctx context.Context, hr *helmv2.HelmRelease) error { + if hr.Spec.Values == nil || len(hr.Spec.Values.Raw) == 0 { + return nil + } + var values map[string]any + if err := json.Unmarshal(hr.Spec.Values.Raw, &values); err != nil { + return err + } + users, _ := lookup(values, m.o.accountsPath).(map[string]any) + changed := false + for name, raw := range users { + u, ok := raw.(map[string]any) + if !ok { + continue + } + if _, has := u["password"]; has { + delete(u, "password") + changed = true + fmt.Printf("%s/%s: removed %s.%s.password from the values\n", hr.Namespace, hr.Name, m.o.accountsPath, name) + } + } + if !changed { + return nil + } + raw, err := json.Marshal(values) + if err != nil { + return err + } + patch := client.MergeFrom(hr.DeepCopy()) + hr.Spec.Values.Raw = raw + return m.c.Patch(ctx, hr, patch) +} + +// retireSource removes the tenant keys from the chart-generated Secret, which +// stay in its data otherwise, and the Secret itself when no platform key +// remains. +func (m *migrator) retireSource(ctx context.Context, hr *helmv2.HelmRelease) error { + 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 + } + keep := map[string]bool{} + for _, k := range m.o.platformKeys { + keep[k] = true + } + remaining := map[string][]byte{} + for k, v := range source.Data { + if keep[k] { + remaining[k] = v + } + } + if len(remaining) == 0 { + if err := m.c.Delete(ctx, source, client.Preconditions{UID: &source.UID}); err != nil && !apierrors.IsNotFound(err) { + return err + } + fmt.Printf("%s/%s: deleted %s\n", hr.Namespace, hr.Name, source.Name) + return nil + } + if len(remaining) == len(source.Data) { + return nil + } + patch := client.MergeFrom(source.DeepCopy()) + source.Data = remaining + if err := m.c.Patch(ctx, source, patch); err != nil { + return err + } + fmt.Printf("%s/%s: removed the tenant keys from %s\n", hr.Namespace, hr.Name, source.Name) + return nil +} + +func (m *migrator) releases(ctx context.Context) ([]helmv2.HelmRelease, error) { + list := &helmv2.HelmReleaseList{} + if err := m.c.List(ctx, list, client.MatchingLabels{ + appsv1alpha1.ApplicationGroupLabel: appsv1alpha1.GroupName, + appsv1alpha1.ApplicationKindLabel: m.o.kind, + }); err != nil { + return nil, err + } + return list.Items, nil +} + +// skip leaves a release out: logged, recorded in the state, and announced +// with an Event on the HelmRelease, so the cause is visible where the +// release is. +func (m *migrator) skip(ctx context.Context, st *state, hr *helmv2.HelmRelease, cause error) { + key := hr.Namespace + "/" + hr.Name + why := fmt.Sprintf("%s at %s", cause.Error(), m.now().UTC().Format(time.RFC3339)) + st.Skipped[key] = why + fmt.Fprintf(os.Stderr, "%s: left out: %v\n", key, cause) + ev := &corev1.Event{ + ObjectMeta: metav1.ObjectMeta{GenerateName: hr.Name + ".", Namespace: hr.Namespace}, + InvolvedObject: corev1.ObjectReference{ + APIVersion: helmv2.GroupVersion.String(), Kind: helmv2.HelmReleaseKind, + Name: hr.Name, Namespace: hr.Namespace, UID: hr.UID, + }, + Reason: reasonSkipped, + Message: fmt.Sprintf("credentials migration %d left this release out: %v", m.o.migration, cause), + Type: corev1.EventTypeWarning, + Source: corev1.EventSource{Component: "credentials-migrate"}, + FirstTimestamp: metav1.NewTime(m.now()), + LastTimestamp: metav1.NewTime(m.now()), + Count: 1, + } + if err := m.c.Create(ctx, ev); err != nil { + fmt.Fprintf(os.Stderr, "%s: failed to record event: %v\n", key, err) + } +} + +func (m *migrator) loadState(ctx context.Context) (*state, error) { + st := &state{Releases: map[string]*releaseState{}, Skipped: map[string]string{}} + cm := &corev1.ConfigMap{} + err := m.c.Get(ctx, types.NamespacedName{Namespace: m.o.stateNamespace, Name: m.o.stateName()}, cm) + if apierrors.IsNotFound(err) { + return st, nil + } + if err != nil { + return nil, err + } + if raw := cm.Data["state"]; raw != "" { + if err := json.Unmarshal([]byte(raw), st); err != nil { + return nil, fmt.Errorf("decode state ConfigMap %s: %w", cm.Name, err) + } + } + if st.Releases == nil { + st.Releases = map[string]*releaseState{} + } + if st.Skipped == nil { + st.Skipped = map[string]string{} + } + return st, nil +} + +func (m *migrator) saveState(ctx context.Context, st *state) error { + raw, err := json.MarshalIndent(st, "", " ") + if err != nil { + return err + } + cm := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: m.o.stateNamespace, Name: m.o.stateName()}} + _, err = ctrl.CreateOrUpdate(ctx, m.c, cm, func() error { + if cm.Data == nil { + cm.Data = map[string]string{} + } + cm.Data["state"] = string(raw) + if cm.Labels == nil { + cm.Labels = map[string]string{} + } + if len(st.Skipped) > 0 { + cm.Labels[incompleteLabel] = "true" + } else { + cm.Labels[incompleteLabel] = "false" + } + return nil + }) + return err +} + +func chartVersion(hr *helmv2.HelmRelease) string { + if s := hr.Status.History.Latest(); s != nil { + return s.ChartVersion + } + return "" +} diff --git a/cmd/credentials-migrate/main_test.go b/cmd/credentials-migrate/main_test.go new file mode 100644 index 000000000..016007839 --- /dev/null +++ b/cmd/credentials-migrate/main_test.go @@ -0,0 +1,458 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "encoding/json" + "strings" + "testing" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" + "github.com/cozystack/cozystack/pkg/credentials/account" + "github.com/cozystack/cozystack/pkg/credentials/format" +) + +func newMigrator(t *testing.T, objs ...client.Object) *migrator { + t.Helper() + return newMigratorWith(t, nil, objs...) +} + +// newMigratorWith builds the migrator on a client whose calls go through funcs. +func newMigratorWith(t *testing.T, funcs *interceptor.Funcs, objs ...client.Object) *migrator { + t.Helper() + scheme := runtime.NewScheme() + if err := corev1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + if err := helmv2.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + b := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objs...).WithStatusSubresource(&helmv2.HelmRelease{}) + if funcs != nil { + b = b.WithInterceptorFuncs(*funcs) + } + c := b.Build() + 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, + } + return &migrator{c: c, o: o, now: func() time.Time { return time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC) }} +} + +func release(values string, chartVersion string, ready bool) *helmv2.HelmRelease { + hr := &helmv2.HelmRelease{ + ObjectMeta: metav1.ObjectMeta{Name: "postgres-orders", Namespace: "tenant-foo", UID: "hr-uid", Labels: map[string]string{ + appsv1alpha1.ApplicationGroupLabel: appsv1alpha1.GroupName, + appsv1alpha1.ApplicationKindLabel: "Postgres", + appsv1alpha1.ApplicationNameLabel: "orders", + }}, + Spec: helmv2.HelmReleaseSpec{Values: &apiextv1.JSON{Raw: []byte(values)}}, + } + if chartVersion != "" { + hr.Status.History = helmv2.Snapshots{{Version: 1, ChartVersion: chartVersion, Status: "deployed"}} + } + if ready { + hr.Status.Conditions = []metav1.Condition{{Type: "Ready", Status: metav1.ConditionTrue, Reason: "x", LastTransitionTime: metav1.Now()}} + } + return hr +} + +func sourceSecret(data map[string]string) *corev1.Secret { + sec := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "postgres-orders-credentials", Namespace: "tenant-foo"}, Data: map[string][]byte{}} + for k, v := range data { + sec.Data[k] = []byte(v) + } + return sec +} + +func (m *migrator) secret(t *testing.T, name string) (*corev1.Secret, bool) { + t.Helper() + sec := &corev1.Secret{} + err := m.c.Get(context.Background(), types.NamespacedName{Namespace: "tenant-foo", Name: name}, sec) + if apierrors.IsNotFound(err) { + return nil, false + } + if err != nil { + t.Fatal(err) + } + return sec, true +} + +func TestSeedRecordsAndMigrates(t *testing.T) { + ctx := context.Background() + m := newMigrator(t, release(`{"users":{"web":{},"Api.1":{}}}`, "0.1.0", true), sourceSecret(map[string]string{"web": "hunter2", "Api.1": "secret"})) + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + st, err := m.loadState(ctx) + if err != nil { + t.Fatal(err) + } + rec := st.Releases["tenant-foo/postgres-orders"] + if rec == nil || rec.ChartVersion != "0.1.0" || rec.Done || len(st.Skipped) != 0 { + t.Fatalf("state = %+v", st) + } + for _, c := range []struct{ secret, user, plain string }{{"postgres-orders.web.account", "web", "hunter2"}, {"postgres-orders.api-1.account", "Api.1", "secret"}} { + sec, ok := m.secret(t, c.secret) + if !ok { + t.Fatalf("%s not written", c.secret) + } + if string(sec.Data[account.UsernameKey]) != c.user || !strings.HasPrefix(string(sec.Data[account.PasswordKey]), "SCRAM-SHA-256$4096:") { + t.Fatalf("%s data = %q", c.secret, sec.Data) + } + if strings.Contains(string(sec.Data[account.PasswordKey]), c.plain) { + t.Fatal("the plaintext must not be stored") + } + // Unowned: the CredentialTemplate controller adopts it once the + // converted chart renders the template. + if sec.Labels["cnpg.io/reload"] != "true" || sec.Labels[account.AccountLabel] != "true" || len(sec.OwnerReferences) != 0 || sec.Annotations[account.FormatAnnotation] != "scram-sha-256" { + t.Fatalf("%s meta = %+v", c.secret, sec.ObjectMeta) + } + r := account.ReadRecord(sec) + if r.Origin != corev1alpha1.CredentialOriginMigrated || r.By != "migration" || len(r.History) != 1 || r.History[0].Operation != corev1alpha1.CredentialOperationMigrate { + t.Fatalf("%s record = %+v", c.secret, r) + } + } + hr := &helmv2.HelmRelease{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: "tenant-foo", Name: "postgres-orders"}, hr); err != nil { + t.Fatal(err) + } + if hr.Annotations[account.SeedAnnotation] != "true" { + t.Fatal("a release whose accounts all got a Secret must be marked for seeding") + } + // A second run keeps what it wrote. + before, _ := m.secret(t, "postgres-orders.web.account") + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + after, _ := m.secret(t, "postgres-orders.web.account") + if string(after.Data[account.PasswordKey]) != string(before.Data[account.PasswordKey]) { + t.Fatal("seed must be idempotent") + } +} + +func TestSeedLeavesOutUnresolvableAndRecordsMissingSource(t *testing.T) { + ctx := context.Background() + colliding := release(`{"users":{"web_app":{},"web-app":{}}}`, "0.1.0", true) + m := newMigrator(t, colliding) + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + st, _ := m.loadState(ctx) + if why := st.Skipped["tenant-foo/postgres-orders"]; !strings.Contains(why, "both map to the name") { + t.Fatalf("skipped = %v", st.Skipped) + } + evs := &corev1.EventList{} + if err := m.c.List(ctx, evs, client.InNamespace("tenant-foo")); err != nil || len(evs.Items) != 1 || evs.Items[0].Reason != reasonSkipped { + t.Fatalf("events = %+v err=%v", evs.Items, err) + } + + // No source Secret: recorded, nothing seeded, not skipped. + m = newMigrator(t, release(`{"users":{"web":{}}}`, "0.1.0", true)) + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + st, _ = m.loadState(ctx) + if st.Releases["tenant-foo/postgres-orders"] == nil || len(st.Skipped) != 0 { + t.Fatalf("state = %+v", st) + } + if _, ok := m.secret(t, "postgres-orders.web.account"); ok { + t.Fatal("nothing to seed from") + } +} + +func TestSeedMarksAReleaseWithoutUsersAndWithoutASource(t *testing.T) { + ctx := context.Background() + // The chart renders the source only once there is a user. + m := newMigrator(t, release(`{"users":{}}`, "0.1.0", true)) + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + hr := &helmv2.HelmRelease{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: "tenant-foo", Name: "postgres-orders"}, hr); err != nil { + t.Fatal(err) + } + if hr.Annotations[account.SeedAnnotation] != "true" { + t.Fatal("a release without users must be marked, or its first user never gets a Secret") + } +} + +func TestFinishWaitsForTheSwitchThenStripsAndRetires(t *testing.T) { + ctx := context.Background() + hr := release(`{"users":{"web":{"password":"leftover"}},"size":"10Gi"}`, "0.1.0", true) + m := newMigrator(t, hr, sourceSecret(map[string]string{"web": "hunter2"})) + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + // Still on the recorded chart version: left out, reported, state kept. + err := m.finish(ctx) + if err == nil || !strings.Contains(err.Error(), "1 release(s) left out") { + t.Fatalf("finish on an unswitched release: %v", err) + } + if _, ok := m.secret(t, "postgres-orders-credentials"); !ok { + t.Fatal("the source must survive until the chart has switched") + } + + // Switched and Ready. + cur := &helmv2.HelmRelease{} + if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil { + t.Fatal(err) + } + 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) + } + st, _ := m.loadState(ctx) + if rec := st.Releases["tenant-foo/postgres-orders"]; rec == nil || !rec.Done || len(st.Skipped) != 0 { + t.Fatalf("state = %+v", st) + } + if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), 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 || values["size"] != "10Gi" { + t.Fatalf("values = %v", values) + } + if _, ok := m.secret(t, "postgres-orders-credentials"); ok { + t.Fatal("the source Secret of a kind without platform accounts must be deleted") + } + if _, ok := m.secret(t, "postgres-orders.web.account"); !ok { + t.Fatal("the account Secret must stay") + } +} + +func TestRetireSourceKeepsPlatformKeys(t *testing.T) { + ctx := context.Background() + hr := release(`{"users":{"web":{}}}`, "0.1.0", true) + m := newMigrator(t, hr, sourceSecret(map[string]string{"web": "hunter2", "root": "toor"})) + m.o.platformKeys = stringFlags{"root"} + if err := m.retireSource(ctx, hr); err != nil { + t.Fatal(err) + } + sec, ok := m.secret(t, "postgres-orders-credentials") + if !ok || string(sec.Data["root"]) != "toor" || len(sec.Data) != 1 { + t.Fatalf("source = %v", sec) + } +} + +// A transient API error must fail the hook, so the upgrade retries: left out +// as a skip, the chart would switch and take the plaintext with it. +func TestSeedFailsClosedOnAnAPIError(t *testing.T) { + ctx := context.Background() + m := newMigratorWith(t, &interceptor.Funcs{ + Create: func(ctx context.Context, cl client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + if sec, ok := obj.(*corev1.Secret); ok && strings.HasSuffix(sec.Name, ".account") { + return apierrors.NewServiceUnavailable("etcd is busy") + } + return cl.Create(ctx, obj, opts...) + }, + }, release(`{"users":{"web":{}}}`, "0.1.0", true), sourceSecret(map[string]string{"web": "hunter2"})) + if err := m.seed(ctx); err == nil || !strings.Contains(err.Error(), "etcd is busy") { + t.Fatalf("seed = %v, want the API error", err) + } + st, err := m.loadState(ctx) + if err != nil { + t.Fatal(err) + } + if len(st.Skipped) != 0 { + t.Fatalf("a transient error must not be recorded as a skip: %v", st.Skipped) + } +} + +func TestFinishHoldsAReleaseWithNoRecordedVersion(t *testing.T) { + ctx := context.Background() + m := newMigrator(t, release(`{"users":{"web":{}}}`, "", true), sourceSecret(map[string]string{"web": "hunter2"})) + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + m.switchChart(t, "0.2.0", true) + if err := m.finish(ctx); err == nil { + t.Fatal("finish must report a release it cannot confirm switched") + } + if _, ok := m.secret(t, "postgres-orders-credentials"); !ok { + t.Fatal("the source must stay while the switch cannot be confirmed") + } +} + +func TestFinishWaitsForReady(t *testing.T) { + ctx := context.Background() + m := newMigrator(t, release(`{"users":{"web":{"password":"leftover"}}}`, "0.1.0", true), sourceSecret(map[string]string{"web": "hunter2"})) + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + // On the new chart, but the upgrade has not succeeded. + m.switchChart(t, "0.2.0", false) + if err := m.finish(ctx); err == nil { + t.Fatal("finish must hold a release that is not Ready") + } + if _, ok := m.secret(t, "postgres-orders-credentials"); !ok { + t.Fatal("the source must stay until the release is Ready on the new chart") + } +} + +func TestFinishTreatsADeletedReleaseAsDone(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 err := m.c.Delete(ctx, hr); err != nil { + t.Fatal(err) + } + if err := m.finish(ctx); err != nil { + t.Fatalf("finish = %v, want nothing left to convert", err) + } +} + +func TestSeedKeepsTheFirstRecordedVersion(t *testing.T) { + ctx := context.Background() + m := newMigrator(t, release(`{"users":{"web":{}}}`, "0.1.0", true), sourceSecret(map[string]string{"web": "hunter2"})) + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + // The hook runs again after the chart has moved on, as a retried upgrade does. + m.switchChart(t, "0.2.0", true) + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + st, _ := m.loadState(ctx) + if v := st.Releases["tenant-foo/postgres-orders"].ChartVersion; v != "0.1.0" { + t.Fatalf("recorded version = %q, want the first one", v) + } +} + +func TestSeedReplacesAForeignSecretAndSkipsAMissingPlaintext(t *testing.T) { + ctx := context.Background() + foreign := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "postgres-orders.web.account", Namespace: "tenant-foo"}, + Data: map[string][]byte{account.UsernameKey: []byte("web"), account.PasswordKey: []byte("planted")}} + m := newMigrator(t, release(`{"users":{"web":{},"api":{}}}`, "0.1.0", true), foreign, sourceSecret(map[string]string{"web": "hunter2"})) + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + sec, _ := m.secret(t, "postgres-orders.web.account") + if string(sec.Data[account.PasswordKey]) == "planted" || !account.IsAccountSecret(sec) { + t.Fatal("a Secret that is not the release's own must be replaced, or the operator applies its verifier") + } + if _, ok := m.secret(t, "postgres-orders.api.account"); ok { + t.Fatal("an account with no plaintext to migrate is left to its first mint") + } + hr := &helmv2.HelmRelease{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: "tenant-foo", Name: "postgres-orders"}, hr); err != nil { + t.Fatal(err) + } + if hr.Annotations[account.SeedAnnotation] == "true" { + t.Fatal("a release with an account left for a mint must stay unmarked, or the controller seeds over the password its clients use") + } +} + +func TestSeedSkipsAPasswordThatDoesNotCarryOver(t *testing.T) { + ctx := context.Background() + // PostgreSQL runs SASLprep on the presented password at login, and it + // removes a soft hyphen (U+00AD), so a SCRAM verifier built here from the + // raw bytes would never authenticate the password. The account is left to + // its first mint rather than stored as a verifier nobody can log in with. + m := newMigrator(t, release(`{"users":{"ascii":{},"weird":{}}}`, "0.1.0", true), sourceSecret(map[string]string{"ascii": "hunter2", "weird": "I­X"})) + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + if _, ok := m.secret(t, "postgres-orders.ascii.account"); !ok { + t.Fatal("a printable-ASCII password must carry over") + } + if _, ok := m.secret(t, "postgres-orders.weird.account"); ok { + t.Fatal("a password SASLprep would rewrite must be left to its first mint, not stored") + } + st, _ := m.loadState(ctx) + if st.Releases["tenant-foo/postgres-orders"] == nil || len(st.Skipped) != 0 { + t.Fatalf("the release is recorded and not skipped: %+v", st) + } +} + +// switchChart moves the release to another chart version, Ready or not. +func (m *migrator) switchChart(t *testing.T, version string, ready bool) { + t.Helper() + ctx := context.Background() + cur := &helmv2.HelmRelease{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: "tenant-foo", Name: "postgres-orders"}, cur); err != nil { + t.Fatal(err) + } + cur.Status.History = helmv2.Snapshots{{Version: 2, ChartVersion: version, Status: "deployed"}} + status := metav1.ConditionFalse + if ready { + status = metav1.ConditionTrue + } + cur.Status.Conditions = []metav1.Condition{{Type: "Ready", Status: status, Reason: "x", LastTransitionTime: metav1.Now()}} + if err := m.c.Status().Update(ctx, cur); err != nil { + t.Fatal(err) + } +} + +func TestSaveStateLabelsIncompleteForTheAlert(t *testing.T) { + ctx := context.Background() + m := newMigrator(t) + + readLabel := func() string { + cm := &corev1.ConfigMap{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: "cozy-system", Name: m.o.stateName()}, cm); err != nil { + t.Fatalf("get state ConfigMap: %v", err) + } + return cm.Labels[incompleteLabel] + } + + // A release left out marks the conversion incomplete, so the durable + // CredentialsMigrationIncomplete alert fires on the ConfigMap label. + if err := m.saveState(ctx, &state{Releases: map[string]*releaseState{}, Skipped: map[string]string{"tenant-foo/postgres-orders": "left out at 2026-10-14T12:00:00Z"}}); err != nil { + t.Fatal(err) + } + if got := readLabel(); got != "true" { + t.Fatalf("%s = %q, want true while a release is skipped", incompleteLabel, got) + } + + // None left out clears the label, so the alert resolves. + if err := m.saveState(ctx, &state{Releases: map[string]*releaseState{}, Skipped: map[string]string{}}); err != nil { + t.Fatal(err) + } + if got := readLabel(); got != "false" { + t.Fatalf("%s = %q, want false once none is skipped", incompleteLabel, got) + } +} + +func TestSeedLeavesOutAReleaseWithARefusedFlag(t *testing.T) { + ctx := context.Background() + m := newMigrator(t, release(`{"users":{"web":{},"migrator":{"createRole":true}}}`, "0.1.0", true), sourceSecret(map[string]string{"web": "hunter2", "migrator": "secret"})) + m.o.refuseFlags = stringFlags{"createRole"} + if err := m.seed(ctx); err != nil { + t.Fatal(err) + } + st, err := m.loadState(ctx) + if err != nil { + t.Fatal(err) + } + if _, left := st.Skipped["tenant-foo/postgres-orders"]; !left { + t.Fatalf("state = %+v, want the release left out", st) + } + if _, ok := m.secret(t, "postgres-orders.web.account"); ok { + t.Fatal("a release the converted chart refuses must not be converted in part") + } +} diff --git a/cmd/credentials-migrate/retry.go b/cmd/credentials-migrate/retry.go new file mode 100644 index 000000000..cb1c94ea4 --- /dev/null +++ b/cmd/credentials-migrate/retry.go @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "os" + "strings" + "syscall" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// reasonRetrying names an Event for a release that hit a transient error and +// is converted on a later attempt, unlike reasonSkipped, which needs a person. +const reasonRetrying = "CredentialsMigrationRetrying" + +// transientAttempts and transientDelay bound the in-process retries of a +// release that hit a transient error, before the Job's own restart retries it. +var ( + transientAttempts = 3 + transientDelay = 10 * time.Second +) + +// isTransient reports whether err comes from the API server or the +// connection to it rather than from the release: retrying the same release +// can succeed without anyone changing anything. +func isTransient(err error) bool { + switch { + case apierrors.IsServerTimeout(err), apierrors.IsTimeout(err), apierrors.IsTooManyRequests(err), + apierrors.IsServiceUnavailable(err), apierrors.IsInternalError(err), apierrors.IsUnexpectedServerError(err), + apierrors.IsConflict(err): + return true + case errors.Is(err, io.EOF), errors.Is(err, io.ErrUnexpectedEOF), + errors.Is(err, syscall.ECONNRESET), errors.Is(err, syscall.ECONNREFUSED), errors.Is(err, syscall.EPIPE): + return true + } + var netErr net.Error + if errors.As(err, &netErr) { + return true + } + // client-go wraps a body read that failed mid-response this way. + return strings.Contains(err.Error(), "unexpected error when reading response body") +} + +// finishReleaseRetrying runs finishRelease, retrying a transient error on a +// fresh read of the release. +func (m *migrator) finishReleaseRetrying(ctx context.Context, hr *helmv2.HelmRelease, rec *releaseState) error { + var err error + for attempt := 1; ; attempt++ { + if err = m.finishRelease(ctx, hr, rec); err == nil || !isTransient(err) || attempt >= transientAttempts { + return err + } + fmt.Fprintf(os.Stderr, "%s/%s: transient error, retrying: %v\n", hr.Namespace, hr.Name, err) + time.Sleep(transientDelay) + if gerr := m.c.Get(ctx, client.ObjectKeyFromObject(hr), hr); gerr != nil && !isTransient(gerr) { + return gerr + } + } +} + +// leaveOut records a release finish could not convert. A transient error is +// recorded for the alert like any other, but announced as a retry rather +// than as a release left out, since the Job's restart converts it. +func (m *migrator) leaveOut(ctx context.Context, st *state, hr *helmv2.HelmRelease, cause error) { + if !isTransient(cause) { + m.skip(ctx, st, hr, cause) + return + } + key := hr.Namespace + "/" + hr.Name + st.Skipped[key] = fmt.Sprintf("transient error, retried by the Job: %s at %s", cause.Error(), m.now().UTC().Format(time.RFC3339)) + fmt.Fprintf(os.Stderr, "%s: transient error, retried at the next attempt: %v\n", key, cause) + ev := &corev1.Event{ + ObjectMeta: metav1.ObjectMeta{GenerateName: hr.Name + ".", Namespace: hr.Namespace}, + InvolvedObject: corev1.ObjectReference{ + APIVersion: helmv2.GroupVersion.String(), Kind: helmv2.HelmReleaseKind, + Name: hr.Name, Namespace: hr.Namespace, UID: hr.UID, + }, + Reason: reasonRetrying, + Message: fmt.Sprintf("credentials migration %d hit a transient error on this release and retries it: %v", m.o.migration, cause), + Type: corev1.EventTypeNormal, + Source: corev1.EventSource{Component: "credentials-migrate"}, + FirstTimestamp: metav1.NewTime(m.now()), + LastTimestamp: metav1.NewTime(m.now()), + Count: 1, + } + if err := m.c.Create(ctx, ev); err != nil { + fmt.Fprintf(os.Stderr, "%s: failed to record event: %v\n", key, err) + } +} diff --git a/cmd/credentials-migrate/retry_test.go b/cmd/credentials-migrate/retry_test.go new file mode 100644 index 000000000..03366acec --- /dev/null +++ b/cmd/credentials-migrate/retry_test.go @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "fmt" + "syscall" + "testing" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +// readReset is what client-go returns when the connection drops mid-body. +var readReset = fmt.Errorf("unexpected error when reading response body. Please retry. Original error: %w", syscall.ECONNRESET) + +func eventReasons(t *testing.T, m *migrator) map[string]int { + t.Helper() + evs := &corev1.EventList{} + if err := m.c.List(context.Background(), evs); err != nil { + t.Fatal(err) + } + out := map[string]int{} + for _, e := range evs.Items { + out[e.Reason]++ + } + return out +} + +// switchedFixture is a seeded release on the converted chart whose source +// Secret reads fail `fails` times with a dropped connection. +func switchedFixture(t *testing.T, fails int) *migrator { + t.Helper() + transientDelay = 0 + left := fails + funcs := &interceptor.Funcs{Patch: func(ctx context.Context, c client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + if _, ok := obj.(*helmv2.HelmRelease); ok && left > 0 && obj.GetAnnotations()["test/switched"] == "true" { + left-- + return readReset + } + 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"})) + ctx := context.Background() + 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) + } + 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) + } + // Mark it so only finish's patches fail, not the seed's. + cur.Annotations["test/switched"] = "true" + if err := m.c.Update(ctx, cur); err != nil { + t.Fatal(err) + } + return m +} + +func TestFinishRetriesATransientErrorWithoutASkipEvent(t *testing.T) { + m := switchedFixture(t, 1) + if err := m.finish(context.Background()); err != nil { + t.Fatal(err) + } + if r := eventReasons(t, m); r[reasonSkipped] != 0 || r[reasonRetrying] != 0 { + t.Fatalf("events = %v: a release converted on retry must not be announced as left out", r) + } + if st, _ := m.loadState(context.Background()); !st.Releases["tenant-foo/postgres-orders"].Done { + t.Fatalf("state = %+v", st) + } +} + +func TestFinishAnnouncesAPersistentTransientErrorAsARetry(t *testing.T) { + m := switchedFixture(t, 100) + if err := m.finish(context.Background()); err == nil { + t.Fatal("finish must fail so the Job retries") + } + r := eventReasons(t, m) + if r[reasonSkipped] != 0 || r[reasonRetrying] != 1 { + t.Fatalf("events = %v", r) + } + // Still recorded, so the incomplete alert fires if it never converts. + if st, _ := m.loadState(context.Background()); st.Skipped["tenant-foo/postgres-orders"] == "" { + t.Fatalf("state = %+v", st) + } +} + +func TestFinishStillSkipsAFinalError(t *testing.T) { + transientDelay = 0 + hr := release(`{"users":{"web":{}}}`, "0.1.0", true) + m := newMigrator(t, hr, sourceSecret(map[string]string{"web": "hunter2"})) + if err := m.seed(context.Background()); err != nil { + t.Fatal(err) + } + // Never switches: the wait times out, which no retry fixes. + if err := m.finish(context.Background()); err == nil { + t.Fatal("finish must fail") + } + if r := eventReasons(t, m); r[reasonSkipped] != 1 || r[reasonRetrying] != 0 { + t.Fatalf("events = %v", r) + } +} + +func TestIsTransient(t *testing.T) { + for _, c := range []struct { + err error + want bool + }{ + {readReset, true}, + {fmt.Errorf("get x: %w", syscall.ECONNRESET), true}, + {fmt.Errorf("not Ready on a chart version other than %q", "0.1.0"), false}, + {fmt.Errorf("%w: users.x", errUnresolvable), false}, + } { + if got := isTransient(c.err); got != c.want { + t.Errorf("isTransient(%v) = %v, want %v", c.err, got, c.want) + } + } +} From a67fa94fdbc5387ed2f9b3f5d2ede230979cfd34 Mon Sep 17 00:00:00 2001 From: Timofei Larkin Date: Mon, 23 Nov 2026 16:31:46 +0100 Subject: [PATCH 3/7] feat(postgres)!: issue user passwords through the credentials API The chart generated every user's password at render time into -credentials, which tenants could read again at any time and which Helm history kept for MaxHistory revisions, so a deployment whose policy requires a credential shown once could not run PostgreSQL here. The chart now renders a CredentialTemplate per user, and the users move under CloudNativePG's managed roles, each pointing at its account Secret, so the operator creates the role with the SCRAM verifier the Secret holds, applies a changed Secret live, and reverts a password set inside PostgreSQL. Every role is rendered as the init-script created it, because the operator reverts an attribute that differs, revokes a parent role missing from inRoles and clears a comment the spec leaves unset. The init-script stops creating, passwording and altering accounts, where it would be a second writer, and keeps the two things the operator has no field for: the marker membership and the reset of the createrole_self_grant an earlier chart set. Its marking pass waits a bounded time for CloudNativePG to create the declared roles before it marks them. users.app adopts the owner CloudNativePG bootstraps, whose password the instance manager applies again from the bootstrap secret on every pod start, so that secret is the app user's account Secret and both writers apply the one stored verifier. A users..password left in values draws an admission warning that points at a mint on the user's Credential. createRole is refused on every render path. A role a CREATEROLE user creates makes that user a member of it, CloudNativePG revokes every membership a managed role is not declared to hold, and the revoke fails on the dependent self-grant, so the user would sit in cannotReconcile on ordinary use; there is no per-role switch to leave memberships alone. The account-name checks render with the managed roles too, so a restore cannot bypass them: a user CloudNativePG or PostgreSQL reserves, a database whose derived _admin or _readonly role starts with pg_ or cnpg_ (which makes the CloudNativePG webhook reject the whole Cluster), and a user whose account name is no valid object name are refused. The chart's account naming is pinned to the API's on one table of names. A pre-upgrade hook refuses to let CloudNativePG adopt a role the chart did not mark, because the operator adopts a managed role within seconds of the spec reaching it, before any post-upgrade job could look. It reads the live Cluster first and connects to the database only when the upgrade adds a name CloudNativePG does not manage yet, so a database that is down does not block the resize that might fix it. For each absent declared database role it creates and marks the role as the superuser before the Cluster applies, so no tenant can plant it in the adoption window. The refusal and the create run in one psql session, keyed on a snapshot of the role's existence taken at the top, so a role planted in between collides with the CREATE and stops the hook; the statements are built with format() and \gexec, since psql does not substitute :'role' inside a DO $$ block. Verified on postgres:18: a fresh role is created NOINHERIT, commented and marked, a role planted after the snapshot fails the hook, and an existing unmarked role is refused. The hook reads the Cluster at run time with a ServiceAccount that may get only that Cluster, rather than through a template lookup, which nothing re-renders when the object changes. The flag an earlier chart set when a user held createRole is still read and never set, so such a release keeps refusing to adopt a role it did not mark. The EndpointAttachment e2e suite read testuser's password from that Secret to probe the attached addresses. It now mints one per probe and waits until the application's own Service accepts it, so the attached address is still queried exactly once. BREAKING CHANGE: PostgreSQL passwords are no longer readable from -credentials. A password is issued once, by a mint on the account's Credential in core.cozystack.io, and replaced by the next mint. users..createRole is refused; a release that sets it keeps its previous chart version and passwords until it is false. Deleting a Postgres application whose release is suspended is refused. The conversion needs a platform variant with migrations enabled. Co-authored-by: IvanHunters Co-authored-by: Andrei Kvapil Assisted-by: LLM Signed-off-by: Timofei Larkin Signed-off-by: Andrei Kvapil --- api/apps/v1alpha1/postgresql/types.go | 6 +- hack/check-postgres-app-owner-password.bats | 25 -- .../endpointattachment/chainsaw-test.yaml | 43 ++- .../endpointattachment/query-as-testuser.sh | 40 +++ packages/apps/postgres/README.md | 23 +- packages/apps/postgres/templates/NOTES.txt | 23 +- .../apps/postgres/templates/_accounts.tpl | 62 +++++ .../apps/postgres/templates/credentials.yaml | 23 ++ packages/apps/postgres/templates/db.yaml | 56 +++- .../templates/hooks/preflight-job.yaml | 245 ++++++++++++++++ .../apps/postgres/templates/init-job.yaml | 15 - .../apps/postgres/templates/init-script.yaml | 216 +++------------ .../postgres/tests/app_owner_secret_test.yaml | 89 +----- .../tests/credential_templates_test.yaml | 72 +++++ .../tests/credentials_lookup_test.yaml | 36 --- .../apps/postgres/tests/credentials_test.yaml | 71 ----- .../database_extension_validation_test.yaml | 5 +- .../postgres/tests/delete_users_test.yaml | 19 +- .../init_script_runtime_password_test.yaml | 195 ------------- .../tests/managed_roles_cluster_test.yaml | 241 ++++++++++++++++ .../postgres/tests/managed_roles_test.yaml | 60 ++-- .../tests/no_tenant_password_test.yaml | 60 ++++ .../postgres/tests/notes_bootstrap_test.yaml | 30 +- .../apps/postgres/tests/preflight_test.yaml | 262 ++++++++++++++++++ .../postgres/tests/user_createrole_test.yaml | 210 ++++++++------ .../tests/username_validation_test.yaml | 173 +++--------- packages/apps/postgres/values.schema.json | 6 +- packages/apps/postgres/values.yaml | 7 +- .../system/postgres-rd/cozyrds/postgres.yaml | 4 +- pkg/credentials/account/account_test.go | 9 + pkg/registry/apps/application/rest.go | 35 ++- ...est_warn_removed_password_callsite_test.go | 41 ++- 32 files changed, 1430 insertions(+), 972 deletions(-) delete mode 100644 hack/check-postgres-app-owner-password.bats create mode 100755 hack/e2e-chainsaw/endpointattachment/query-as-testuser.sh create mode 100644 packages/apps/postgres/templates/_accounts.tpl create mode 100644 packages/apps/postgres/templates/credentials.yaml create mode 100644 packages/apps/postgres/templates/hooks/preflight-job.yaml create mode 100644 packages/apps/postgres/tests/credential_templates_test.yaml delete mode 100644 packages/apps/postgres/tests/credentials_lookup_test.yaml delete mode 100644 packages/apps/postgres/tests/credentials_test.yaml delete mode 100644 packages/apps/postgres/tests/init_script_runtime_password_test.yaml create mode 100644 packages/apps/postgres/tests/managed_roles_cluster_test.yaml create mode 100644 packages/apps/postgres/tests/no_tenant_password_test.yaml create mode 100644 packages/apps/postgres/tests/preflight_test.yaml diff --git a/api/apps/v1alpha1/postgresql/types.go b/api/apps/v1alpha1/postgresql/types.go index 76e62b179..95b0a57c1 100644 --- a/api/apps/v1alpha1/postgresql/types.go +++ b/api/apps/v1alpha1/postgresql/types.go @@ -65,7 +65,7 @@ type ConfigSpec struct { // Read-replica autoscaling configuration. // +kubebuilder:default:={} Autoscaling Autoscaling `json:"autoscaling"` - // Users configuration map. Passwords are always auto-generated and stored in the `-credentials` Secret; they cannot be set from values — read a user's password from that Secret. A `password` left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret. + // Users configuration map. Each user is a PostgreSQL role the operator manages from an account Secret the platform keeps. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once and stores only its SCRAM verifier, and a revoke retires the password without issuing one. A `password` key here is ignored and draws an admission warning. A password set inside PostgreSQL is reverted by the operator. // +kubebuilder:default:={} Users map[string]User `json:"users,omitempty"` // Databases configuration map. The PostgreSQL system databases `postgres`, `template0` and `template1` are refused. @@ -243,9 +243,9 @@ type TLS struct { } type User struct { - // Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself, so this is required alongside `createRole` to provision a privileged service role. + // Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself. BypassRls bool `json:"bypassRls,omitempty"` - // Whether the user can create and manage roles (CREATEROLE). Requires PostgreSQL 16 or newer. Setting it back to `false` withdraws the attribute only: the roles the user created, and its ADMIN and SET memberships in them, stay. Once any user has held it, the chart no longer adopts an existing role it did not create, so a user or database declared later under the name of such a role fails the init job until a platform administrator drops that role. + // Not supported while users are CloudNativePG managed roles: the chart refuses to render when it is true, and a release that sets it keeps its previous chart version until it is false. CloudNativePG revokes every membership a managed role is not declared to hold, including the one PostgreSQL gives a CREATEROLE user in each role it creates. Setting it to false withdraws CREATEROLE from a role that held it. CreateRole bool `json:"createRole,omitempty"` // Whether the user has replication privileges. Replication bool `json:"replication,omitempty"` diff --git a/hack/check-postgres-app-owner-password.bats b/hack/check-postgres-app-owner-password.bats deleted file mode 100644 index 724bb714c..000000000 --- a/hack/check-postgres-app-owner-password.bats +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/env bats -# Unit test: on a fresh install, packages/apps/postgres hands CNPG the same -# users.app password it stores in -credentials. -# -# The password is generated at render time, so the two Secrets can only be -# compared within one render. helm-unittest asserts each document against a -# fixed value and has no way to compare one document with another, so a chart -# generating two independent passwords would still pass the chart's own suite. - -load test_helper - -REPO_ROOT="$(cd "$(dirname "${BATS_TEST_FILENAME:-$0}")/.." && pwd)" -CHART="$REPO_ROOT/packages/apps/postgres" - -@test "a fresh users.app gets one generated password in both Secrets" { - rendered="$BATS_TEST_TMPDIR/init-script.yaml" - helm template pg "$CHART" --namespace tenant-test \ - --set-json '_cluster={"scheduling":{}}' --set-json 'users={"app":{}}' \ - --show-only templates/init-script.yaml > "$rendered" - - app=$(yq -e 'select(.kind == "Secret" and .metadata.name == "pg-credentials").stringData.app' "$rendered") - owner=$(yq -e 'select(.kind == "Secret" and .metadata.name == "pg-app-owner").stringData.password' "$rendered") - [ -n "$app" ] || { echo "no generated password for app in pg-credentials" >&2; return 1; } - [ "$app" = "$owner" ] || { printf 'pg-credentials app: %s\npg-app-owner password: %s\n' "$app" "$owner" >&2; return 1; } -} diff --git a/hack/e2e-chainsaw/endpointattachment/chainsaw-test.yaml b/hack/e2e-chainsaw/endpointattachment/chainsaw-test.yaml index 772ef6e65..ee7b939f3 100644 --- a/hack/e2e-chainsaw/endpointattachment/chainsaw-test.yaml +++ b/hack/e2e-chainsaw/endpointattachment/chainsaw-test.yaml @@ -68,6 +68,26 @@ spec: metadata: name: postgres-ea-b-rw (subsets[0].addresses[0].ip != null): true + # The probes below mint testuser's password, which needs the Credential + # cozystack-controller keeps for each application user. + - assert: + timeout: 2m + resource: + apiVersion: core.cozystack.io/v1alpha1 + kind: Credential + metadata: + name: postgres-ea-a.testuser + spec: + user: testuser + - assert: + timeout: 2m + resource: + apiVersion: core.cozystack.io/v1alpha1 + kind: Credential + metadata: + name: postgres-ea-b.testuser + spec: + user: testuser # Lineage: ea-b's primary is tenant-facing, but not ea-a's, so an attachment # naming ea-a is refused and renders nothing. @@ -121,18 +141,17 @@ spec: (addresses[0] != null): true (claimName != null): true - script: - timeout: 2m + timeout: 4m content: | set -eu ip=$(kubectl -n "$NAMESPACE" get endpointattachments.local.sdn.cozystack.io ea-a-ro -o jsonpath='{.status.addresses[0]}') pod=$(kubectl -n "$NAMESPACE" get pod -l cnpg.io/cluster=postgres-ea-a,cnpg.io/instanceRole=primary -o name | head -n1) - # The chart generates each user's password into its credentials Secret. - pw=$(kubectl get secret postgres-ea-a-credentials --namespace "$NAMESPACE" --output jsonpath='{.data.testuser}' | base64 -d) # The attached address must answer as a replica, not as the primary # the pod itself is: "t" from pg_is_in_recovery() proves the - # -ro selector was mirrored, not the -rw one. - kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \ - env PGPASSWORD="$pw" psql -h "$ip" -U testuser -d testdb -tAc 'SELECT pg_is_in_recovery()' + # -ro selector was mirrored, not the -rw one. The wait is on the + # application's own -ro Service, so the replica already has the + # minted password when the address is asked. + ./query-as-testuser.sh postgres-ea-a "$pod" postgres-ea-a-ro "$ip" 'SELECT pg_is_in_recovery()' check: ($error == null): true (trim_space($stdout)): "t" @@ -207,7 +226,7 @@ spec: phase: Attached claimName: ea-held - script: - timeout: 2m + timeout: 4m content: | set -eu ip=$(kubectl get ipaddressclaims.local.sdn.cozystack.io ea-held --namespace "$NAMESPACE" --output jsonpath='{.metadata.annotations.e2e\.cozystack\.io/reserved-address}') @@ -217,9 +236,7 @@ spec: pod=$(kubectl -n "$NAMESPACE" get pod -l cnpg.io/cluster=postgres-ea-b -o name | head -n1) # Probe from ea-b's pod so the answer cannot come from the local # instance: the reserved address must reach ea-a's primary. - pw=$(kubectl get secret postgres-ea-a-credentials --namespace "$NAMESPACE" --output jsonpath='{.data.testuser}' | base64 -d) - kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \ - env PGPASSWORD="$pw" psql -h "$ip" -U testuser -d testdb -tAc "SELECT current_setting('cluster_name') || ' ' || pg_is_in_recovery()" + ./query-as-testuser.sh postgres-ea-a "$pod" postgres-ea-a-rw "$ip" "SELECT current_setting('cluster_name') || ' ' || pg_is_in_recovery()" check: ($error == null): true (trim_space($stdout)): "postgres-ea-a false" @@ -277,7 +294,7 @@ spec: phase: Attached claimName: ea-held - script: - timeout: 2m + timeout: 4m content: | set -eu ip=$(kubectl get ipaddressclaims.local.sdn.cozystack.io ea-held --namespace "$NAMESPACE" --output jsonpath='{.metadata.annotations.e2e\.cozystack\.io/reserved-address}') @@ -285,9 +302,7 @@ spec: got=$(kubectl -n "$NAMESPACE" get endpointattachments.local.sdn.cozystack.io ea-b-rw-held -o jsonpath='{.status.addresses[0]}') [ "$got" = "$ip" ] pod=$(kubectl -n "$NAMESPACE" get pod -l cnpg.io/cluster=postgres-ea-a,cnpg.io/instanceRole=primary -o name | head -n1) - pw=$(kubectl get secret postgres-ea-b-credentials --namespace "$NAMESPACE" --output jsonpath='{.data.testuser}' | base64 -d) - kubectl -n "$NAMESPACE" exec "$pod" -c postgres -- \ - env PGPASSWORD="$pw" psql -h "$ip" -U testuser -d testdb -tAc "SELECT current_setting('cluster_name') || ' ' || pg_is_in_recovery()" + ./query-as-testuser.sh postgres-ea-b "$pod" postgres-ea-b-rw "$ip" "SELECT current_setting('cluster_name') || ' ' || pg_is_in_recovery()" check: ($error == null): true (trim_space($stdout)): "postgres-ea-b false" diff --git a/hack/e2e-chainsaw/endpointattachment/query-as-testuser.sh b/hack/e2e-chainsaw/endpointattachment/query-as-testuser.sh new file mode 100755 index 000000000..75545c9ed --- /dev/null +++ b/hack/e2e-chainsaw/endpointattachment/query-as-testuser.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# Usage: query-as-testuser.sh +# +# Mints a password for testuser of , waits until accepts +# it, then runs once against from and prints the answer. +# +# The chart keeps no password a tenant can read back, so each probe mints its +# own. A mint replaces the previous password, and CloudNativePG applies it +# live, on a replica once replay reaches it; the wait is on the application's +# own Service, so the address under test is queried exactly once and a wrong +# answer from it is never retried away. The wait carries its own deadline: the +# step's ceiling kills only the calling shell, which would leave this loop +# running and holding the step's output open. +set -euo pipefail + +release=$1 pod=$2 ready=$3 host=$4 query=$5 + +pw=$(kubectl create --raw "/apis/core.cozystack.io/v1alpha1/namespaces/$NAMESPACE/credentials/$release.testuser/mint" \ + --filename <(printf '{"apiVersion":"core.cozystack.io/v1alpha1","kind":"CredentialRequest"}') \ + | jq --raw-output '.status.password') +[ "${#pw}" -eq 32 ] || { echo "minted password has ${#pw} characters, want 32" >&2; exit 1; } + +# The password goes to psql on stdin: exec arguments travel in the request +# URI, which the audit log records at any level. +psql_on() { + printf '%s\n' "$pw" | kubectl --namespace "$NAMESPACE" exec --stdin "$pod" --container postgres -- \ + sh -c 'IFS= read -r PGPASSWORD; export PGPASSWORD; exec psql "$@"' sh \ + -h "$1" -U testuser -d testdb -tAc "$2" +} + +deadline=$((SECONDS + 180)) +until [ "$(psql_on "$ready" 'SELECT 1' 2>/dev/null | tr -d '[:space:]')" = 1 ]; do + if [ "$SECONDS" -ge "$deadline" ]; then + echo "$ready did not accept the password minted for $release.testuser within 180s" >&2 + exit 1 + fi + sleep 5 +done + +psql_on "$host" "$query" diff --git a/packages/apps/postgres/README.md b/packages/apps/postgres/README.md index 915f26298..ce47c9761 100644 --- a/packages/apps/postgres/README.md +++ b/packages/apps/postgres/README.md @@ -277,12 +277,12 @@ For `sslmode=verify-full` to work, the CA bundle retrieved above must be saved t ### Users configuration -| Name | Description | Type | Value | -| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ------- | -| `users` | Users configuration map. Passwords are always auto-generated and stored in the `-credentials` Secret; they cannot be set from values — read a user's password from that Secret. A `password` left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret. | `map[string]object` | `{}` | -| `users[name].replication` | Whether the user has replication privileges. | `bool` | `false` | -| `users[name].createRole` | Whether the user can create and manage roles (CREATEROLE). Requires PostgreSQL 16 or newer. Setting it back to `false` withdraws the attribute only: the roles the user created, and its ADMIN and SET memberships in them, stay. Once any user has held it, the chart no longer adopts an existing role it did not create, so a user or database declared later under the name of such a role fails the init job until a platform administrator drops that role. | `bool` | `false` | -| `users[name].bypassRls` | Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself, so this is required alongside `createRole` to provision a privileged service role. | `bool` | `false` | +| Name | Description | Type | Value | +| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ------- | +| `users` | Users configuration map. Each user is a PostgreSQL role the operator manages from an account Secret the platform keeps. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once and stores only its SCRAM verifier, and a revoke retires the password without issuing one. A `password` key here is ignored and draws an admission warning. A password set inside PostgreSQL is reverted by the operator. | `map[string]object` | `{}` | +| `users[name].replication` | Whether the user has replication privileges. | `bool` | `false` | +| `users[name].createRole` | Not supported while users are CloudNativePG managed roles: the chart refuses to render when it is true, and a release that sets it keeps its previous chart version until it is false. CloudNativePG revokes every membership a managed role is not declared to hold, including the one PostgreSQL gives a CREATEROLE user in each role it creates. Setting it to false withdraws CREATEROLE from a role that held it. | `bool` | `false` | +| `users[name].bypassRls` | Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself. | `bool` | `false` | ### Databases configuration @@ -363,7 +363,16 @@ users: replication: true ``` -Passwords cannot be set here — they are auto-generated and stored in the `-credentials` Secret. Read a user's password with `kubectl get tenantsecret -credentials -o json | jq -r '.data["user1"]' | base64 -d` (a username may contain a `.`, which `jsonpath` would treat as a path step and return nothing). +Passwords cannot be set here. Each user is an account of the Cozystack credentials API: a `Credential` named `.` in `core.cozystack.io/v1alpha1`, where `` is the user name lowercased with every character outside `[a-z0-9-]` replaced by `-`. A mint returns a new password once and replaces the previous one; only its SCRAM verifier is stored, so the password cannot be read back: + +```bash +kubectl create --raw "/apis/core.cozystack.io/v1alpha1/namespaces//credentials/postgres-.user1/mint" \ + -f <(echo '{"apiVersion":"core.cozystack.io/v1alpha1","kind":"CredentialRequest"}') | jq -r .status.password +``` + +A user added to an existing application has no password until the first mint. Names PostgreSQL or CloudNativePG reserve (`postgres`, `streaming_replica`, `pg_*`, `cnpg_*`), the name of a database role (`_admin`, `_readonly`), and two users mapping to one account name are refused. + +Downgrading the platform past the conversion to minted passwords is not supported: the previous chart generates a new password for every account. A manual `helm rollback` of a release to a revision from before the conversion is undone at its next reconcile, and meanwhile the old revision's `-credentials` shows a password that no longer works; mint again once the release is back. ### databases diff --git a/packages/apps/postgres/templates/NOTES.txt b/packages/apps/postgres/templates/NOTES.txt index 214cd79f8..685296e11 100644 --- a/packages/apps/postgres/templates/NOTES.txt +++ b/packages/apps/postgres/templates/NOTES.txt @@ -1,20 +1,11 @@ {{- if and .Values.bootstrap.enabled .Values.users }} WARNING: this PostgreSQL was provisioned as a restore (bootstrap.enabled=true). -The roles recovered from the backup keep their original password hashes, but the -{{ .Release.Name }}-credentials Secret now holds freshly generated passwords that -are NOT yet applied to the database — the init-job that runs ALTER ROLE is skipped -while bootstrap is on. While bootstrap is on the credentials Secret carries the -annotation postgres.cozystack.io/credentials-pending: "true". That flag tracks only -the bootstrap phase, not the whole convergence: the restore driver REMOVES it when -it clears bootstrap.enabled, and that same reconcile is what triggers the init-job -— so the flag is already gone for the short window before the init-job has finished -applying the passwords. Do not read a missing flag as "converged". - -The restore driver clears bootstrap.enabled automatically once recovery is healthy, -and the next reconcile runs the init-job to apply the Secret's passwords onto the -recovered roles — no action is required. Confirm convergence by logging in as an -application user rather than by the flag; until a login with the Secret's password -succeeds, do not treat the advertised application passwords as usable — the database -is reachable as the CloudNativePG superuser in the meantime. +The roles recovered from the backup keep the password hashes of the source. Each +declared user is a managed role of the Cluster pointing at its account Secret, +and CloudNativePG applies the stored value from that Secret once the recovered +primary is up, so a password minted on this application's credentials +(core.cozystack.io) takes effect without any action here. A restored account +whose Secret was seeded with this application has no issued password yet: mint +one, and poll a login with it until it succeeds. {{- end }} diff --git a/packages/apps/postgres/templates/_accounts.tpl b/packages/apps/postgres/templates/_accounts.tpl new file mode 100644 index 000000000..7810840e2 --- /dev/null +++ b/packages/apps/postgres/templates/_accounts.tpl @@ -0,0 +1,62 @@ +{{/* + Account Secret naming, which must match pkg/credentials/account.MapName: + each user's CredentialTemplate is named ., where + is the user name lowercased with every character outside + [a-z0-9-] replaced by "-", and the controller writes its account Secret as +