feat(credentials-migrate): read passwords from per-account Secrets

Some charts keep each tenant password in a Secret of its own rather
than under the user name in <release>-credentials: MongoDB renders
<release>-user-<name> with a password key, which the operator reads.
The conversion has to seed account Secrets from there, and finish
has to remove those Secrets if Helm leaves one behind, while the
platform Secret of such a kind stays untouched.

Two flags describe the source, so that a kind keyed by something
other than the user name can reuse them: --source-key names the key
holding the password (the user name when empty), and
--source-per-account reads it from <release><source-suffix><user>
rather than from the single source Secret. A per-account Secret is
never keyed by user name, so the second requires the first.

Assisted-by: LLM
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
This commit is contained in:
Andrei Kvapil committed 2026-12-01 14:30:33 +01:00
1 parent d5c6170892
commit e6a7973185
2 files changed
+183 -28

No files matched your search

+100 -28
View File
@@ -72,23 +72,25 @@ const (
// 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
reservedUsers stringFlags
skipAccounts stringFlags
labels labelFlags
valuesPath string
sourceSuffix string
platformKeys stringFlags
rotateKeys stringFlags
stateNamespace string
actor string
timeout time.Duration
holdRollouts stringFlags
holdTimeout time.Duration
migration int
kind string
formatName string
accountsPath string
refuseFlags stringFlags
reservedUsers stringFlags
skipAccounts stringFlags
labels labelFlags
valuesPath string
sourceSuffix string
sourceKey string
sourcePerAccount bool
platformKeys stringFlags
rotateKeys stringFlags
stateNamespace string
actor string
timeout time.Duration
holdRollouts stringFlags
holdTimeout time.Duration
}
type labelFlags map[string]string
@@ -156,6 +158,8 @@ func run(args []string) error {
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.StringVar(&o.sourceKey, "source-key", "", "key of the source Secret holding an account's password; empty means the user name")
fs.BoolVar(&o.sourcePerAccount, "source-per-account", false, "the chart kept one source Secret per account, named <release><source-suffix><user>, with the password under --source-key")
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")
@@ -169,6 +173,9 @@ func run(args []string) error {
if o.migration == 0 || o.kind == "" || !format.Known(o.formatName) {
return errors.New("--migration, --kind and a built-in --format are required")
}
if o.sourcePerAccount && o.sourceKey == "" {
return errors.New("--source-per-account needs --source-key: a per-account Secret is not keyed by user name")
}
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)
@@ -384,14 +391,17 @@ func (m *migrator) seedRelease(ctx context.Context, hr *helmv2.HelmRelease) erro
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
var source *corev1.Secret
if !m.o.sourcePerAccount {
source = &corev1.Secret{}
if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: hr.Name + m.o.sourceSuffix}, source); err != nil {
if !apierrors.IsNotFound(err) {
return err
}
if len(accounts) > 0 {
fmt.Printf("%s/%s: %s%s is gone; its accounts get a Secret at their first mint\n", hr.Namespace, hr.Name, hr.Name, m.o.sourceSuffix)
return nil
}
}
}
now := metav1.NewTime(m.now())
@@ -417,9 +427,12 @@ func (m *migrator) seedRelease(ctx context.Context, hr *helmv2.HelmRelease) erro
case !apierrors.IsNotFound(err):
return err
}
plaintext, ok := source.Data[acc.Username]
plaintext, from, ok, err := m.plaintext(ctx, hr, source, acc.Username)
if err != nil {
return err
}
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)
fmt.Printf("%s/%s: no password for %q in %s; the account gets a Secret at its first mint\n", hr.Namespace, hr.Name, acc.Username, from)
complete = false
continue
}
@@ -427,7 +440,7 @@ func (m *migrator) seedRelease(ctx context.Context, hr *helmv2.HelmRelease) erro
// 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)
fmt.Printf("%s/%s: the password for %q in %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, from, m.o.formatName)
complete = false
continue
}
@@ -504,6 +517,37 @@ func (m *migrator) addValuesFrom(ctx context.Context, hr *helmv2.HelmRelease, ac
return m.c.Patch(ctx, hr, patch)
}
// plaintext returns the chart-generated password of one account and the name
// of the Secret it was looked up in: the release's single source Secret or,
// with --source-per-account, the account's own Secret
// <release><source-suffix><user>, as charts that render one Secret per user
// keep it. The password is under --source-key, or under the user name when
// that is empty. A missing Secret or key is reported as not found.
func (m *migrator) plaintext(ctx context.Context, hr *helmv2.HelmRelease, source *corev1.Secret, user string) ([]byte, string, bool, error) {
key := m.o.sourceKey
if key == "" {
key = user
}
if !m.o.sourcePerAccount {
v, ok := source.Data[key]
return v, source.Name, ok, nil
}
name := m.perAccountSource(hr, user)
sec := &corev1.Secret{}
if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: name}, sec); err != nil {
if apierrors.IsNotFound(err) {
return nil, name, false, nil
}
return nil, name, false, err
}
v, ok := sec.Data[key]
return v, name, ok, nil
}
func (m *migrator) perAccountSource(hr *helmv2.HelmRelease, user string) string {
return hr.Name + m.o.sourceSuffix + user
}
// 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,
@@ -607,6 +651,9 @@ func (m *migrator) stripPasswords(ctx context.Context, hr *helmv2.HelmRelease) e
// stay in its data otherwise, and the Secret itself when no platform key
// remains.
func (m *migrator) retireSource(ctx context.Context, hr *helmv2.HelmRelease) error {
if m.o.sourcePerAccount {
return m.retirePerAccountSources(ctx, hr)
}
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) {
@@ -765,6 +812,31 @@ func (m *migrator) rotatePlatformKeys(ctx context.Context, hr *helmv2.HelmReleas
return nil
}
// retirePerAccountSources deletes the per-account source Secrets of the
// declared accounts. The converted chart no longer renders them, so Helm has
// usually pruned them at the switch; this removes one Helm left behind.
func (m *migrator) retirePerAccountSources(ctx context.Context, hr *helmv2.HelmRelease) error {
accounts, err := m.o.resolveAccounts(hr)
if err != nil {
return err
}
for _, acc := range accounts {
sec := &corev1.Secret{}
name := m.perAccountSource(hr, acc.Username)
if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: name}, sec); err != nil {
if apierrors.IsNotFound(err) {
continue
}
return err
}
if err := m.c.Delete(ctx, sec, client.Preconditions{UID: &sec.UID}); err != nil && !apierrors.IsNotFound(err) {
return err
}
fmt.Printf("%s/%s: deleted %s\n", hr.Namespace, hr.Name, name)
}
return nil
}
func (m *migrator) releases(ctx context.Context) ([]helmv2.HelmRelease, error) {
list := &helmv2.HelmReleaseList{}
if err := m.c.List(ctx, list, client.MatchingLabels{
+83
View File
@@ -802,3 +802,86 @@ func TestResolveAccountsSkipsBeforeMapping(t *testing.T) {
t.Fatalf("accounts = %+v, want only web", got)
}
}
// A chart that renders one Secret per user, as MongoDB's does, is migrated
// from <release><source-suffix><user> under --source-per-account, and finish
// deletes what Helm left of those Secrets while the platform Secret stays.
func TestSeedAndRetirePerAccountSources(t *testing.T) {
ctx := context.Background()
perUser := func(user, pass string) *corev1.Secret {
return &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{Name: "postgres-orders-user-" + user, Namespace: "tenant-foo"},
Data: map[string][]byte{"password": []byte(pass)},
}
}
hr := release(`{"users":{"web":{},"api":{},"ghost":{}}}`, "0.1.0", true)
m := newMigrator(t, hr, perUser("web", "hunter2"), perUser("api", "s3cret"), sourceSecret(map[string]string{"username": "databaseAdmin", "password": "adm"}))
m.o.formatName = format.Plaintext
m.o.sourceSuffix = "-user-"
m.o.sourceKey = "password"
m.o.sourcePerAccount = true
m.o.labels = labelFlags{}
if err := m.seed(ctx); err != nil {
t.Fatal(err)
}
for _, c := range []struct{ secret, user, plain string }{{"postgres-orders.web.account", "web", "hunter2"}, {"postgres-orders.api.account", "api", "s3cret"}} {
sec, ok := m.secret(t, c.secret)
if !ok {
t.Fatalf("%s not written", c.secret)
}
if string(sec.Data[account.UsernameKey]) != c.user || string(sec.Data[account.PasswordKey]) != c.plain || sec.Annotations[account.FormatAnnotation] != format.Plaintext {
t.Fatalf("%s = %+v %q", c.secret, sec.ObjectMeta, sec.Data)
}
}
if _, ok := m.secret(t, "postgres-orders.ghost.account"); ok {
t.Fatal("an account without a per-user Secret waits for a mint")
}
cur := &helmv2.HelmRelease{}
if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil {
t.Fatal(err)
}
if cur.Annotations[account.SeedAnnotation] == "true" {
t.Fatal("a release with an account left without a Secret must not be marked for seeding")
}
if err := m.retireSource(ctx, cur); err != nil {
t.Fatal(err)
}
for _, name := range []string{"postgres-orders-user-web", "postgres-orders-user-api"} {
if _, ok := m.secret(t, name); ok {
t.Fatalf("%s must be deleted", name)
}
}
if _, ok := m.secret(t, "postgres-orders-credentials"); !ok {
t.Fatal("the platform Secret is not a per-account source and must stay")
}
if _, ok := m.secret(t, "postgres-orders.web.account"); !ok {
t.Fatal("the account Secret must stay")
}
}
func TestSeedMarksAReleaseWithoutUsersFromPerAccountSources(t *testing.T) {
ctx := context.Background()
m := newMigrator(t, release(`{"users":{}}`, "0.1.0", true))
m.o.formatName = format.Plaintext
m.o.sourceSuffix = "-user-"
m.o.sourceKey = "password"
m.o.sourcePerAccount = 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 TestRunRefusesPerAccountSourcesWithoutAKey(t *testing.T) {
err := run([]string{"seed", "--migration=67", "--kind=MongoDB", "--format=plaintext", "--source-per-account"})
if err == nil || !strings.Contains(err.Error(), "--source-key") {
t.Fatalf("err = %v", err)
}
}