mirror of
https://github.com/cozystack/cozystack.git
synced 2026-12-06 07:03:45 +09:00
Redis and Valkey have no accounts map: one default user exists while authEnabled is on, and its password sits under the single key password of <release>-auth. The conversion read accounts only from the keys of a values map. --fixed-account names the users such a chart always renders, and --enabled-flag the boolean that switches them off; unset counts as true, the chart default, and a non-boolean leaves the release out rather than guess what the chart renders. The password key comes from the existing --source-key, which already covers a source not keyed by user name, rather than from a flag of its own. Assisted-by: LLM Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
1141 lines
44 KiB
Go
1141 lines
44 KiB
Go
// SPDX-License-Identifier: Apache-2.0
|
||
|
||
package main
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"strings"
|
||
"testing"
|
||
"time"
|
||
|
||
helmv2 "github.com/fluxcd/helm-controller/api/v2"
|
||
appsv1 "k8s.io/api/apps/v1"
|
||
corev1 "k8s.io/api/core/v1"
|
||
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
|
||
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
||
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"
|
||
|
||
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
|
||
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
|
||
corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1"
|
||
"github.com/cozystack/cozystack/pkg/credentials/account"
|
||
"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)
|
||
}
|
||
if err := appsv1.AddToScheme(scheme); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := cozyv1alpha1.AddToScheme(scheme); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
b := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objs...).WithStatusSubresource(&helmv2.HelmRelease{})
|
||
if funcs != nil {
|
||
b = b.WithInterceptorFuncs(*funcs)
|
||
}
|
||
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, holdTimeout: -time.Second,
|
||
}
|
||
return &migrator{c: c, o: o, now: func() time.Time { return time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC) }}
|
||
}
|
||
|
||
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": "IX"}))
|
||
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")
|
||
}
|
||
}
|
||
|
||
func TestSeedLeavesOutAReleaseWithAReservedUser(t *testing.T) {
|
||
ctx := context.Background()
|
||
m := newMigrator(t, release(`{"users":{"web":{},"backup":{}}}`, "0.1.0", true), sourceSecret(map[string]string{"web": "hunter2", "backup": "platform"}))
|
||
m.o.reservedUsers = stringFlags{"backup", "default"}
|
||
if err := m.seed(ctx); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
st, err := m.loadState(ctx)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if why, left := st.Skipped["tenant-foo/postgres-orders"]; !left || !strings.Contains(why, "reserves") {
|
||
t.Fatalf("state = %+v, want the release left out for the reserved name", st)
|
||
}
|
||
for _, name := range []string{"postgres-orders.web.account", "postgres-orders.backup.account"} {
|
||
if _, ok := m.secret(t, name); ok {
|
||
t.Fatalf("%s: a release the converted chart refuses must not be converted in part", name)
|
||
}
|
||
}
|
||
}
|
||
|
||
// With a values path, the hook gives the release the controller's valuesFrom
|
||
// entries ahead of the switch, so the converted chart's first render already
|
||
// carries every stored value; other entries keep their place.
|
||
func TestSeedAddsTheAccountValuesFrom(t *testing.T) {
|
||
ctx := context.Background()
|
||
hr := release(`{"users":{"web":{},"Api.1":{}}}`, "0.1.0", true)
|
||
hr.Spec.ValuesFrom = []helmv2.ValuesReference{
|
||
{Kind: "Secret", Name: "cozystack-values"},
|
||
account.ValuesFrom("postgres-orders.gone.account", "_accounts", "gone"),
|
||
}
|
||
m := newMigrator(t, hr, sourceSecret(map[string]string{"web": "hunter2", "Api.1": "secret"}))
|
||
m.o.valuesPath = "_accounts"
|
||
if err := m.seed(ctx); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
cur := &helmv2.HelmRelease{}
|
||
if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
want := []helmv2.ValuesReference{
|
||
{Kind: "Secret", Name: "cozystack-values"},
|
||
account.ValuesFrom("postgres-orders.api-1.account", "_accounts", "Api.1"),
|
||
account.ValuesFrom("postgres-orders.web.account", "_accounts", "web"),
|
||
}
|
||
if len(cur.Spec.ValuesFrom) != len(want) {
|
||
t.Fatalf("valuesFrom = %+v", cur.Spec.ValuesFrom)
|
||
}
|
||
for i := range want {
|
||
if cur.Spec.ValuesFrom[i] != want[i] {
|
||
t.Fatalf("valuesFrom[%d] = %+v, want %+v", i, cur.Spec.ValuesFrom[i], want[i])
|
||
}
|
||
}
|
||
if !strings.HasPrefix(want[2].TargetPath, "_accounts.u") || !want[2].Optional {
|
||
t.Fatalf("entry = %+v", want[2])
|
||
}
|
||
|
||
// Without a values path the release's valuesFrom is left as it is.
|
||
hr2 := release(`{"users":{"web":{}}}`, "0.1.0", true)
|
||
m = newMigrator(t, hr2, sourceSecret(map[string]string{"web": "hunter2"}))
|
||
if err := m.seed(ctx); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr2), cur); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if len(cur.Spec.ValuesFrom) != 0 {
|
||
t.Fatalf("valuesFrom = %+v, want none", cur.Spec.ValuesFrom)
|
||
}
|
||
}
|
||
|
||
func rotationFixture(t *testing.T, suspended bool, annotations map[string]string) (*migrator, *helmv2.HelmRelease) {
|
||
t.Helper()
|
||
hr := release(`{"users":{"web":{}}}`, "0.2.0", true)
|
||
hr.Spec.Suspend = suspended
|
||
hr.Annotations = annotations
|
||
m := newMigrator(t, hr, sourceSecret(map[string]string{"backup": "tenant-readable"}))
|
||
m.o.platformKeys = stringFlags{"backup"}
|
||
m.o.rotateKeys = stringFlags{"backup"}
|
||
return m, hr
|
||
}
|
||
|
||
func TestRotatePlatformKeysOnceAndForcesAnUpgrade(t *testing.T) {
|
||
ctx := context.Background()
|
||
m, hr := rotationFixture(t, false, nil)
|
||
if err := m.rotatePlatformKeys(ctx, hr); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
sec, _ := m.secret(t, "postgres-orders-credentials")
|
||
first := string(sec.Data["backup"])
|
||
if first == "tenant-readable" || len(first) != 32 || sec.Annotations[RotatedAnnotation] == "" {
|
||
t.Fatalf("source = %v %v", sec.Annotations, len(first))
|
||
}
|
||
cur := &helmv2.HelmRelease{}
|
||
if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if cur.Spec.Suspend || cur.Annotations[SuspendedByAnnotation] != "" {
|
||
t.Fatalf("the suspension the rotation set must be lifted: %+v", cur.Annotations)
|
||
}
|
||
if at := cur.Annotations["reconcile.fluxcd.io/forceAt"]; at == "" || at != cur.Annotations["reconcile.fluxcd.io/requestedAt"] {
|
||
t.Fatalf("want a forced upgrade, annotations = %v", cur.Annotations)
|
||
}
|
||
|
||
// A rerun does not rotate twice.
|
||
if err := m.rotatePlatformKeys(ctx, cur); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
sec, _ = m.secret(t, "postgres-orders-credentials")
|
||
if string(sec.Data["backup"]) != first {
|
||
t.Fatal("a rerun must not rotate again")
|
||
}
|
||
}
|
||
|
||
// A run stopped between the suspension and the Secret write is finished by
|
||
// the next one, which also lifts the suspension it left.
|
||
func TestRotatePlatformKeysRecoversAnInterruptedRun(t *testing.T) {
|
||
ctx := context.Background()
|
||
m, hr := rotationFixture(t, true, map[string]string{SuspendedByAnnotation: "64"})
|
||
if err := m.rotatePlatformKeys(ctx, hr); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
sec, _ := m.secret(t, "postgres-orders-credentials")
|
||
if string(sec.Data["backup"]) == "tenant-readable" {
|
||
t.Fatal("the rotation must complete")
|
||
}
|
||
cur := &helmv2.HelmRelease{}
|
||
if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if cur.Spec.Suspend {
|
||
t.Fatal("the suspension an earlier run set must be lifted")
|
||
}
|
||
}
|
||
|
||
// A release someone else suspended stays suspended and is left out with no
|
||
// force request, which helm-controller would spend while it is suspended; the
|
||
// rerun after the resume forces the upgrade, once.
|
||
func TestRotatePlatformKeysKeepsAForeignSuspension(t *testing.T) {
|
||
ctx := context.Background()
|
||
m, hr := rotationFixture(t, true, nil)
|
||
if err := m.rotatePlatformKeys(ctx, hr); err == nil || !strings.Contains(err.Error(), "suspended by someone else") {
|
||
t.Fatalf("err = %v", err)
|
||
}
|
||
cur := &helmv2.HelmRelease{}
|
||
if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if !cur.Spec.Suspend || cur.Annotations["reconcile.fluxcd.io/forceAt"] != "" || cur.Annotations["reconcile.fluxcd.io/requestedAt"] != "" {
|
||
t.Fatalf("suspend = %v, annotations = %v", cur.Spec.Suspend, cur.Annotations)
|
||
}
|
||
sec, _ := m.secret(t, "postgres-orders-credentials")
|
||
rotated := string(sec.Data["backup"])
|
||
if rotated == "tenant-readable" || sec.Annotations[ForcedAnnotation] != "" {
|
||
t.Fatalf("source = %v", sec.Annotations)
|
||
}
|
||
|
||
// Resumed: the rerun forces the upgrade without rotating again.
|
||
patch := client.MergeFrom(cur.DeepCopy())
|
||
cur.Spec.Suspend = false
|
||
if err := m.c.Patch(ctx, cur, patch); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := m.rotatePlatformKeys(ctx, cur); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
forceAt := cur.Annotations["reconcile.fluxcd.io/forceAt"]
|
||
if forceAt == "" || forceAt != cur.Annotations["reconcile.fluxcd.io/requestedAt"] {
|
||
t.Fatalf("want a forced upgrade, annotations = %v", cur.Annotations)
|
||
}
|
||
sec, _ = m.secret(t, "postgres-orders-credentials")
|
||
if string(sec.Data["backup"]) != rotated || sec.Annotations[ForcedAnnotation] != sec.Annotations[RotatedAnnotation] {
|
||
t.Fatalf("source = %v", sec.Annotations)
|
||
}
|
||
|
||
// Forced once: a further rerun leaves the request alone.
|
||
m.now = func() time.Time { return time.Date(2026, 10, 15, 12, 0, 0, 0, time.UTC) }
|
||
if err := m.rotatePlatformKeys(ctx, cur); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := m.c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if cur.Annotations["reconcile.fluxcd.io/forceAt"] != forceAt {
|
||
t.Fatal("a rerun after the forced upgrade must not force again")
|
||
}
|
||
}
|
||
|
||
// rotationFinishFixture is a seeded release on the converted chart whose
|
||
// values still carry a password and whose source holds a platform key due
|
||
// for rotation; patches of the release go through onPatch first.
|
||
func rotationFinishFixture(t *testing.T, onPatch func(c client.WithWatch, hr *helmv2.HelmRelease, data []byte) error) *migrator {
|
||
t.Helper()
|
||
funcs := &interceptor.Funcs{Patch: func(ctx context.Context, c client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error {
|
||
if hr, ok := obj.(*helmv2.HelmRelease); ok && onPatch != nil {
|
||
data, err := patch.Data(obj)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if err := onPatch(c, hr, data); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
return c.Patch(ctx, obj, patch, opts...)
|
||
}}
|
||
hr := release(`{"users":{"web":{"password":"leftover"}}}`, "0.1.0", true)
|
||
m := newMigratorWith(t, funcs, hr, sourceSecret(map[string]string{"web": "hunter2", "backup": "tenant-readable"}))
|
||
m.o.platformKeys = stringFlags{"backup"}
|
||
m.o.rotateKeys = stringFlags{"backup"}
|
||
if err := m.seed(context.Background()); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
m.switchChart(t, "0.2.0", true)
|
||
return m
|
||
}
|
||
|
||
// Stripping the passwords from the values starts a render that reads the
|
||
// source with lookup, so the release is suspended before the values change;
|
||
// otherwise that render could write the retired backup password back after
|
||
// the rotation, and nothing would retry.
|
||
func TestFinishSuspendsBeforeTheValuesChange(t *testing.T) {
|
||
ctx := context.Background()
|
||
valuesPatched, unsuspended := false, false
|
||
m := rotationFinishFixture(t, func(c client.WithWatch, hr *helmv2.HelmRelease, data []byte) error {
|
||
if !strings.Contains(string(data), `"values"`) {
|
||
return nil
|
||
}
|
||
valuesPatched = true
|
||
cur := &helmv2.HelmRelease{}
|
||
if err := c.Get(ctx, client.ObjectKeyFromObject(hr), cur); err != nil {
|
||
return err
|
||
}
|
||
if !cur.Spec.Suspend {
|
||
unsuspended = true
|
||
}
|
||
return nil
|
||
})
|
||
if err := m.finish(ctx); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if !valuesPatched {
|
||
t.Fatal("the leftover password must be stripped from the values")
|
||
}
|
||
if unsuspended {
|
||
t.Fatal("the values changed while the release was not suspended for the rotation")
|
||
}
|
||
cur := &helmv2.HelmRelease{}
|
||
if err := m.c.Get(ctx, types.NamespacedName{Namespace: "tenant-foo", Name: "postgres-orders"}, cur); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if cur.Spec.Suspend || cur.Annotations[SuspendedByAnnotation] != "" || cur.Annotations["reconcile.fluxcd.io/forceAt"] == "" {
|
||
t.Fatalf("suspend = %v, annotations = %v", cur.Spec.Suspend, cur.Annotations)
|
||
}
|
||
sec, _ := m.secret(t, "postgres-orders-credentials")
|
||
if string(sec.Data["backup"]) == "tenant-readable" {
|
||
t.Fatal("the backup password must be rotated")
|
||
}
|
||
}
|
||
|
||
// A suspension that does not persist leaves the release out before its
|
||
// values change or its platform password is rotated.
|
||
func TestFinishLeavesOutAReleaseThatDoesNotStaySuspended(t *testing.T) {
|
||
ctx := context.Background()
|
||
m := rotationFinishFixture(t, func(_ client.WithWatch, hr *helmv2.HelmRelease, _ []byte) error {
|
||
hr.Spec.Suspend = false
|
||
return nil
|
||
})
|
||
err := m.finish(ctx)
|
||
if err == nil || !strings.Contains(err.Error(), "did not stay suspended") {
|
||
t.Fatalf("err = %v", err)
|
||
}
|
||
sec, _ := m.secret(t, "postgres-orders-credentials")
|
||
if string(sec.Data["backup"]) != "tenant-readable" || sec.Annotations[RotatedAnnotation] != "" {
|
||
t.Fatalf("source = %v", sec.Annotations)
|
||
}
|
||
cur := &helmv2.HelmRelease{}
|
||
if err := m.c.Get(ctx, types.NamespacedName{Namespace: "tenant-foo", Name: "postgres-orders"}, cur); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
var values map[string]any
|
||
if err := json.Unmarshal(cur.Spec.Values.Raw, &values); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if _, has := values["users"].(map[string]any)["web"].(map[string]any)["password"]; !has {
|
||
t.Fatal("the values must not change before the suspension holds")
|
||
}
|
||
}
|
||
|
||
func TestRunRefusesARotateKeyThatIsNotAPlatformKey(t *testing.T) {
|
||
err := run([]string{"finish", "--migration=65", "--kind=ClickHouse", "--format=sha256", "--rotate-key=backup"})
|
||
if err == nil || !strings.Contains(err.Error(), "not a --platform-key") {
|
||
t.Fatalf("err = %v", err)
|
||
}
|
||
}
|
||
|
||
func TestSeedSkipsAPlatformAccountInTheUsersMap(t *testing.T) {
|
||
ctx := context.Background()
|
||
// MariaDB keeps root in <release>-credentials and ignores users.root, so
|
||
// the converted chart renders no template for it: the conversion must
|
||
// neither write an account Secret holding root's verifier nor let the key
|
||
// stop the release from being marked for seeding.
|
||
m := newMigrator(t, release(`{"users":{"web":{},"root":{}}}`, "0.1.0", true), sourceSecret(map[string]string{"web": "hunter2", "root": "toor"}))
|
||
m.o.formatName = format.MySQLNative
|
||
m.o.skipAccounts = stringFlags{"root"}
|
||
if err := m.seed(ctx); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if _, ok := m.secret(t, "postgres-orders.root.account"); ok {
|
||
t.Fatal("a skipped account must get no account Secret")
|
||
}
|
||
sec, ok := m.secret(t, "postgres-orders.web.account")
|
||
if !ok {
|
||
t.Fatal("the tenant account must still be migrated")
|
||
}
|
||
if got, want := string(sec.Data[account.PasswordKey]), "*58815970BE77B3720276F63DB198B1FA42E5CC02"; got != want {
|
||
t.Fatalf("stored = %q, want the mysql_native_password hash %q", got, want)
|
||
}
|
||
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 skipped key must not keep the release from being marked for seeding")
|
||
}
|
||
}
|
||
|
||
func TestResolveAccountsSkipsBeforeMapping(t *testing.T) {
|
||
// A skipped key is dropped before the name mapping, so it neither
|
||
// collides with a tenant account nor fails the mapping.
|
||
hr := release(`{"users":{"root":{},"web":{}}}`, "", false)
|
||
got, err := (&options{accountsPath: "users", skipAccounts: stringFlags{"root"}}).resolveAccounts(hr)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if len(got) != 1 || got[0].Username != "web" {
|
||
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)
|
||
}
|
||
}
|
||
|
||
func perAccountSource(name, release, user, password string) *corev1.Secret {
|
||
return &corev1.Secret{
|
||
ObjectMeta: metav1.ObjectMeta{
|
||
Name: name, Namespace: "tenant-foo",
|
||
Labels: map[string]string{"apps.cozystack.io/user-secret": "true"},
|
||
Annotations: map[string]string{account.ReleaseNameAnnotation: release},
|
||
},
|
||
Data: map[string][]byte{account.UsernameKey: []byte(user), account.PasswordKey: []byte(password)},
|
||
}
|
||
}
|
||
|
||
// A chart that kept one Secret per account is read by label and by the Helm
|
||
// release that rendered it, so a sibling release's Secrets in the same
|
||
// namespace never feed this one.
|
||
func TestSeedReadsPerAccountSources(t *testing.T) {
|
||
ctx := context.Background()
|
||
m := newMigrator(t,
|
||
release(`{"users":{"web":{},"Api.1":{}}}`, "0.1.0", true),
|
||
perAccountSource("postgres-orders-web-credentials", "postgres-orders", "web", "hunter2"),
|
||
perAccountSource("postgres-orders-api-1-credentials", "postgres-orders", "Api.1", "secret"),
|
||
perAccountSource("postgres-other-web-credentials", "postgres-other", "web", "sibling"),
|
||
)
|
||
m.o.formatName = format.Plaintext
|
||
m.o.labels = labelFlags{"rabbitmq.com/topology-operator": "true"}
|
||
m.o.sourceSelector = labelFlags{"apps.cozystack.io/user-secret": "true"}
|
||
m.o.sourceKey = account.PasswordKey
|
||
if err := m.seed(ctx); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
for _, c := range []struct{ secret, user, plain string }{{"postgres-orders.web.account", "web", "hunter2"}, {"postgres-orders.api-1.account", "Api.1", "secret"}} {
|
||
sec, ok := m.secret(t, c.secret)
|
||
if !ok {
|
||
t.Fatalf("%s not written", c.secret)
|
||
}
|
||
if string(sec.Data[account.UsernameKey]) != c.user || string(sec.Data[account.PasswordKey]) != c.plain {
|
||
t.Fatalf("%s data = %q", c.secret, sec.Data)
|
||
}
|
||
if sec.Labels["rabbitmq.com/topology-operator"] != "true" || sec.Annotations[account.FormatAnnotation] != format.Plaintext {
|
||
t.Fatalf("%s meta = %+v", c.secret, sec.ObjectMeta)
|
||
}
|
||
}
|
||
hr := &helmv2.HelmRelease{}
|
||
if err := m.c.Get(ctx, types.NamespacedName{Namespace: "tenant-foo", Name: "postgres-orders"}, hr); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if hr.Annotations[account.SeedAnnotation] != "true" {
|
||
t.Fatal("a release whose accounts all got a Secret must be marked for seeding")
|
||
}
|
||
}
|
||
|
||
func TestSeedWithoutPerAccountSourcesLeavesTheReleaseUnmarked(t *testing.T) {
|
||
ctx := context.Background()
|
||
m := newMigrator(t, release(`{"users":{"web":{}}}`, "0.1.0", true))
|
||
m.o.formatName = format.Plaintext
|
||
m.o.sourceSelector = labelFlags{"apps.cozystack.io/user-secret": "true"}
|
||
m.o.sourceKey = account.PasswordKey
|
||
if err := m.seed(ctx); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if _, ok := m.secret(t, "postgres-orders.web.account"); ok {
|
||
t.Fatal("no account Secret can be written without its plaintext")
|
||
}
|
||
hr := &helmv2.HelmRelease{}
|
||
if err := m.c.Get(ctx, types.NamespacedName{Namespace: "tenant-foo", Name: "postgres-orders"}, hr); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if hr.Annotations[account.SeedAnnotation] == "true" {
|
||
t.Fatal("a release whose passwords are gone must not be seeded with random ones")
|
||
}
|
||
}
|
||
|
||
// RabbitMQ's chart default is users: {}, which leaves no source to select.
|
||
func TestSeedMarksAReleaseWithoutUsersFromSelectedSources(t *testing.T) {
|
||
ctx := context.Background()
|
||
m := newMigrator(t, release(`{"users":{}}`, "0.1.0", true))
|
||
m.o.formatName = format.Plaintext
|
||
m.o.sourceSelector = labelFlags{"apps.cozystack.io/user-secret": "true"}
|
||
m.o.sourceKey = account.PasswordKey
|
||
if err := m.seed(ctx); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
hr := &helmv2.HelmRelease{}
|
||
if err := m.c.Get(ctx, types.NamespacedName{Namespace: "tenant-foo", Name: "postgres-orders"}, hr); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if hr.Annotations[account.SeedAnnotation] != "true" {
|
||
t.Fatal("a release without users must be marked, or its first user never gets a Secret")
|
||
}
|
||
}
|
||
|
||
func TestRetireSourceDeletesPerAccountSourcesOfThisReleaseOnly(t *testing.T) {
|
||
ctx := context.Background()
|
||
hr := release(`{"users":{"web":{}}}`, "0.2.0", true)
|
||
m := newMigrator(t, hr,
|
||
perAccountSource("postgres-orders-web-credentials", "postgres-orders", "web", "hunter2"),
|
||
perAccountSource("postgres-other-web-credentials", "postgres-other", "web", "sibling"),
|
||
)
|
||
m.o.sourceSelector = labelFlags{"apps.cozystack.io/user-secret": "true"}
|
||
m.o.sourceKey = account.PasswordKey
|
||
if err := m.retireSource(ctx, hr); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if _, ok := m.secret(t, "postgres-orders-web-credentials"); ok {
|
||
t.Fatal("the release's per-account source must be deleted")
|
||
}
|
||
if _, ok := m.secret(t, "postgres-other-web-credentials"); !ok {
|
||
t.Fatal("a sibling release's Secret must be left alone")
|
||
}
|
||
}
|
||
|
||
func TestHidePlatformSecretsLabelsAnOperatorSecret(t *testing.T) {
|
||
ctx := context.Background()
|
||
hr := release(`{}`, "0.2.0", true)
|
||
admin := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "postgres-orders-default-user", Namespace: "tenant-foo", Labels: map[string]string{
|
||
corev1alpha1.TenantResourceLabelKey: "true", "app.kubernetes.io/name": "orders",
|
||
}}}
|
||
m := newMigrator(t, hr, admin)
|
||
m.o.hideSuffixes = stringFlags{"-default-user", "-missing"}
|
||
if err := m.hidePlatformSecrets(ctx, hr); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
sec, ok := m.secret(t, "postgres-orders-default-user")
|
||
if !ok || sec.Labels[corev1alpha1.TenantResourceLabelKey] != "false" || sec.Labels["app.kubernetes.io/name"] != "orders" {
|
||
t.Fatalf("secret = %+v", sec)
|
||
}
|
||
}
|
||
|
||
func TestRunRefusesTwoWaysToFindPerAccountSources(t *testing.T) {
|
||
err := run([]string{"seed", "--migration=68", "--kind=RabbitMQ", "--format=plaintext", "--source-key=password", "--source-per-account", "--source-selector=apps.cozystack.io/user-secret=true"})
|
||
if err == nil || !strings.Contains(err.Error(), "pass one") {
|
||
t.Fatalf("err = %v", err)
|
||
}
|
||
}
|
||
|
||
// redisMigrator is set up as the Redis conversion runs: one fixed account
|
||
// whose password sits under one key of <release>-auth, switched by
|
||
// authEnabled.
|
||
func redisMigrator(t *testing.T, values string, auth map[string]string) (*migrator, *helmv2.HelmRelease) {
|
||
t.Helper()
|
||
hr := release(values, "0.1.0", true)
|
||
hr.Name = "redis-cache"
|
||
hr.Labels[appsv1alpha1.ApplicationKindLabel] = "Redis"
|
||
hr.Labels[appsv1alpha1.ApplicationNameLabel] = "cache"
|
||
objs := []client.Object{hr}
|
||
if auth != nil {
|
||
sec := sourceSecret(auth)
|
||
sec.Name = "redis-cache-auth"
|
||
objs = append(objs, sec)
|
||
}
|
||
m := newMigrator(t, objs...)
|
||
m.o.kind = "Redis"
|
||
m.o.formatName = format.Plaintext
|
||
m.o.labels = labelFlags{}
|
||
m.o.sourceSuffix = "-auth"
|
||
m.o.fixedAccounts = stringFlags{"default"}
|
||
m.o.sourceKey = "password"
|
||
m.o.enabledFlag = "authEnabled"
|
||
return m, hr
|
||
}
|
||
|
||
func TestSeedFixedAccountFromOneSourceKey(t *testing.T) {
|
||
ctx := context.Background()
|
||
for _, values := range []string{`{}`, `{"authEnabled":true}`} {
|
||
m, hr := redisMigrator(t, values, map[string]string{"password": "s3cret"})
|
||
if err := m.seed(ctx); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
sec, ok := m.secret(t, "redis-cache.default.account")
|
||
if !ok {
|
||
t.Fatalf("%s: the default account Secret was not written", values)
|
||
}
|
||
if string(sec.Data[account.UsernameKey]) != "default" || string(sec.Data[account.PasswordKey]) != "s3cret" || sec.Annotations[account.FormatAnnotation] != format.Plaintext {
|
||
t.Fatalf("%s: account Secret = %+v %q", values, sec.ObjectMeta, sec.Data)
|
||
}
|
||
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.Fatalf("%s: a release whose account got its Secret must be marked for seeding", values)
|
||
}
|
||
}
|
||
}
|
||
|
||
func TestSeedFixedAccountSwitchedOff(t *testing.T) {
|
||
ctx := context.Background()
|
||
m, _ := redisMigrator(t, `{"authEnabled":false}`, nil)
|
||
if err := m.seed(ctx); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if _, ok := m.secret(t, "redis-cache.default.account"); ok {
|
||
t.Fatal("a release with authentication off declares no account")
|
||
}
|
||
st, _ := m.loadState(ctx)
|
||
if st.Releases["tenant-foo/redis-cache"] == nil || len(st.Skipped) != 0 {
|
||
t.Fatalf("state = %+v", st)
|
||
}
|
||
// Turning authentication on later seeds the account, which no client
|
||
// holds a password for yet.
|
||
hr := &helmv2.HelmRelease{}
|
||
if err := m.c.Get(ctx, types.NamespacedName{Namespace: "tenant-foo", Name: "redis-cache"}, hr); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if hr.Annotations[account.SeedAnnotation] != "true" {
|
||
t.Fatal("a release with no account must be marked for seeding")
|
||
}
|
||
}
|
||
|
||
func TestSeedFixedAccountLeavesOutANonBooleanFlag(t *testing.T) {
|
||
ctx := context.Background()
|
||
m, _ := redisMigrator(t, `{"authEnabled":"yes"}`, map[string]string{"password": "s3cret"})
|
||
if err := m.seed(ctx); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
st, _ := m.loadState(ctx)
|
||
if why := st.Skipped["tenant-foo/redis-cache"]; !strings.Contains(why, "not a boolean") {
|
||
t.Fatalf("skipped = %v", st.Skipped)
|
||
}
|
||
if _, ok := m.secret(t, "redis-cache.default.account"); ok {
|
||
t.Fatal("an unresolvable release gets no account Secret")
|
||
}
|
||
}
|
||
|
||
func TestFinishFixedAccountRetiresTheSource(t *testing.T) {
|
||
ctx := context.Background()
|
||
m, hr := redisMigrator(t, `{}`, map[string]string{"password": "s3cret"})
|
||
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)
|
||
}
|
||
if err := m.finish(ctx); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if _, ok := m.secret(t, "redis-cache-auth"); ok {
|
||
t.Fatal("the source Secret must be deleted")
|
||
}
|
||
sec, ok := m.secret(t, "redis-cache.default.account")
|
||
if !ok || string(sec.Data[account.PasswordKey]) != "s3cret" {
|
||
t.Fatal("the account Secret must keep the migrated password")
|
||
}
|
||
}
|