diff --git a/api/apps/v1alpha1/bucket/types.go b/api/apps/v1alpha1/bucket/types.go index 98e8f8551..2b3ad37f9 100644 --- a/api/apps/v1alpha1/bucket/types.go +++ b/api/apps/v1alpha1/bucket/types.go @@ -41,6 +41,8 @@ type ConfigSpec struct { } type User struct { + // Marks a platform account, such as the `system` user of the backup bucket, which backupstrategy-controller sets. Its keys stay in the `--credentials` Secret, which no tenant can read, and are never minted. Clearing it drops the chart-rendered BucketAccess, which revokes those keys, and the user becomes a normal account whose keys are minted through its Credential. Leave it unset for your own users. + Platform bool `json:"platform,omitempty"` // Whether the user has read-only access. Readonly bool `json:"readonly,omitempty"` } diff --git a/api/apps/v1alpha1/rabbitmq/types.go b/api/apps/v1alpha1/rabbitmq/types.go index e9917379d..751af6c5a 100644 --- a/api/apps/v1alpha1/rabbitmq/types.go +++ b/api/apps/v1alpha1/rabbitmq/types.go @@ -46,7 +46,7 @@ type ConfigSpec struct { // RabbitMQ major.minor version to deploy // +kubebuilder:default:="v4.2" Version Version `json:"version"` - // Users configuration map. + // Users configuration map. Each user is a RabbitMQ user that messaging-topology-operator keeps from an account Secret the platform holds. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. The operator applies either to the broker within seconds. A `password` key here is ignored. The administrator in `-default-user` belongs to the platform and is not shown to tenants. // +kubebuilder:default:={} Users map[string]User `json:"users,omitempty"` // Virtual hosts configuration map. @@ -80,8 +80,6 @@ type TLS struct { } type User struct { - // Password for the user. - Password string `json:"password,omitempty"` } type Vhost struct { diff --git a/api/apps/v1alpha1/redis/types.go b/api/apps/v1alpha1/redis/types.go index 2c95eb6cc..602b5203d 100644 --- a/api/apps/v1alpha1/redis/types.go +++ b/api/apps/v1alpha1/redis/types.go @@ -46,7 +46,7 @@ type ConfigSpec struct { // TLS configuration. TLS is opt-in and is not inferred from `external`. // +kubebuilder:default:={} Tls TLS `json:"tls,omitempty"` - // Enable password generation. + // Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password. // +kubebuilder:default:=true AuthEnabled bool `json:"authEnabled"` // Redis `min-replicas-to-write`: the master refuses writes unless at least this many replicas are connected and within `minReplicasMaxLag`. Unset by default, which leaves the Redis default (disabled). With `replicas: 2` and a value of 1 the master rejects writes while its only replica is down, trading availability for a bound on the writes lost if an isolated master is failed over. Replication stays asynchronous, so this bounds the loss, it does not remove it. Must be 0 or more and below `replicas` (a master with `replicas` pods has `replicas - 1` replicas), otherwise every write is refused; the chart refuses such a value. diff --git a/api/apps/v1alpha1/valkey/types.go b/api/apps/v1alpha1/valkey/types.go index f70980030..0f25d0b1c 100644 --- a/api/apps/v1alpha1/valkey/types.go +++ b/api/apps/v1alpha1/valkey/types.go @@ -39,7 +39,7 @@ type ConfigSpec struct { // Valkey major version to deploy // +kubebuilder:default:="v8" Version Version `json:"version"` - // Enable password generation. + // Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password. // +kubebuilder:default:=true AuthEnabled bool `json:"authEnabled"` // Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant. diff --git a/api/v1alpha1/credentialtemplate_types.go b/api/v1alpha1/credentialtemplate_types.go index e23709965..b29e9d479 100644 --- a/api/v1alpha1/credentialtemplate_types.go +++ b/api/v1alpha1/credentialtemplate_types.go @@ -9,6 +9,7 @@ import ( // CredentialTemplateSpec describes one account of an application and the // Secret that stores its password. A kind's chart renders one per account; a // tenant cannot write it. +// +kubebuilder:validation:XValidation:rule="!has(self.bucketAccess) || self.format.name == 'plaintext'",message="a template with bucketAccess stores its keys in the plaintext format" type CredentialTemplateSpec struct { // Username is the account name as the engine knows it. // +kubebuilder:validation:MinLength=1 @@ -30,6 +31,29 @@ type CredentialTemplateSpec struct { // +optional // +kubebuilder:validation:Pattern=`^_[A-Za-z0-9_]*$` ValuesPath string `json:"valuesPath,omitempty"` + + // BucketAccess makes the account engine-issued: it names the BucketAccess + // whose COSI grant issues the account's keys, which the platform cannot + // choose. cozystack-controller creates and owns it, re-creates it on a + // mint, and deletes it on a revoke. The keys are stored as they are + // issued, so the format is plaintext. + // +optional + BucketAccess *CredentialTemplateBucketAccess `json:"bucketAccess,omitempty"` +} + +// CredentialTemplateBucketAccess is the BucketAccess an engine-issued +// template stands for. Its credentials Secret carries the BucketAccess's own name. +// +kubebuilder:validation:XValidation:rule="self.name == oldSelf.name",message="bucketAccess.name is immutable" +type CredentialTemplateBucketAccess struct { + // Name of the BucketAccess and of the Secret the COSI sidecar writes. + // +kubebuilder:validation:MinLength=1 + Name string `json:"name"` + // BucketClaimName is the BucketClaim the access is granted on. + // +kubebuilder:validation:MinLength=1 + BucketClaimName string `json:"bucketClaimName"` + // BucketAccessClassName is the class that sets the access policy. + // +kubebuilder:validation:MinLength=1 + BucketAccessClassName string `json:"bucketAccessClassName"` } // CredentialTemplateFormat names a stored form of a password. @@ -103,6 +127,10 @@ const ( CredentialTemplateSecretConflict = "SecretConflict" // CredentialTemplateUnknownFormat: the format names no built-in format. CredentialTemplateUnknownFormat = "UnknownFormat" + // CredentialTemplateBucketAccessConflict: a BucketAccess at the name an + // engine-issued template names that the controller did not create or + // adopt; it is left alone. + CredentialTemplateBucketAccessConflict = "BucketAccessConflict" ) // +kubebuilder:object:root=true diff --git a/api/v1alpha1/zz_generated.deepcopy.go b/api/v1alpha1/zz_generated.deepcopy.go index dfb0c233d..5ae6a6462 100644 --- a/api/v1alpha1/zz_generated.deepcopy.go +++ b/api/v1alpha1/zz_generated.deepcopy.go @@ -382,6 +382,21 @@ func (in *CredentialTemplate) DeepCopyObject() runtime.Object { return nil } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CredentialTemplateBucketAccess) DeepCopyInto(out *CredentialTemplateBucketAccess) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialTemplateBucketAccess. +func (in *CredentialTemplateBucketAccess) DeepCopy() *CredentialTemplateBucketAccess { + if in == nil { + return nil + } + out := new(CredentialTemplateBucketAccess) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CredentialTemplateFormat) DeepCopyInto(out *CredentialTemplateFormat) { *out = *in @@ -491,6 +506,11 @@ func (in *CredentialTemplateSpec) DeepCopyInto(out *CredentialTemplateSpec) { *out = *in out.Format = in.Format in.Secret.DeepCopyInto(&out.Secret) + if in.BucketAccess != nil { + in, out := &in.BucketAccess, &out.BucketAccess + *out = new(CredentialTemplateBucketAccess) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CredentialTemplateSpec. diff --git a/cmd/cozystack-controller/main.go b/cmd/cozystack-controller/main.go index c296496a9..3239ae15f 100644 --- a/cmd/cozystack-controller/main.go +++ b/cmd/cozystack-controller/main.go @@ -361,6 +361,15 @@ func main() { setupLog.Error(err, "unable to create controller", "controller", "CredentialTemplate") os.Exit(1) } + if err = (&controller.COSICredentialReconciler{ + Client: mgr.GetClient(), + Reader: mgr.GetAPIReader(), + Scheme: mgr.GetScheme(), + Recorder: mgr.GetEventRecorderFor("credentialtemplate-cosi-controller"), + }).SetupWithManager(mgr, caSecretCluster.GetCache()); err != nil { + setupLog.Error(err, "unable to create controller", "controller", "CredentialTemplateCOSI") + os.Exit(1) + } if err = (&controller.CredentialValuesReconciler{ Client: mgr.GetClient(), Reader: mgr.GetAPIReader(), diff --git a/cmd/credentials-migrate/hide.go b/cmd/credentials-migrate/hide.go new file mode 100644 index 000000000..0d7e65bfd --- /dev/null +++ b/cmd/credentials-migrate/hide.go @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "fmt" + "time" + + helmv2 "github.com/fluxcd/helm-controller/api/v2" + corev1 "k8s.io/api/core/v1" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + "github.com/cozystack/cozystack/internal/lineagecontrollerwebhook" + "github.com/cozystack/cozystack/internal/shared/appdefowner" + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" +) + +// waitDefinitionHides waits until the ApplicationDefinition of the kind, as +// it stands in the API, no longer selects sec as tenant-visible. An operator +// that rewrites the Secret replaces its labels, and the lineage webhook then +// stamps it again from that definition, so a label written while the old +// definition is in place is undone by the next such write. The definition +// comes from the kind's rd chart, which upgrades only after the operator it +// depends on is Ready: a new operator rewriting the Secret on its first pass +// lands before it. Labelling only once the new definition hides the Secret +// leaves every later rewrite stamped not tenant-visible as well. +func (m *migrator) waitDefinitionHides(ctx context.Context, hr *helmv2.HelmRelease, sec *corev1.Secret) error { + appName := hr.Labels[appsv1alpha1.ApplicationNameLabel] + deadline := m.now().Add(m.o.timeout) + for { + defs := &cozyv1alpha1.ApplicationDefinitionList{} + if err := m.c.List(ctx, defs); err != nil { + return fmt.Errorf("list ApplicationDefinitions: %w", err) + } + owner := appdefowner.Owners(defs.Items)[m.o.kind] + var def *cozyv1alpha1.ApplicationDefinition + for i := range defs.Items { + if defs.Items[i].Name == owner { + def = &defs.Items[i] + } + } + if !lineagecontrollerwebhook.SecretTenantVisible(ctx, def, appName, hr.Namespace, sec.Name, sec.Labels) { + return nil + } + if m.now().After(deadline) { + return fmt.Errorf("ApplicationDefinition %s still selects %s as tenant-visible after %s; it would be stamped visible again at the operator's next write, so it is not labelled yet", owner, sec.Name, m.o.timeout) + } + time.Sleep(10 * time.Second) + } +} diff --git a/cmd/credentials-migrate/hide_test.go b/cmd/credentials-migrate/hide_test.go new file mode 100644 index 000000000..e9aea843b --- /dev/null +++ b/cmd/credentials-migrate/hide_test.go @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "strings" + "testing" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" +) + +// definition is the Postgres ApplicationDefinition with the admin Secret +// either included by name, as before a conversion, or excluded, as after. +func definition(adminVisible bool) *cozyv1alpha1.ApplicationDefinition { + sel := []*cozyv1alpha1.ApplicationDefinitionResourceSelector{{ResourceNames: []string{"postgres-{{ .name }}-default-user"}}} + def := &cozyv1alpha1.ApplicationDefinition{ObjectMeta: metav1.ObjectMeta{Name: "postgres"}} + def.Spec.Application.Kind = "Postgres" + if adminVisible { + def.Spec.Secrets.Include = sel + } else { + def.Spec.Secrets.Exclude = sel + } + return def +} + +func TestHidePlatformSecretsWaitsForTheDefinitionToHideIt(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", + }}} + def := definition(true) + m := newMigrator(t, hr, admin, def) + m.o.hideSuffixes = stringFlags{"-default-user"} + + // The old definition still selects it: a label now would be undone by + // the operator's next write, so none is written. + err := m.hidePlatformSecrets(ctx, hr) + if err == nil || !strings.Contains(err.Error(), "still selects postgres-orders-default-user") { + t.Fatalf("hide under the old definition = %v", err) + } + if sec, _ := m.secret(t, "postgres-orders-default-user"); sec.Labels[corev1alpha1.TenantResourceLabelKey] != "true" { + t.Fatal("labelled while the definition still selects the Secret") + } + + // The rd chart upgrades and excludes it: labelled, and the webhook stamps + // every later rewrite the same. + cur := &cozyv1alpha1.ApplicationDefinition{} + if err := m.c.Get(ctx, client.ObjectKeyFromObject(def), cur); err != nil { + t.Fatal(err) + } + cur.Spec.Secrets = definition(false).Spec.Secrets + if err := m.c.Update(ctx, cur); err != nil { + t.Fatal(err) + } + if err := m.hidePlatformSecrets(ctx, hr); err != nil { + t.Fatal(err) + } + if sec, _ := m.secret(t, "postgres-orders-default-user"); sec.Labels[corev1alpha1.TenantResourceLabelKey] != "false" { + t.Fatalf("labels = %v", sec.Labels) + } +} diff --git a/cmd/credentials-migrate/main.go b/cmd/credentials-migrate/main.go index 07004d01a..c6c368e0a 100644 --- a/cmd/credentials-migrate/main.go +++ b/cmd/credentials-migrate/main.go @@ -34,6 +34,7 @@ import ( ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + 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" @@ -84,8 +85,12 @@ type options struct { sourceSuffix string sourceKey string sourcePerAccount bool + sourceSelector labelFlags platformKeys stringFlags rotateKeys stringFlags + hideSuffixes stringFlags + fixedAccounts stringFlags + enabledFlag string stateNamespace string actor string timeout time.Duration @@ -146,7 +151,7 @@ func run(args []string) error { return errors.New("usage: credentials-migrate seed|finish [flags]") } cmd := args[0] - o := &options{labels: labelFlags{}} + o := &options{labels: labelFlags{}, sourceSelector: 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") @@ -160,8 +165,12 @@ func run(args []string) error { 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 , with the password under --source-key") + fs.Var(o.sourceSelector, "source-selector", "label, key=value, of the chart's per-account source Secrets, found by label and by the Helm release that rendered them rather than by name; each holds the user name under username and the password under --source-key; repeatable") fs.Var(&o.platformKeys, "platform-key", "key of the source Secret that belongs to a platform account and stays; repeatable") + fs.Var(&o.hideSuffixes, "hide-secret-suffix", "finish: suffix, after the release name, of a Secret the chart does not render that holds a platform account; it is labelled not tenant-visible; 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.Var(&o.fixedAccounts, "fixed-account", "user the chart renders a template for whatever the values hold, for a kind with no accounts map; used instead of --accounts-path; repeatable") + fs.StringVar(&o.enabledFlag, "enabled-flag", "", "boolean value, by dotted path, that switches the fixed accounts off when false; unset counts as true, the chart default") 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") @@ -173,8 +182,11 @@ func run(args []string) error { if o.migration == 0 || o.kind == "" || !format.Known(o.formatName) { return errors.New("--migration, --kind and a built-in --format are required") } - if o.sourcePerAccount && o.sourceKey == "" { - return errors.New("--source-per-account needs --source-key: a per-account Secret is not keyed by user name") + if (o.sourcePerAccount || len(o.sourceSelector) > 0) && o.sourceKey == "" { + return errors.New("--source-per-account and --source-selector need --source-key: a per-account Secret is not keyed by user name") + } + if o.sourcePerAccount && len(o.sourceSelector) > 0 { + return errors.New("--source-per-account and --source-selector are two ways to find the same Secrets; pass one") } for _, k := range o.rotateKeys { if !slices.Contains(o.platformKeys, k) { @@ -197,6 +209,9 @@ func run(args []string) error { if err := appsv1.AddToScheme(scheme); err != nil { return err } + if err := cozyv1alpha1.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) @@ -371,9 +386,47 @@ func (m *migrator) finishRelease(ctx context.Context, hr *helmv2.HelmRelease, re if err := m.retireSource(ctx, hr); err != nil { return err } + if err := m.hidePlatformSecrets(ctx, hr); err != nil { + return err + } return m.rotatePlatformKeys(ctx, hr) } +// hidePlatformSecrets labels the platform Secrets the chart does not render, +// such as one an operator creates, not tenant-visible. The lineage webhook +// decided their visibility at admission and skips them while their lineage +// labels stay, so dropping them from the ApplicationDefinition does not +// reach a Secret that exists until the operator next rewrites it. The label +// goes on only once the definition hides the Secret too, since a rewrite +// before that would stamp it visible again. +func (m *migrator) hidePlatformSecrets(ctx context.Context, hr *helmv2.HelmRelease) error { + for _, suffix := range m.o.hideSuffixes { + sec := &corev1.Secret{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: hr.Name + suffix}, sec); err != nil { + if apierrors.IsNotFound(err) { + continue + } + return err + } + if err := m.waitDefinitionHides(ctx, hr, sec); err != nil { + return err + } + if sec.Labels[corev1alpha1.TenantResourceLabelKey] == "false" { + continue + } + patch := client.MergeFrom(sec.DeepCopy()) + if sec.Labels == nil { + sec.Labels = map[string]string{} + } + sec.Labels[corev1alpha1.TenantResourceLabelKey] = "false" + if err := m.c.Patch(ctx, sec, patch); err != nil { + return fmt.Errorf("hide %s: %w", sec.Name, err) + } + fmt.Printf("%s/%s: labelled %s not tenant-visible\n", hr.Namespace, hr.Name, sec.Name) + } + return nil +} + // 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 @@ -391,18 +444,13 @@ func (m *migrator) seedRelease(ctx context.Context, hr *helmv2.HelmRelease) erro if err != nil { return fmt.Errorf("%w: %v", errUnresolvable, err) } - 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 - } - } + passwords, found, err := m.sourcePasswords(ctx, hr, accounts) + if err != nil { + return err + } + if !found && len(accounts) > 0 { + fmt.Printf("%s/%s: %s is gone; its accounts get a Secret at their first mint\n", hr.Namespace, hr.Name, m.sourceDesc(hr, "")) + return nil } now := metav1.NewTime(m.now()) complete := true @@ -427,10 +475,8 @@ func (m *migrator) seedRelease(ctx context.Context, hr *helmv2.HelmRelease) erro case !apierrors.IsNotFound(err): return err } - plaintext, from, ok, err := m.plaintext(ctx, hr, source, acc.Username) - if err != nil { - return err - } + plaintext, ok := passwords[acc.Username] + from := m.sourceDesc(hr, acc.Username) if !ok { 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 @@ -517,31 +563,92 @@ 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 -// , 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 +// sourcePasswords returns the chart-generated plaintext of the release's +// accounts by user name, and whether any source Secret exists. The chart kept +// either one Secret, , or one Secret per account: +// named with --source-per-account, or found by +// --source-selector and the Helm release that rendered it, for a chart whose +// name mapping is not worth re-deriving. The password is under --source-key, +// or, in the single Secret, under the user name when that is empty. +func (m *migrator) sourcePasswords(ctx context.Context, hr *helmv2.HelmRelease, accounts []account.Account) (map[string][]byte, bool, error) { + passwords := map[string][]byte{} + switch { + case len(m.o.sourceSelector) > 0: + sources, err := m.selectedSources(ctx, hr) + if err != nil { + return nil, false, err } - return nil, name, false, err + for _, sec := range sources { + user := string(sec.Data[account.UsernameKey]) + pw, ok := sec.Data[m.o.sourceKey] + if user == "" || !ok { + continue + } + passwords[user] = pw + } + return passwords, len(sources) > 0, nil + case m.o.sourcePerAccount: + for _, acc := range accounts { + sec := &corev1.Secret{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: m.perAccountSource(hr, acc.Username)}, sec); err != nil { + if apierrors.IsNotFound(err) { + continue + } + return nil, false, err + } + if pw, ok := sec.Data[m.o.sourceKey]; ok { + passwords[acc.Username] = pw + } + } + return passwords, true, nil } - v, ok := sec.Data[key] - return v, name, ok, nil + source := &corev1.Secret{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: hr.Name + m.o.sourceSuffix}, source); err != nil { + if apierrors.IsNotFound(err) { + return nil, false, nil + } + return nil, false, err + } + for _, acc := range accounts { + key := m.o.sourceKey + if key == "" { + key = acc.Username + } + if pw, ok := source.Data[key]; ok { + passwords[acc.Username] = pw + } + } + return passwords, true, nil +} + +// sourceDesc names where the plaintext of user, or of every account when user +// is empty, was looked up. +func (m *migrator) sourceDesc(hr *helmv2.HelmRelease, user string) string { + switch { + case len(m.o.sourceSelector) > 0: + return fmt.Sprintf("the Secrets labelled %s of release %s", m.o.sourceSelector, hr.GetReleaseName()) + case m.o.sourcePerAccount && user != "": + return m.perAccountSource(hr, user) + case m.o.sourcePerAccount: + return hr.Name + m.o.sourceSuffix + "" + } + return hr.Name + m.o.sourceSuffix +} + +// selectedSources lists the per-account source Secrets that carry +// --source-selector and that the release's chart rendered. +func (m *migrator) selectedSources(ctx context.Context, hr *helmv2.HelmRelease) ([]corev1.Secret, error) { + list := &corev1.SecretList{} + if err := m.c.List(ctx, list, client.InNamespace(hr.Namespace), client.MatchingLabels(m.o.sourceSelector)); err != nil { + return nil, err + } + var out []corev1.Secret + for _, sec := range list.Items { + if sec.Annotations[account.ReleaseNameAnnotation] == hr.GetReleaseName() { + out = append(out, sec) + } + } + return out, nil } func (m *migrator) perAccountSource(hr *helmv2.HelmRelease, user string) string { @@ -554,7 +661,13 @@ func (m *migrator) perAccountSource(hr *helmv2.HelmRelease, user string) string // which the converted chart would not render, or a reserved user name leave // the release unresolvable. A skipped key is not a tenant account: the // converted chart renders no template for it, so it is left out of the result. +// +// A kind with fixed accounts has no accounts map: its accounts are the fixed +// ones, or none when the release turns them off through the enabled flag. func (o *options) resolveAccounts(hr *helmv2.HelmRelease) ([]account.Account, error) { + if len(o.fixedAccounts) > 0 { + return resolveFixedAccounts(hr, o.fixedAccounts, o.enabledFlag) + } 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 { @@ -596,6 +709,39 @@ func (o *options) resolveAccounts(hr *helmv2.HelmRelease) ([]account.Account, er return accounts, nil } +// resolveFixedAccounts returns the fixed accounts of a kind with no accounts +// map, such as the one default user of Redis, or none when the release turns +// them off through the enabled flag. A flag that is not a boolean leaves the +// release unresolvable rather than guessing what the chart renders. +func resolveFixedAccounts(hr *helmv2.HelmRelease, users []string, enabledFlag string) ([]account.Account, error) { + if enabledFlag != "" { + 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 + } + } + switch v := lookup(values, enabledFlag).(type) { + case nil: + case bool: + if !v { + return nil, nil + } + default: + return nil, fmt.Errorf("%s is %v, not a boolean", enabledFlag, v) + } + } + accounts := make([]account.Account, 0, len(users)) + for _, name := range users { + mapped, err := account.MapName(name) + if err != nil { + return nil, err + } + 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 @@ -651,7 +797,7 @@ 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 { + if m.o.sourcePerAccount || len(m.o.sourceSelector) > 0 { return m.retirePerAccountSources(ctx, hr) } source := &corev1.Secret{} @@ -812,27 +958,39 @@ 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. +// retirePerAccountSources deletes the release's per-account source Secrets. +// Each holds one tenant password and nothing else, and the converted chart no +// longer renders them, so Helm has usually pruned them at the switch; this +// removes what a release installed outside Helm, or a failed prune, left. 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 - } + var sources []corev1.Secret + if len(m.o.sourceSelector) > 0 { + var err error + if sources, err = m.selectedSources(ctx, hr); err != nil { return err } + } else { + accounts, err := m.o.resolveAccounts(hr) + if err != nil { + return err + } + for _, acc := range accounts { + sec := &corev1.Secret{} + if err := m.c.Get(ctx, types.NamespacedName{Namespace: hr.Namespace, Name: m.perAccountSource(hr, acc.Username)}, sec); err != nil { + if apierrors.IsNotFound(err) { + continue + } + return err + } + sources = append(sources, *sec) + } + } + for i := range sources { + sec := &sources[i] 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) + fmt.Printf("%s/%s: deleted %s\n", hr.Namespace, hr.Name, sec.Name) } return nil } diff --git a/cmd/credentials-migrate/main_test.go b/cmd/credentials-migrate/main_test.go index 02ecc618b..be9cab54a 100644 --- a/cmd/credentials-migrate/main_test.go +++ b/cmd/credentials-migrate/main_test.go @@ -21,6 +21,7 @@ import ( "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" @@ -45,6 +46,9 @@ func newMigratorWith(t *testing.T, funcs *interceptor.Funcs, objs ...client.Obje 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) @@ -885,3 +889,252 @@ func TestRunRefusesPerAccountSourcesWithoutAKey(t *testing.T) { 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 -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") + } +} diff --git a/examples/backups/redis/00-helpers.sh b/examples/backups/redis/00-helpers.sh index 8c7272a57..e20ee6916 100755 --- a/examples/backups/redis/00-helpers.sh +++ b/examples/backups/redis/00-helpers.sh @@ -80,13 +80,16 @@ print_header() { source "$(dirname "${BASH_SOURCE[0]}")/../_lib/wait-helpers.sh" # The cozystack redis chart names its RedisFailover (hence the operator's rfr-/ -# rfs- Services and the -auth Secret) redis-, the valkey chart valkey-, -# mirroring the strategy driver that derives the same base from .Release.Prefix -# and .Release.Name. So app X's password lives in X-auth. The chart -# renders that Secret only with authEnabled, so its absence reads as no -# password; any other error still fails the read. +# rfs- Services) redis-, the valkey chart valkey-, mirroring the +# strategy driver that derives the same base from .Release.Prefix and +# .Release.Name. App X's password lives in the account Secret of its default +# CredentialTemplate, X.default.account, which holds the password itself +# and which this walkthrough reads with the platform credentials it runs under; +# a tenant gets the password by minting it instead. The Secret exists only with +# authEnabled, so its absence reads as no password; any other error still fails +# the read. redis_pw() { - kubectl -n "$NAMESPACE" get secret "${APP_PREFIX}$1-auth" --ignore-not-found -o jsonpath='{.data.password}' | base64 -d + kubectl -n "$NAMESPACE" get secret "${APP_PREFIX}$1.default.account" --ignore-not-found -o jsonpath='{.data.password}' | base64 -d } # Run a redis-cli command against an application's CURRENT master. Master diff --git a/examples/backups/redis/redis-strategy.yaml b/examples/backups/redis/redis-strategy.yaml index 6533b0e38..88ee39f8d 100644 --- a/examples/backups/redis/redis-strategy.yaml +++ b/examples/backups/redis/redis-strategy.yaml @@ -51,7 +51,7 @@ spec: - name: REDIS_PASSWORD valueFrom: secretKeyRef: - name: '{{ .Release.Prefix | default "redis-" }}{{ .Release.Name }}-auth' + name: '{{ .Release.Prefix | default "redis-" }}{{ .Release.Name }}.default.account' key: password optional: true # S3 coordinates come from this demo's Bucket: the access keys are diff --git a/hack/check-rabbitmq-rd-secrets.bats b/hack/check-rabbitmq-rd-secrets.bats index 869f42111..07d528877 100644 --- a/hack/check-rabbitmq-rd-secrets.bats +++ b/hack/check-rabbitmq-rd-secrets.bats @@ -34,12 +34,16 @@ COZYRDS="$REPO_ROOT/packages/system/rabbitmq-rd/cozyrds/rabbitmq.yaml" # label whitelist alone passes an added name. Either dimension reaches a # key-bearing Secret -- controller.cert-manager.io/fao is stamped on both the CA # and the leaf, so a selector on it is a one-line grant of the CA private key. -EXPECTED_RD_INCLUDE='[{"resourceNames":["rabbitmq-{{ .name }}-default-user"]},{"matchLabels":{"internal.cozystack.io/tenant-ca":"true"}},{"matchLabels":{"apps.cozystack.io/user-secret":"true"}}]' +# +# Since the credentials conversion the trust anchor is the only Secret a tenant +# reads here: -default-user is the platform administrator, and the tenant +# accounts live in account Secrets no definition selects. +EXPECTED_RD_INCLUDE='[{"matchLabels":{"internal.cozystack.io/tenant-ca":"true"}}]' # exclude is evaluated before include and wins, so it is the structural backstop # against a mis-stamped label on a key-bearing object. Asserted whole for the same # reason as the include: dropping one entry is the edit that has to be caught. -EXPECTED_RD_EXCLUDE='[{"resourceNames":["rabbitmq-{{ .name }}-ca","rabbitmq-{{ .name }}-tls","rabbitmq-{{ .name }}-erlang-cookie"]}]' +EXPECTED_RD_EXCLUDE='[{"resourceNames":["rabbitmq-{{ .name }}-ca","rabbitmq-{{ .name }}-tls","rabbitmq-{{ .name }}-erlang-cookie","rabbitmq-{{ .name }}-default-user"]}]' # Subsumed by the whitelist below, which cannot match without this entry. Kept # because the runner stops at the first failing test, so this one fires first and @@ -61,7 +65,7 @@ EXPECTED_RD_EXCLUDE='[{"resourceNames":["rabbitmq-{{ .name }}-ca","rabbitmq-{{ . fi } -@test "rabbitmq-rd cozyrds grants nothing beyond the default user, the trust anchor and user credentials" { +@test "rabbitmq-rd cozyrds grants nothing beyond the trust anchor" { if [ ! -f "$COZYRDS" ]; then echo "ResourceDefinition not found at $COZYRDS -- did it move?" >&2 exit 1 diff --git a/hack/check-redis-rd-secrets.bats b/hack/check-redis-rd-secrets.bats index 915e870fa..888d29886 100644 --- a/hack/check-redis-rd-secrets.bats +++ b/hack/check-redis-rd-secrets.bats @@ -44,11 +44,13 @@ load test_helper REPO_ROOT="$(cd "$(dirname "${BATS_TEST_FILENAME:-$0}")/.." && pwd)" CHART="$REPO_ROOT/packages/system/redis-rd" -# The complete tenant-visible Secret surface. The generated password by name; -# the trust anchor by label. Nothing else. The two key-bearing Secrets are +# The complete tenant-visible Secret surface: the trust anchor by label, and +# nothing else. The password is issued through the credentials API, and its +# account Secret is the platform's. The operator's internal account joins the +# key-bearing Secrets in exclude. The two key-bearing Secrets are # named in exclude, which is evaluated before include and so backstops the # label-only entry against a mis-stamp. -EXPECTED_SECRETS='{"exclude":[{"resourceNames":["redis-{{ .name }}.ca-tls","redis-{{ .name }}.tls","redis-{{ .name }}.ca-cert"]}],"include":[{"resourceNames":["redis-{{ .name }}-auth"]},{"matchLabels":{"internal.cozystack.io/tenant-ca":"true"}}]}' +EXPECTED_SECRETS='{"exclude":[{"resourceNames":["redis-{{ .name }}.ca-tls","redis-{{ .name }}.tls","redis-{{ .name }}.ca-cert","rfr-redis-{{ .name }}-internal"]}],"include":[{"matchLabels":{"internal.cozystack.io/tenant-ca":"true"}}]}' # Order within include is meaningless -- the matcher ORs across entries -- so # both arrays are sorted before comparing, and a missing exclude is normalized @@ -115,7 +117,7 @@ NORMALIZE='{exclude: ((.exclude // []) | sort), include: (.include | sort)}' # Whole-structure comparison. Anything added to the tenant's Secret surface -- # by name, by label, or by an unrestricted entry -- changes this string. -@test "redis-rd exposes no Secret beyond the password and the trust anchor" { +@test "redis-rd exposes no Secret beyond the trust anchor" { rendered=$(helm template redis-rd "$CHART") || return 1 if [ -z "$rendered" ]; then diff --git a/hack/e2e-chainsaw/redis/chainsaw-test.yaml b/hack/e2e-chainsaw/redis/chainsaw-test.yaml index feb45281e..7b7c126a9 100644 --- a/hack/e2e-chainsaw/redis/chainsaw-test.yaml +++ b/hack/e2e-chainsaw/redis/chainsaw-test.yaml @@ -81,6 +81,87 @@ spec: status: readyReplicas: 2 + # The password is the platform's to issue: a mint reaches every running + # server with CONFIG SET, restarts no pod and moves no master (replication, + # the Sentinels, the probes and the exporter use the operator's internal + # account, not this password), and a second mint replaces the first. + - name: verify-minted-credential + try: + - assert: + timeout: 2m + resource: + apiVersion: core.cozystack.io/v1alpha1 + kind: Credential + metadata: + name: redis-test.default + spec: + application: + kind: Redis + name: test + user: default + status: + password: + origin: NotIssued + # bash for pipefail and process substitution; the sandbox's /bin/sh is dash. + - script: + timeout: 10m + shell: bash + content: | + set -euo pipefail + cred=redis-test.default + mint() { + kubectl create --raw "/apis/core.cozystack.io/v1alpha1/namespaces/$NAMESPACE/credentials/$cred/mint" \ + -f <(printf '{"apiVersion":"core.cozystack.io/v1alpha1","kind":"CredentialRequest"}') \ + | jq -r '.status.password' + } + # The password goes to redis-cli on stdin: exec arguments travel in + # the request URI, which the audit log records at any level. + cli() { + local password=$1; shift + local pod + pod=$(kubectl -n "$NAMESPACE" get pod -l app.kubernetes.io/component=redis,app.kubernetes.io/instance=redis-test \ + --field-selector status.phase=Running -o name | head -n1) + [ -n "$pod" ] || return 0 + printf '%s\n' "$password" | kubectl -n "$NAMESPACE" exec -i "$pod" -c redis -- \ + sh -c 'IFS= read -r REDISCLI_AUTH; export REDISCLI_AUTH; exec redis-cli -h rfrm-redis-test "$@"' sh \ + "$@" 2>/dev/null | tr -d '\r' || true + } + login() { cli "$1" ping; } + # Every redis pod with its uid and restart count, and which one the + # master label is on: a mint must change none of it. + pods() { + kubectl -n "$NAMESPACE" get pod -l app.kubernetes.io/component=redis,app.kubernetes.io/instance=redis-test \ + -o jsonpath='{range .items[*]}{.metadata.name} {.metadata.uid} {.status.containerStatuses[*].restartCount} {.metadata.labels.redisfailovers-role}{"\n"}{end}' | sort + } + before=$(pods) + [ "$(printf '%s\n' "$before" | grep -c ' master$')" = 1 ] || { echo "no single master before the mint: $before" >&2; exit 1; } + + first=$(mint) + [ "${#first}" -eq 32 ] || { echo "minted password has ${#first} characters, want 32" >&2; exit 1; } + # The operator applies the changed account Secret on its next + # reconcile; a readiness wait on that, not a retry. + until [ "$(login "$first")" = "PONG" ]; do sleep 5; done + view=$(kubectl -n "$NAMESPACE" get credentials.core.cozystack.io "$cred" -o json) + [ "$(printf '%s' "$view" | jq -r .status.password.origin)" = "Minted" ] || { echo "origin is not Minted: $view" >&2; exit 1; } + if printf '%s' "$view" | grep -qF -- "$first"; then echo "the Credential carries the minted password" >&2; exit 1; fi + + second=$(mint) + [ "$second" != "$first" ] || { echo "a second mint returned the same password" >&2; exit 1; } + until [ "$(login "$second")" = "PONG" ]; do sleep 5; done + # The operator drops the replaced password once every server takes + # the new one, a pass after it applies it. + while [ "$(login "$first")" = "PONG" ]; do sleep 5; done + # Replication outlived both rotations, and nothing restarted or + # failed over to get there. + until cli "$second" info replication | grep -qx 'connected_slaves:1'; do sleep 5; done + after=$(pods) + if [ "$after" != "$before" ]; then + printf 'a mint restarted a pod or moved the master:\nbefore:\n%s\nafter:\n%s\n' "$before" "$after" >&2 + exit 1 + fi + check: + ($error == null): true + # One replica runs one Sentinel with its PDB disabled. The PDB the operator # created for the three Sentinels of two replicas has to go with it, or its # minAvailable: 1 pins the only Sentinel against every eviction. @@ -267,20 +348,10 @@ spec: try: # Positive control, and it comes first: the negatives below are satisfied # by an ABSENT label, which is also what a webhook that stamped nothing - # this run looks like. The auth Secret is chart-rendered, traces to the - # Redis CR and is included by name, so it MUST be stamped. - - assert: - timeout: 2m - resource: - apiVersion: v1 - kind: Secret - metadata: - name: redis-secure-auth - labels: - internal.cozystack.io/tenantresource: "true" - # tenant-ca is stamped by the CA-extraction controller; tenantresource is - # the lineage webhook's verdict from the redis ApplicationDefinition's - # matchLabels include. Both true means the whole chain held. + # this run looks like. tenant-ca is stamped by the CA-extraction + # controller; tenantresource is the lineage webhook's verdict from the + # redis ApplicationDefinition's matchLabels include. Both true means the + # whole chain held. - assert: timeout: 2m resource: @@ -320,6 +391,15 @@ spec: metadata: name: redis-secure.ca-cert (metadata.labels."internal.cozystack.io/tenantresource" != 'true'): true + # The account Secret holds the password itself and is the platform's. + - assert: + timeout: 2m + resource: + apiVersion: v1 + kind: Secret + metadata: + name: redis-secure.default.account + (metadata.labels."internal.cozystack.io/tenantresource" != 'true'): true # No retry around this script. The replica link it reads is settled by # none of the asserts above and carries its own bounded wait below. The # whole step measured 3.0s on run 34711755303, so link_wait is wide @@ -523,7 +603,10 @@ spec: # unlinked, and a dropped link re-enters it. The topology is thus in # motion here and one sampling would decide on it. Wait for it to # settle, then assert the sentinels moved off the bootstrap address, - # which nothing above covers at all. + # which nothing above covers at all. The redis container's + # REDIS_PASSWORD belongs to REDIS_USER (rf-internal), not to + # default, so the dial names that user, as the operator's own + # scripts do. link_wait=60 started=$(date +%s) deadline=$(( started + link_wait )) @@ -534,7 +617,7 @@ spec: for i in 0 1; do rc=0 info=$(k -n "$NAMESPACE" exec "rfr-redis-secure-$i" -c redis -- \ - sh -c 'REDISCLI_AUTH="$REDIS_PASSWORD" timeout 15 redis-cli --tls --cacert /tls/ca.crt -h localhost -p 6379 info replication' 2>&1) || rc=$? + sh -c 'REDISCLI_AUTH="$REDIS_PASSWORD" timeout 15 redis-cli ${REDIS_USER:+--user "$REDIS_USER"} --tls --cacert /tls/ca.crt -h localhost -p 6379 info replication' 2>&1) || rc=$? if [ "$rc" -ne 0 ]; then echo "INFO replication on rfr-redis-secure-$i failed (exit $rc): $info" >&2 exit 1 diff --git a/hack/migration-68-rabbitmq-credentials.bats b/hack/migration-68-rabbitmq-credentials.bats new file mode 100644 index 000000000..d68cafa7a --- /dev/null +++ b/hack/migration-68-rabbitmq-credentials.bats @@ -0,0 +1,202 @@ +#!/usr/bin/env bats +# ----------------------------------------------------------------------------- +# Unit tests for platform migration 68 --> 69 (convert RabbitMQ users to +# platform-minted credentials, first part). +# +# The migration seeds the account Secrets of every RabbitMQ release, then +# creates the cozystack-credentials-migration-68 finish Job directly (rather +# than rendering it from the platform chart) so a changing migrations image +# never collides with an immutable pod template and helm-controller waits on no +# long-running Job. See packages/core/platform/images/migrations/migrations/68. +# +# FAIL CLOSED is pinned for each path: a failed seed, a pod whose image cannot +# be read, and a failed apply of the Job must stop the migration before it +# stamps the version, because migrations never re-run. +# +# The harness (docker, the migrations image base, fake kubectl and +# credentials-migrate on PATH) is the one hack/migration-58-http-cache-freeze.bats +# describes; see there for why each piece is load-bearing. +# +# Run with: hack/cozytest.sh hack/migration-68-rabbitmq-credentials.bats +# ----------------------------------------------------------------------------- + +load test_helper + +FAKEBIN="$PWD/hack/testdata/migration-68-rabbitmq-credentials" +MIG_DIR="$PWD/packages/core/platform/images/migrations/migrations" +ALPINE=$(sed -n 's/^FROM \(alpine:[^ ]*\).*$/\1/p' \ + "$PWD/packages/core/platform/images/migrations/Dockerfile" | head -1) +TESTIMG="cozystack-migration68-test:$(printf '%s' "$ALPINE" | sed 's/[^a-zA-Z0-9]/-/g')" +WORKROOT="${TMPDIR:-/tmp}/cozy-migration-68-$$" +IMAGE=registry.example.org/cozystack/cozystack:v1.7.0 + +cozy_cleanup() { + rm -rf "$WORKROOT" + return 0 +} + +cmdlog_line() { + grep -nE -- "$1" "$FAKE_CMDLOG" | head -1 | cut -d: -f1 +} + +run_migration() { + _run_migration_rc=0 + docker run --rm --network none \ + --user "$(id -u):$(id -g)" \ + -v "$MIG_DIR:/migrations:ro" \ + -v "$FAKEBIN:/fakebin:ro" \ + -v "$WORK:/work" \ + -e PATH=/fakebin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + -e FAKE_CMDLOG=/work/cmdlog \ + -e NAMESPACE="${NAMESPACE-}" \ + -e FAKE_IMAGE="${FAKE_IMAGE-}" \ + -e FAKE_IMAGE_EMPTY="${FAKE_IMAGE_EMPTY-}" \ + -e FAKE_GETPOD_FAIL="${FAKE_GETPOD_FAIL-}" \ + -e FAKE_APPLY_FAIL="${FAKE_APPLY_FAIL-}" \ + -e FAKE_SEED_FAIL="${FAKE_SEED_FAIL-}" \ + -e FAKE_GETJOB_FAIL="${FAKE_GETJOB_FAIL-}" \ + -e FAKE_JOBUID_EMPTY="${FAKE_JOBUID_EMPTY-}" \ + -e FAKE_PATCH_FAIL="${FAKE_PATCH_FAIL-}" \ + "$TESTIMG" "/migrations/$1" || _run_migration_rc=$? + return "$_run_migration_rc" +} + +prep() { + docker info >/dev/null 2>&1 || { + echo "docker is required: these tests run migration 68 inside a build of" >&2 + echo "$ALPINE, the migrations image's base." >&2 + return 1 + } + docker build -q -t "$TESTIMG" - >/dev/null < "$FAKE_CMDLOG" + export NAMESPACE=cozy-system + export FAKE_IMAGE="$IMAGE" + unset FAKE_IMAGE_EMPTY FAKE_GETPOD_FAIL FAKE_APPLY_FAIL FAKE_SEED_FAIL FAKE_GETJOB_FAIL FAKE_JOBUID_EMPTY FAKE_PATCH_FAIL || true + return 0 +} + +@test "it seeds, creates the finish Job on its own image, and stamps" { + prep + rc=0 + run_migration 68 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -eq 0 ] + + # The seed runs for migration 68, reading the per-user Secrets by label and + # labelling the account Secrets for the topology operator. + grep -qE "^CREDMIGRATE seed --migration 68 --kind RabbitMQ --format plaintext .*--source-selector apps.cozystack.io/user-secret=true --source-key password --label rabbitmq.com/topology-operator=true$" "$FAKE_CMDLOG" + grep -qE "^APPLY-RABBITMQ selector=1 key=1 hide=1 list=1$" "$FAKE_CMDLOG" + + # The finish Job carries its least-privilege ClusterRole (never cluster-admin), + # ServiceAccount and binding, the migration number, and the image this hook + # runs as, read from its own pod rather than values. + grep -qE "^APPLY-FINISH role=1 sa=1 crb=1 admin=0 jobname=1 migration=1 image=1 serviceaccount=1 appdefs=1$" "$FAKE_CMDLOG" + + # The Job owns its ServiceAccount, so the cluster-admin identity is collected + # with the Job and does not stand indefinitely. + grep -qE "^PATCH-SA-OWNER owner=1$" "$FAKE_CMDLOG" + + # A stale Job from an earlier run is deleted before the apply, so a rerun on a + # newer image does not fault on the immutable pod template; the ownership is + # set after the Job exists; and only then, after the Job is created and owned, + # the version is stamped. A stamp before the Job would mark the migration done + # with no finisher. + _del=$(cmdlog_line "^DELETE-JOB$") + _apply=$(cmdlog_line "^APPLY-FINISH ") + _own=$(cmdlog_line "^PATCH-SA-OWNER ") + _stamp=$(cmdlog_line "^STAMP 69$") + [ -n "$_del" ] && [ "$_del" -lt "$_apply" ] + [ -n "$_own" ] && [ "$_apply" -lt "$_own" ] + [ -n "$_stamp" ] && [ "$_own" -lt "$_stamp" ] + rm -rf "$WORK" +} + +@test "a pod whose image cannot be read, as a failed get, stops before the Job and the stamp" { + prep + export FAKE_GETPOD_FAIL="the server could not find the requested resource" + rc=0 + run_migration 68 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + grep -qE "^CREDMIGRATE seed --migration 68 " "$FAKE_CMDLOG" + if grep -qE "^APPLY-FINISH" "$FAKE_CMDLOG"; then echo "created the Job after a failed image read" >&2; return 1; fi + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after a failed image read" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "a failed seed stops before the Job and before stamping" { + prep + export FAKE_SEED_FAIL="apiserver is unavailable" + rc=0 + run_migration 68 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + if grep -qE "^APPLY-FINISH" "$FAKE_CMDLOG"; then echo "created the Job after a failed seed" >&2; return 1; fi + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after a failed seed" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "a pod whose image cannot be read stops after the seed, before the Job and the stamp" { + prep + export FAKE_IMAGE_EMPTY=1 + rc=0 + run_migration 68 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + grep -qE "^CREDMIGRATE seed --migration 68 " "$FAKE_CMDLOG" + if grep -qE "^APPLY-FINISH" "$FAKE_CMDLOG"; then echo "created the Job with no image to run" >&2; return 1; fi + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped with no image to run" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "a failed apply of the Job stops before stamping" { + prep + export FAKE_APPLY_FAIL="admission webhook denied the request" + rc=0 + run_migration 68 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after the Job failed to apply" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "a Job whose uid cannot be read stops before owning the SA and before stamping" { + prep + export FAKE_GETJOB_FAIL="the server was unable to return a response" + rc=0 + run_migration 68 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + if grep -qE "^PATCH-SA-OWNER" "$FAKE_CMDLOG"; then echo "patched ownership with no uid" >&2; return 1; fi + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped without owning the SA" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "an empty Job uid stops before owning the SA and before stamping" { + prep + export FAKE_JOBUID_EMPTY=1 + rc=0 + run_migration 68 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + if grep -qE "^PATCH-SA-OWNER" "$FAKE_CMDLOG"; then echo "patched ownership with an empty uid" >&2; return 1; fi + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped with an empty uid" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "a failed ownership patch stops before stamping" { + prep + export FAKE_PATCH_FAIL="serviceaccounts \"cozystack-credentials-migration\" not found" + rc=0 + run_migration 68 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after the ownership patch failed" >&2; return 1; fi + rm -rf "$WORK" +} diff --git a/hack/migration-69-70-redis-valkey-credentials.bats b/hack/migration-69-70-redis-valkey-credentials.bats new file mode 100644 index 000000000..e13d23660 --- /dev/null +++ b/hack/migration-69-70-redis-valkey-credentials.bats @@ -0,0 +1,180 @@ +#!/usr/bin/env bats +# ----------------------------------------------------------------------------- +# Unit tests for platform migrations 69 --> 70 (Redis) and 70 --> 71 (Valkey): +# convert the default password to platform-minted credentials, first part. +# +# Each migration seeds the account Secret of the default user of every release +# of its kind from -auth, then creates its finish Job directly, as +# migration 64 does. These pin what the two add over 64: the seed and the Job +# take the fixed account, its source key and the enabled flag, and the Job's +# ClusterRole, ServiceAccount and binding are named for the migration, so the +# two conversions running in one upgrade share none of them. +# +# FAIL CLOSED is pinned for each path: a failed seed, a pod whose image cannot +# be read, a failed apply of the Job, and a Job that cannot be owned must stop +# the migration before it stamps the version, because migrations never re-run. +# +# The harness (docker, the migrations image base, fake kubectl and +# credentials-migrate on PATH) is the one hack/migration-58-http-cache-freeze.bats +# describes; see there for why each piece is load-bearing. +# +# Run with: hack/cozytest.sh hack/migration-69-70-redis-valkey-credentials.bats +# ----------------------------------------------------------------------------- + +load test_helper + +FAKEBIN="$PWD/hack/testdata/migration-69-70-redis-valkey-credentials" +MIG_DIR="$PWD/packages/core/platform/images/migrations/migrations" +ALPINE=$(sed -n 's/^FROM \(alpine:[^ ]*\).*$/\1/p' \ + "$PWD/packages/core/platform/images/migrations/Dockerfile" | head -1) +TESTIMG="cozystack-migration69-test:$(printf '%s' "$ALPINE" | sed 's/[^a-zA-Z0-9]/-/g')" +WORKROOT="${TMPDIR:-/tmp}/cozy-migration-69-$$" +IMAGE=registry.example.org/cozystack/cozystack:v1.7.0 + +cozy_cleanup() { + rm -rf "$WORKROOT" + return 0 +} + +cmdlog_line() { + grep -nE -- "$1" "$FAKE_CMDLOG" | head -1 | cut -d: -f1 +} + +run_migration() { + _run_migration_rc=0 + docker run --rm --network none \ + --user "$(id -u):$(id -g)" \ + -v "$MIG_DIR:/migrations:ro" \ + -v "$FAKEBIN:/fakebin:ro" \ + -v "$WORK:/work" \ + -e PATH=/fakebin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + -e FAKE_CMDLOG=/work/cmdlog \ + -e FAKE_MIGRATION="$1" \ + -e NAMESPACE="${NAMESPACE-}" \ + -e FAKE_IMAGE="${FAKE_IMAGE-}" \ + -e FAKE_IMAGE_EMPTY="${FAKE_IMAGE_EMPTY-}" \ + -e FAKE_GETPOD_FAIL="${FAKE_GETPOD_FAIL-}" \ + -e FAKE_APPLY_FAIL="${FAKE_APPLY_FAIL-}" \ + -e FAKE_SEED_FAIL="${FAKE_SEED_FAIL-}" \ + -e FAKE_GETJOB_FAIL="${FAKE_GETJOB_FAIL-}" \ + -e FAKE_JOBUID_EMPTY="${FAKE_JOBUID_EMPTY-}" \ + -e FAKE_PATCH_FAIL="${FAKE_PATCH_FAIL-}" \ + "$TESTIMG" "/migrations/$1" || _run_migration_rc=$? + return "$_run_migration_rc" +} + +prep() { + docker info >/dev/null 2>&1 || { + echo "docker is required: these tests run migrations 69 and 70 inside a" >&2 + echo "build of $ALPINE, the migrations image's base." >&2 + return 1 + } + docker build -q -t "$TESTIMG" - >/dev/null < "$FAKE_CMDLOG" + export NAMESPACE=cozy-system + export FAKE_IMAGE="$IMAGE" + unset FAKE_IMAGE_EMPTY FAKE_GETPOD_FAIL FAKE_APPLY_FAIL FAKE_SEED_FAIL FAKE_GETJOB_FAIL FAKE_JOBUID_EMPTY FAKE_PATCH_FAIL || true + return 0 +} + +# check_converts +check_converts() { + prep + rc=0 + run_migration "$1" >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -eq 0 ] + + # The seed takes the one default user, its password from the password key + # of -auth, and authEnabled as the switch. + # It holds the releases until the new redis-operator runs, which the + # finish Job reads the Deployment for: the old operator rolls the converted + # pod template by deleting the master. + grep -qxF "CREDMIGRATE seed --migration $1 --kind $2 --format plaintext --fixed-account default --source-key password --enabled-flag authEnabled --source-suffix=-auth --hold-until-rollout cozy-redis-operator/redis-operator" "$FAKE_CMDLOG" + + # The finish Job carries its least-privilege ClusterRole (never + # cluster-admin), ServiceAccount and binding, all named for the migration + # (five names: the three objects, the roleRef and the Job), the same account + # flags as the seed, and the image this hook runs as. + grep -qxE "APPLY-FINISH role=1 sa=1 crb=1 admin=0 migration=1 image=1 serviceaccount=1 fixed=5 actor=1 named=5 deployments=1" "$FAKE_CMDLOG" + grep -qxE "PATCH-SA-OWNER owner=1" "$FAKE_CMDLOG" + + # Stale Job deleted before the apply, owned after it, stamped last. + _del=$(cmdlog_line "^DELETE-JOB$") + _apply=$(cmdlog_line "^APPLY-FINISH ") + _own=$(cmdlog_line "^PATCH-SA-OWNER ") + _stamp=$(cmdlog_line "^STAMP $(($1 + 1))$") + [ -n "$_del" ] && [ "$_del" -lt "$_apply" ] + [ -n "$_own" ] && [ "$_apply" -lt "$_own" ] + [ -n "$_stamp" ] && [ "$_own" -lt "$_stamp" ] + rm -rf "$WORK" +} + +# check_fails_closed +check_fails_closed() { + prep + export "$2=$3" + rc=0 + run_migration "$1" >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "migration $1 stamped after $2" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "69 converts Redis: seeds, creates its own finish Job, and stamps 70" { + check_converts 69 Redis +} + +@test "70 converts Valkey: seeds, creates its own finish Job, and stamps 71" { + check_converts 70 Valkey +} + +@test "a failed seed stops before the Job and the stamp" { + for n in 69 70; do + check_fails_closed "$n" FAKE_SEED_FAIL "apiserver is unavailable" + done +} + +@test "a pod whose image cannot be read stops before the Job and the stamp" { + for n in 69 70; do + check_fails_closed "$n" FAKE_GETPOD_FAIL "the server could not find the requested resource" + check_fails_closed "$n" FAKE_IMAGE_EMPTY 1 + done +} + +@test "a seed that fails to hold a release stops before the Job and the stamp" { + # A release suspended with no finish Job to resume it would stay frozen. + for n in 69 70; do + prep + export FAKE_SEED_FAIL="tenant-a/redis-x: hold until the new components run: the object has been modified" + rc=0 + run_migration "$n" >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + grep -qF "hold until the new components run" "$WORK/out" + if grep -qE "^APPLY-FINISH" "$FAKE_CMDLOG"; then echo "migration $n created the Job after a failed hold" >&2; return 1; fi + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "migration $n stamped after a failed hold" >&2; return 1; fi + rm -rf "$WORK" + done +} + +@test "a failed apply of the Job stops before stamping" { + for n in 69 70; do + check_fails_closed "$n" FAKE_APPLY_FAIL "admission webhook denied the request" + done +} + +@test "a Job that cannot be owned stops before stamping" { + for n in 69 70; do + check_fails_closed "$n" FAKE_GETJOB_FAIL "the server was unable to return a response" + check_fails_closed "$n" FAKE_JOBUID_EMPTY 1 + check_fails_closed "$n" FAKE_PATCH_FAIL "serviceaccounts not found" + done +} diff --git a/hack/migration-71-bucket-credentials.bats b/hack/migration-71-bucket-credentials.bats new file mode 100644 index 000000000..261afcde2 --- /dev/null +++ b/hack/migration-71-bucket-credentials.bats @@ -0,0 +1,252 @@ +#!/usr/bin/env bats +# ----------------------------------------------------------------------------- +# Unit tests for platform migration 71 --> 72 (convert Bucket users to +# platform-minted credentials). +# +# The migration marks every tenant BucketAccess the bucket chart rendered with +# helm.sh/resource-policy=keep and credentials.cozystack.io/adopt=true, so the +# chart upgrade leaves it in place and cozystack-controller adopts it with its +# keys, and marks the backup bucket's system user platform. See +# packages/core/platform/images/migrations/migrations/71. +# +# FAIL CLOSED is pinned: a failed listing or a failed mark must stop the +# migration before it stamps the version, because migrations never re-run. +# +# The harness (docker, the migrations image base, fake kubectl on PATH) is the +# one hack/migration-58-http-cache-freeze.bats describes. +# +# Run with: hack/cozytest.sh hack/migration-71-bucket-credentials.bats +# ----------------------------------------------------------------------------- + +load test_helper + +FAKEBIN="$PWD/hack/testdata/migration-71-bucket-credentials" +MIG_DIR="$PWD/packages/core/platform/images/migrations/migrations" +ALPINE=$(sed -n 's/^FROM \(alpine:[^ ]*\).*$/\1/p' \ + "$PWD/packages/core/platform/images/migrations/Dockerfile" | head -1) +TESTIMG="cozystack-migration71-test:$(printf '%s' "$ALPINE" | sed 's/[^a-zA-Z0-9]/-/g')" +WORKROOT="${TMPDIR:-/tmp}/cozy-migration-71-$$" + +# namespace name release class controller-kind. bucket-docs-public-read is a +# tenant user named public-read in a bucket without publicRead, on the base +# class of a SeaweedFS in tenant-public, which ends in -public too; +# bucket-old-public-read is an anonymous access whose class is gone. +ACCESSES='tenant-foo bucket-photos-web bucket-photos tenant-foo +tenant-foo bucket-photos-reader bucket-photos tenant-foo-readonly +tenant-foo bucket-photos-public-read bucket-photos tenant-foo-public +tenant-public bucket-docs-public-read bucket-docs tenant-public +tenant-bar bucket-old-public-read bucket-old tenant-bar-public +tenant-root bucket-cozy-backups-system bucket-cozy-backups tenant-root +tenant-foo bucket-done-app bucket-done tenant-foo CredentialTemplate +tenant-foo unrelated some-release tenant-foo ' + +# name accessPolicy, as the SeaweedFS chart renders them. +CLASSES='tenant-foo readwrite +tenant-foo-readonly readonly +tenant-foo-public public-read +tenant-public readwrite +tenant-public-readonly readonly +tenant-public-public public-read +tenant-root readwrite' + +cmdlog_line() { + grep -nE -- "$1" "$FAKE_CMDLOG" | head -1 | cut -d: -f1 +} + +cozy_cleanup() { + rm -rf "$WORKROOT" + return 0 +} + +run_migration() { + _run_migration_rc=0 + docker run --rm --network none \ + --user "$(id -u):$(id -g)" \ + -v "$MIG_DIR:/migrations:ro" \ + -v "$FAKEBIN:/fakebin:ro" \ + -v "$WORK:/work" \ + -e PATH=/fakebin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + -e FAKE_CMDLOG=/work/cmdlog \ + -e NAMESPACE=cozy-system \ + -e FAKE_ACCESSES="${FAKE_ACCESSES-}" \ + -e FAKE_CLASSES="${FAKE_CLASSES-}" \ + -e FAKE_CLASS_FAIL="${FAKE_CLASS_FAIL-}" \ + -e FAKE_BACKUP_NS="${FAKE_BACKUP_NS-}" \ + -e FAKE_BACKUP_BUCKET="${FAKE_BACKUP_BUCKET-}" \ + -e FAKE_NO_SYSTEM="${FAKE_NO_SYSTEM-}" \ + -e FAKE_NO_CRD="${FAKE_NO_CRD-}" \ + -e FAKE_LIST_FAIL="${FAKE_LIST_FAIL-}" \ + -e FAKE_LABEL_FAIL="${FAKE_LABEL_FAIL-}" \ + -e FAKE_KEYLESS="${FAKE_KEYLESS-}" \ + -e FAKE_STRIP_FAIL="${FAKE_STRIP_FAIL-}" \ + -e FAKE_CRD_FAIL="${FAKE_CRD_FAIL-}" \ + -e CREDENTIAL_CRD_FILE=/work/credentialtemplates.yaml \ + "$TESTIMG" "/migrations/$1" || _run_migration_rc=$? + return "$_run_migration_rc" +} + +prep() { + docker info >/dev/null 2>&1 || { + echo "docker is required: these tests run migration 71 inside a build of" >&2 + echo "$ALPINE, the migrations image's base." >&2 + return 1 + } + docker build -q -t "$TESTIMG" - >/dev/null < "$FAKE_CMDLOG" + export FAKE_ACCESSES="$ACCESSES" + export FAKE_CLASSES="$CLASSES" + unset FAKE_CLASS_FAIL FAKE_BACKUP_NS FAKE_BACKUP_BUCKET FAKE_NO_SYSTEM FAKE_NO_CRD FAKE_LIST_FAIL FAKE_LABEL_FAIL FAKE_CRD_FAIL FAKE_KEYLESS FAKE_STRIP_FAIL || true + return 0 +} + +@test "it marks tenant BucketAccesses, the backup user platform, and stamps" { + prep + rc=0 + run_migration 71 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -eq 0 ] + + grep -qxF "PATCH-PLATFORM tenant-root/bucket-cozy-backups platform=1" "$FAKE_CMDLOG" + # The CRD with spec.bucketAccess is applied, owned by the + # cozystack-controller release, and established before anything else. + _crd=$(cmdlog_line "^CRD established$") + _platform=$(cmdlog_line "^PATCH-PLATFORM ") + [ -n "$_crd" ] && [ "$_crd" -lt "$_platform" ] + grep -qxF "CRD label" "$FAKE_CMDLOG" + grep -qxF "CRD annotate" "$FAKE_CMDLOG" + for name in tenant-foo/bucket-photos-web tenant-foo/bucket-photos-reader tenant-public/bucket-docs-public-read; do + grep -qxF "KEEP $name keep=1" "$FAKE_CMDLOG" + grep -qxF "ADOPT $name adopt=1" "$FAKE_CMDLOG" + done + grep -qxF "STRIP tenant-public/bucket-docs-public-read-credentials strip=1" "$FAKE_CMDLOG" + # The anonymous public-read access has no keys, whether its class is there + # or gone; the backup user stays a platform account, an adopted + # BucketAccess is left alone, and nothing a bucket chart did not render is + # touched. + for name in bucket-photos-public-read bucket-old-public-read bucket-cozy-backups-system bucket-done-app unrelated; do + if grep -qE "^(KEEP|ADOPT) [^ ]*/$name " "$FAKE_CMDLOG"; then echo "marked $name" >&2; return 1; fi + done + # Each tenant user's readable Secret loses its keys; the platform user's + # keeps them, and nothing reads the key values out. + for name in bucket-photos-web bucket-photos-reader bucket-done-app; do + grep -qxF "STRIP tenant-foo/$name-credentials strip=1" "$FAKE_CMDLOG" + done + if grep -qE "^STRIP [^ ]*/bucket-cozy-backups-system-credentials " "$FAKE_CMDLOG"; then echo "stripped the platform user's keys" >&2; return 1; fi + if grep -qE "^READ-KEYS " "$FAKE_CMDLOG"; then echo "read the key values" >&2; return 1; fi + _strip=$(cmdlog_line "^STRIP ") + _stamp=$(cmdlog_line "^STAMP 72$") + [ -n "$_strip" ] && [ "$_strip" -lt "$_stamp" ] + rm -rf "$WORK" +} + +@test "a Secret that holds no keys is not patched" { + prep + export FAKE_ACCESSES='tenant-foo bucket-photos-web bucket-photos tenant-foo ' + export FAKE_KEYLESS=bucket-photos-web-credentials + rc=0 + run_migration 71 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -eq 0 ] + if grep -qE "^STRIP " "$FAKE_CMDLOG"; then echo "patched a keyless Secret" >&2; return 1; fi + grep -qxF "ADOPT tenant-foo/bucket-photos-web adopt=1" "$FAKE_CMDLOG" + rm -rf "$WORK" +} + +@test "a failed strip stops before stamping" { + prep + export FAKE_STRIP_FAIL="secrets is forbidden" + rc=0 + run_migration 71 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after a failed strip" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "it finds the backup bucket where backupstrategy-controller provisions it" { + prep + export FAKE_BACKUP_NS=tenant-ops FAKE_BACKUP_BUCKET=backups + export FAKE_ACCESSES='tenant-ops bucket-backups-system bucket-backups tenant-ops ' + rc=0 + run_migration 71 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -eq 0 ] + grep -qxF "PATCH-PLATFORM tenant-ops/bucket-backups platform=1" "$FAKE_CMDLOG" + if grep -qE "^(KEEP|ADOPT) " "$FAKE_CMDLOG"; then echo "marked the backup user" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "a backup release without a system user is not given one" { + prep + export FAKE_NO_SYSTEM=1 + rc=0 + run_migration 71 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -eq 0 ] + if grep -qE "^PATCH-PLATFORM" "$FAKE_CMDLOG"; then echo "patched a release without a system user" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "a cluster without the COSI API stamps without listing" { + prep + export FAKE_NO_CRD=1 + rc=0 + run_migration 71 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -eq 0 ] + if grep -qF "get bucketaccesses" "$FAKE_CMDLOG"; then echo "listed BucketAccesses without the CRD" >&2; return 1; fi + grep -qxF "STAMP 72" "$FAKE_CMDLOG" + rm -rf "$WORK" +} + +@test "a failed listing stops before stamping" { + prep + export FAKE_LIST_FAIL="the server was unable to return a response" + rc=0 + run_migration 71 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after a failed listing" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "a failed class listing stops before any mark and the stamp" { + prep + export FAKE_CLASS_FAIL="the server was unable to return a response" + rc=0 + run_migration 71 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + if grep -qE "^(KEEP|ADOPT|STRIP) " "$FAKE_CMDLOG"; then echo "marked without the classes" >&2; return 1; fi + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after a failed class listing" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "a failed mark stops before stamping" { + prep + export FAKE_LABEL_FAIL="admission webhook denied the request" + rc=0 + run_migration 71 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped after a failed mark" >&2; return 1; fi + rm -rf "$WORK" +} + +@test "a CRD that fails to apply stops before any mark and the stamp" { + prep + export FAKE_CRD_FAIL=1 + rc=0 + run_migration 71 >"$WORK/out" 2>&1 || rc=$? + cat "$WORK/out"; cat "$FAKE_CMDLOG" + [ "$rc" -ne 0 ] + if grep -qE "^(PATCH-PLATFORM|KEEP|ADOPT) " "$FAKE_CMDLOG"; then echo "marked without the CRD" >&2; return 1; fi + if grep -qF "STAMP" "$FAKE_CMDLOG"; then echo "stamped without the CRD" >&2; return 1; fi + rm -rf "$WORK" +} diff --git a/hack/redis-backup-demo-helpers.bats b/hack/redis-backup-demo-helpers.bats index bbc9fdaa3..432bf40fd 100644 --- a/hack/redis-backup-demo-helpers.bats +++ b/hack/redis-backup-demo-helpers.bats @@ -20,7 +20,7 @@ make_stubs() { cat > "$stub/kubectl" <<'EOF' #!/bin/bash printf '%s\n' "$*" >> "$STUB_DIR/kubectl.argv" -if [ "$*" = "-n tenant-root get secret redis-demo-auth --ignore-not-found -o jsonpath={.data.password}" ]; then +if [ "$*" = "-n tenant-root get secret redis-demo.default.account --ignore-not-found -o jsonpath={.data.password}" ]; then printf '%s' "${STUB_PW_B64:-}" exit 0 fi diff --git a/hack/testdata/migration-68-rabbitmq-credentials/credentials-migrate b/hack/testdata/migration-68-rabbitmq-credentials/credentials-migrate new file mode 100755 index 000000000..978ef8d45 --- /dev/null +++ b/hack/testdata/migration-68-rabbitmq-credentials/credentials-migrate @@ -0,0 +1,22 @@ +#!/bin/sh +# Fake credentials-migrate for hack/migration-68-rabbitmq-credentials.bats. +# Migration 68 runs `credentials-migrate seed` in the hook; the real binary is +# exercised by cmd/credentials-migrate's Go tests, so this fake only records the +# call and fails on demand to pin the hook's fail-closed behaviour. +# +# FAKE_CMDLOG file to append a one-line record of each call to +# FAKE_SEED_FAIL non-empty => `seed` exits 1 with this stderr +set -u + +[ -n "${FAKE_CMDLOG:-}" ] && printf 'CREDMIGRATE %s\n' "$*" >> "$FAKE_CMDLOG" + +case "${1:-}" in + seed) + if [ -n "${FAKE_SEED_FAIL:-}" ]; then + printf '%s\n' "$FAKE_SEED_FAIL" >&2 + exit 1 + fi + exit 0 + ;; +esac +exit 0 diff --git a/hack/testdata/migration-68-rabbitmq-credentials/kubectl b/hack/testdata/migration-68-rabbitmq-credentials/kubectl new file mode 100755 index 000000000..3c1937b03 --- /dev/null +++ b/hack/testdata/migration-68-rabbitmq-credentials/kubectl @@ -0,0 +1,119 @@ +#!/bin/sh +# Fake kubectl for hack/migration-68-rabbitmq-credentials.bats, modelled on +# hack/testdata/migration-58-http-cache/kubectl. It serves only the calls +# migration 68 and lib/cozystack-version.sh make, and logs each one to +# $FAKE_CMDLOG. +# +# Migration 68 reads its own pod's image, applies the finish Job (with its +# ServiceAccount and ClusterRoleBinding), and stamps the version. The Job +# manifest and the version stamp both arrive as `apply --filename -`, so this +# fake reads stdin and branches on the manifest's kind. +# +# FAKE_CMDLOG file to append a one-line record of each call to +# FAKE_IMAGE image the `get pod` call returns (default a test ref) +# FAKE_IMAGE_EMPTY non-empty => `get pod` returns an empty image +# FAKE_GETPOD_FAIL non-empty => `get pod` exits 1 with this stderr +# FAKE_APPLY_FAIL non-empty => applying the Job exits 1 with this stderr +set -u + +log() { [ -n "${FAKE_CMDLOG:-}" ] && printf '%s\n' "$*" >> "$FAKE_CMDLOG"; } +log "KUBECTL $*" + +args="$*" +IMAGE="${FAKE_IMAGE:-registry.example.org/cozystack/cozystack:v1.7.0}" + +case "$args" in + *"get pod"*jsonpath*) + if [ -n "${FAKE_GETPOD_FAIL:-}" ]; then + printf '%s\n' "$FAKE_GETPOD_FAIL" >&2 + exit 1 + fi + [ -n "${FAKE_IMAGE_EMPTY:-}" ] || printf '%s' "$IMAGE" + exit 0 + ;; + + *"delete job cozystack-credentials-migration-68"*) + # The hook deletes a Job left by an earlier run before recreating it. + log "DELETE-JOB" + exit 0 + ;; + + *"delete serviceaccount cozystack-credentials-migration-68"*) + # The hook deletes a ServiceAccount left owned by the Job it just deleted, + # so the apply recreates a fresh, owner-less one. + log "DELETE-SA" + exit 0 + ;; + + *"get job cozystack-credentials-migration-68"*jsonpath*) + # The hook reads the Job's uid to own its ServiceAccount. + if [ -n "${FAKE_GETJOB_FAIL:-}" ]; then + printf '%s\n' "$FAKE_GETJOB_FAIL" >&2 + exit 1 + fi + [ -n "${FAKE_JOBUID_EMPTY:-}" ] || printf '%s' "11111111-2222-3333-4444-555555555555" + exit 0 + ;; + + *"patch serviceaccount cozystack-credentials-migration-68"*) + # The ownerReference tying the ServiceAccount to the Job. + if [ -n "${FAKE_PATCH_FAIL:-}" ]; then + printf '%s\n' "$FAKE_PATCH_FAIL" >&2 + exit 1 + fi + owner=$(printf '%s' "$args" | grep -c 'cozystack-credentials-migration-68') + log "PATCH-SA-OWNER owner=$owner" + exit 0 + ;; + + *"apply --filename -"*) + manifest=$(cat) + case "$manifest" in + *"kind: ConfigMap"*) + v=$(printf '%s\n' "$manifest" | sed -n 's/^ version: "\{0,1\}\([0-9]\{1,\}\)"\{0,1\}$/\1/p' | head -1) + log "STAMP ${v:-unknown}" + exit 0 + ;; + *"kind: Job"*) + if [ -n "${FAKE_APPLY_FAIL:-}" ]; then + printf '%s\n' "$FAKE_APPLY_FAIL" >&2 + exit 1 + fi + # Record the fields the Job must carry, so a copy that drops the + # ServiceAccount, names the wrong migration, or renders the wrong image + # is caught. + role=$(printf '%s\n' "$manifest" | grep -c '^kind: ClusterRole$') + sa=$(printf '%s\n' "$manifest" | grep -c '^kind: ServiceAccount$') + crb=$(printf '%s\n' "$manifest" | grep -c '^kind: ClusterRoleBinding$') + # The binding must grant the least-privilege role, never cluster-admin. + admin=$(printf '%s\n' "$manifest" | grep -c 'cluster-admin') + # The ServiceAccount, ClusterRole and binding share the Job's name, so + # count the name inside the Job document only. + jobname=$(printf '%s\n' "$manifest" | awk '/^kind: Job$/ { j = 1 } j && /^ name: cozystack-credentials-migration-68$/ { c++ } END { print c + 0 }') + mig=$(printf '%s\n' "$manifest" | grep -c -- '--migration=68') + img=$(printf '%s\n' "$manifest" | grep -c "^ image: ${IMAGE}$") + sacc=$(printf '%s\n' "$manifest" | grep -c '^ serviceAccountName: cozystack-credentials-migration-68$') + # RabbitMQ finish reads the per-user sources by label, hides the + # operator's administrator Secret, and needs list on Secrets for it. + selector=$(printf '%s\n' "$manifest" | grep -c -- '--source-selector=apps.cozystack.io/user-secret=true') + key=$(printf '%s\n' "$manifest" | grep -c -- '--source-key=password') + hide=$(printf '%s\n' "$manifest" | grep -c -- '--hide-secret-suffix=-default-user') + list=$(printf '%s\n' "$manifest" | grep -c 'verbs: \["get", "list", "create", "patch", "delete"\]') + log "APPLY-RABBITMQ selector=$selector key=$key hide=$hide list=$list" + # It reads the definitions to hide -default-user only once they do. + appdefs=$(printf '%s\n' "$manifest" | grep -c '^ resources: \["applicationdefinitions"\]$') + log "APPLY-FINISH role=$role sa=$sa crb=$crb admin=$admin jobname=$jobname migration=$mig image=$img serviceaccount=$sacc appdefs=$appdefs" + exit 0 + ;; + *) + log "APPLY-UNKNOWN" + printf 'fake kubectl: unmodelled apply\n' >&2 + exit 1 + ;; + esac + ;; +esac + +log "UNHANDLED $args" +printf 'fake kubectl: unmodelled call: %s\n' "$args" >&2 +exit 1 diff --git a/hack/testdata/migration-69-70-redis-valkey-credentials/credentials-migrate b/hack/testdata/migration-69-70-redis-valkey-credentials/credentials-migrate new file mode 100755 index 000000000..d479876c2 --- /dev/null +++ b/hack/testdata/migration-69-70-redis-valkey-credentials/credentials-migrate @@ -0,0 +1,22 @@ +#!/bin/sh +# Fake credentials-migrate for hack/migration-69-70-redis-valkey-credentials.bats. +# Migrations 69 and 70 run `credentials-migrate seed` in the hook; the real binary is +# exercised by cmd/credentials-migrate's Go tests, so this fake only records the +# call and fails on demand to pin the hook's fail-closed behaviour. +# +# FAKE_CMDLOG file to append a one-line record of each call to +# FAKE_SEED_FAIL non-empty => `seed` exits 1 with this stderr +set -u + +[ -n "${FAKE_CMDLOG:-}" ] && printf 'CREDMIGRATE %s\n' "$*" >> "$FAKE_CMDLOG" + +case "${1:-}" in + seed) + if [ -n "${FAKE_SEED_FAIL:-}" ]; then + printf '%s\n' "$FAKE_SEED_FAIL" >&2 + exit 1 + fi + exit 0 + ;; +esac +exit 0 diff --git a/hack/testdata/migration-69-70-redis-valkey-credentials/kubectl b/hack/testdata/migration-69-70-redis-valkey-credentials/kubectl new file mode 100755 index 000000000..387fb5e8d --- /dev/null +++ b/hack/testdata/migration-69-70-redis-valkey-credentials/kubectl @@ -0,0 +1,119 @@ +#!/bin/sh +# Fake kubectl for hack/migration-69-70-redis-valkey-credentials.bats, the +# one hack/testdata/migration-64-postgres-credentials/kubectl is with the +# migration number taken from $FAKE_MIGRATION. It serves only the calls +# migrations 69 and 70 and lib/cozystack-version.sh make, and logs each one +# to $FAKE_CMDLOG. +# +# Each migration reads its own pod's image, applies the finish Job (with its +# ServiceAccount and ClusterRoleBinding), and stamps the version. The Job +# manifest and the version stamp both arrive as `apply --filename -`, so this +# fake reads stdin and branches on the manifest's kind. +# +# FAKE_MIGRATION number of the migration under test +# FAKE_CMDLOG file to append a one-line record of each call to +# FAKE_IMAGE image the `get pod` call returns (default a test ref) +# FAKE_IMAGE_EMPTY non-empty => `get pod` returns an empty image +# FAKE_GETPOD_FAIL non-empty => `get pod` exits 1 with this stderr +# FAKE_APPLY_FAIL non-empty => applying the Job exits 1 with this stderr +set -u + +log() { [ -n "${FAKE_CMDLOG:-}" ] && printf '%s\n' "$*" >> "$FAKE_CMDLOG"; } +log "KUBECTL $*" + +args="$*" +IMAGE="${FAKE_IMAGE:-registry.example.org/cozystack/cozystack:v1.7.0}" +N="${FAKE_MIGRATION:?FAKE_MIGRATION is required}" +NAME="cozystack-credentials-migration-$N" + +case "$args" in + *"get pod"*jsonpath*) + if [ -n "${FAKE_GETPOD_FAIL:-}" ]; then + printf '%s\n' "$FAKE_GETPOD_FAIL" >&2 + exit 1 + fi + [ -n "${FAKE_IMAGE_EMPTY:-}" ] || printf '%s' "$IMAGE" + exit 0 + ;; + + *"delete job $NAME "*) + # The hook deletes a Job left by an earlier run before recreating it. + log "DELETE-JOB" + exit 0 + ;; + + *"delete serviceaccount $NAME "*) + # The hook deletes a ServiceAccount left owned by the Job it just deleted, + # so the apply recreates a fresh, owner-less one. + log "DELETE-SA" + exit 0 + ;; + + *"get job $NAME "*jsonpath*) + # The hook reads the Job's uid to own its ServiceAccount. + if [ -n "${FAKE_GETJOB_FAIL:-}" ]; then + printf '%s\n' "$FAKE_GETJOB_FAIL" >&2 + exit 1 + fi + [ -n "${FAKE_JOBUID_EMPTY:-}" ] || printf '%s' "11111111-2222-3333-4444-555555555555" + exit 0 + ;; + + *"patch serviceaccount $NAME "*) + # The ownerReference tying the ServiceAccount to the Job. + if [ -n "${FAKE_PATCH_FAIL:-}" ]; then + printf '%s\n' "$FAKE_PATCH_FAIL" >&2 + exit 1 + fi + owner=$(printf '%s' "$args" | grep -c "\"name\":\"$NAME\"") + log "PATCH-SA-OWNER owner=$owner" + exit 0 + ;; + + *"apply --filename -"*) + manifest=$(cat) + case "$manifest" in + *"kind: ConfigMap"*) + v=$(printf '%s\n' "$manifest" | sed -n 's/^ version: "\{0,1\}\([0-9]\{1,\}\)"\{0,1\}$/\1/p' | head -1) + log "STAMP ${v:-unknown}" + exit 0 + ;; + *"kind: Job"*) + if [ -n "${FAKE_APPLY_FAIL:-}" ]; then + printf '%s\n' "$FAKE_APPLY_FAIL" >&2 + exit 1 + fi + # Record the fields the Job must carry, so a copy that drops the + # ServiceAccount, names the wrong migration, or renders the wrong image + # is caught. + role=$(printf '%s\n' "$manifest" | grep -c '^kind: ClusterRole$') + sa=$(printf '%s\n' "$manifest" | grep -c '^kind: ServiceAccount$') + crb=$(printf '%s\n' "$manifest" | grep -c '^kind: ClusterRoleBinding$') + # The binding must grant the least-privilege role, never cluster-admin. + admin=$(printf '%s\n' "$manifest" | grep -c 'cluster-admin') + mig=$(printf '%s\n' "$manifest" | grep -c -- "--migration=$N\$") + # The Job finishes the kind with the same accounts the hook seeded. + fixed=$(printf '%s\n' "$manifest" | grep -c -e '- --fixed-account=default$' -e '- --source-key=password$' -e '- --enabled-flag=authEnabled$' -e '- --source-suffix=-auth$' -e '- --format=plaintext$') + actor=$(printf '%s\n' "$manifest" | grep -c "value: system:serviceaccount:.*:$NAME\$") + img=$(printf '%s\n' "$manifest" | grep -c "^ image: ${IMAGE}$") + sacc=$(printf '%s\n' "$manifest" | grep -c "^ serviceAccountName: $NAME\$") + # ClusterRole, ServiceAccount, ClusterRoleBinding and Job, each named for + # the migration, so two conversions in one upgrade do not share them. + named=$(printf '%s\n' "$manifest" | grep -c "^ name: $NAME\$") + # It reads Deployments to resume the held releases after the rollout. + deploy=$(printf '%s\n' "$manifest" | grep -c '^ resources: \["deployments"\]$') + log "APPLY-FINISH role=$role sa=$sa crb=$crb admin=$admin migration=$mig image=$img serviceaccount=$sacc fixed=$fixed actor=$actor named=$named deployments=$deploy" + exit 0 + ;; + *) + log "APPLY-UNKNOWN" + printf 'fake kubectl: unmodelled apply\n' >&2 + exit 1 + ;; + esac + ;; +esac + +log "UNHANDLED $args" +printf 'fake kubectl: unmodelled call: %s\n' "$args" >&2 +exit 1 diff --git a/hack/testdata/migration-71-bucket-credentials/kubectl b/hack/testdata/migration-71-bucket-credentials/kubectl new file mode 100755 index 000000000..ed8717034 --- /dev/null +++ b/hack/testdata/migration-71-bucket-credentials/kubectl @@ -0,0 +1,111 @@ +#!/bin/sh +# Fake kubectl for hack/migration-71-bucket-credentials.bats, modelled on +# hack/testdata/migration-64-postgres-credentials/kubectl. It serves only the +# calls migration 71, lib/credential-crd.sh and lib/cozystack-version.sh +# make, and logs each one to $FAKE_CMDLOG. +# +# FAKE_CMDLOG file to append a one-line record of each call to +# FAKE_BACKUP_NS backupStorage.namespace of backupstrategy-controller +# FAKE_BACKUP_BUCKET backupStorage.bucketName of backupstrategy-controller +# FAKE_NO_SYSTEM non-empty => the backup Bucket release has no system user +# FAKE_NO_CRD non-empty => the BucketAccess CRD is not installed +# FAKE_ACCESSES the BucketAccess listing, one line per object: +# namespace name release class controller-kind +# FAKE_CLASSES the BucketAccessClass listing, one line per object: +# name accessPolicy +# FAKE_CLASS_FAIL non-empty => listing BucketAccessClasses exits 1 +# FAKE_LIST_FAIL non-empty => listing BucketAccesses exits 1 +# FAKE_LABEL_FAIL non-empty => labelling a BucketAccess exits 1 +# FAKE_KEYLESS space-separated Secret names that hold no keys +# FAKE_STRIP_FAIL non-empty => patching a credentials Secret exits 1 +# FAKE_CRD_FAIL non-empty => applying the CredentialTemplate CRD exits 1 +set -u + +log() { [ -n "${FAKE_CMDLOG:-}" ] && printf '%s\n' "$*" >> "$FAKE_CMDLOG"; } +log "KUBECTL $*" + +args="$*" +ns_of() { printf '%s\n' "$args" | sed -n 's/.*--namespace \([^ ]*\).*/\1/p'; } + +case "$args" in + *"apply --server-side --force-conflicts --filename "*credentialtemplates*) + log "CRD apply" + [ -n "${FAKE_CRD_FAIL-}" ] && exit 1 + exit 0 ;; + *"label crd credentialtemplates.cozystack.io app.kubernetes.io/managed-by=Helm"*) + log "CRD label"; exit 0 ;; + *"annotate crd credentialtemplates.cozystack.io"*"meta.helm.sh/release-name=cozystack-controller"*"meta.helm.sh/release-namespace=cozy-system"*) + log "CRD annotate"; exit 0 ;; + *"wait --for=condition=established crd/credentialtemplates.cozystack.io"*) + log "CRD established"; exit 0 ;; + *"get helmreleases.helm.toolkit.fluxcd.io backupstrategy-controller"*"backupStorage.namespace"*) + printf '%s' "${FAKE_BACKUP_NS:-}"; exit 0 ;; + *"get helmreleases.helm.toolkit.fluxcd.io backupstrategy-controller"*"backupStorage.bucketName"*) + printf '%s' "${FAKE_BACKUP_BUCKET:-}"; exit 0 ;; + *"get helmreleases.helm.toolkit.fluxcd.io backupstrategy-controller"*"backupStorage.provisionBucket"*) + exit 0 ;; + *"get helmreleases.helm.toolkit.fluxcd.io bucket-"*"users.system"*) + [ -n "${FAKE_NO_SYSTEM:-}" ] || printf '%s' '{"readonly":false}' + exit 0 ;; + *"patch helmreleases.helm.toolkit.fluxcd.io "*) + name=$(printf '%s\n' "$args" | sed -n 's/.*patch helmreleases.helm.toolkit.fluxcd.io \([^ ]*\).*/\1/p') + platform=$(printf '%s\n' "$args" | grep -c '"system":{"platform":true}') + log "PATCH-PLATFORM $(ns_of)/$name platform=$platform" + exit 0 ;; + *"get customresourcedefinitions.apiextensions.k8s.io bucketaccesses.objectstorage.k8s.io"*) + [ -n "${FAKE_NO_CRD:-}" ] || printf '%s\n' "customresourcedefinition.apiextensions.k8s.io/bucketaccesses.objectstorage.k8s.io" + exit 0 ;; + *"get bucketaccessclasses.objectstorage.k8s.io "*"parameters.accessPolicy"*) + if [ -n "${FAKE_CLASS_FAIL:-}" ]; then + printf '%s\n' "$FAKE_CLASS_FAIL" >&2; exit 1 + fi + printf '%s\n' "${FAKE_CLASSES:-}" + exit 0 ;; + *"get bucketaccesses.objectstorage.k8s.io --all-namespaces"*"spec.bucketAccessClassName"*) + if [ -n "${FAKE_LIST_FAIL:-}" ]; then + printf '%s\n' "$FAKE_LIST_FAIL" >&2; exit 1 + fi + printf '%s\n' "${FAKE_ACCESSES:-}" + exit 0 ;; + *"get secrets "*"go-template="*) + name=$(printf '%s\n' "$args" | sed -n 's/.*get secrets \([^ ]*\).*/\1/p') + # The check must not read the key values out. + case "$args" in *"jsonpath"*) log "READ-KEYS $name"; exit 1 ;; esac + case " ${FAKE_KEYLESS:-} " in *" $name "*) exit 0 ;; esac + printf '%s' held + exit 0 ;; + *"patch secrets "*) + if [ -n "${FAKE_STRIP_FAIL:-}" ]; then + printf '%s\n' "$FAKE_STRIP_FAIL" >&2; exit 1 + fi + name=$(printf '%s\n' "$args" | sed -n 's/.*patch secrets \([^ ]*\).*/\1/p') + strip=$(printf '%s\n' "$args" | grep -c '"accessKey":null,"secretKey":null') + log "STRIP $(ns_of)/$name strip=$strip" + exit 0 ;; + *"annotate bucketaccesses.objectstorage.k8s.io "*) + name=$(printf '%s\n' "$args" | sed -n 's/.*annotate bucketaccesses.objectstorage.k8s.io \([^ ]*\).*/\1/p') + keep=$(printf '%s\n' "$args" | grep -c 'helm.sh/resource-policy=keep') + log "KEEP $(ns_of)/$name keep=$keep" + exit 0 ;; + *"label bucketaccesses.objectstorage.k8s.io "*) + if [ -n "${FAKE_LABEL_FAIL:-}" ]; then + printf '%s\n' "$FAKE_LABEL_FAIL" >&2; exit 1 + fi + name=$(printf '%s\n' "$args" | sed -n 's/.*label bucketaccesses.objectstorage.k8s.io \([^ ]*\).*/\1/p') + adopt=$(printf '%s\n' "$args" | grep -c 'credentials.cozystack.io/adopt=true') + log "ADOPT $(ns_of)/$name adopt=$adopt" + exit 0 ;; + *"apply --filename -"*) + manifest=$(cat) + case "$manifest" in + *"kind: ConfigMap"*) + v=$(printf '%s\n' "$manifest" | sed -n 's/^ version: "\{0,1\}\([0-9]\{1,\}\)"\{0,1\}$/\1/p' | head -1) + log "STAMP ${v:-unknown}" + exit 0 ;; + esac + ;; +esac + +log "UNHANDLED $args" +printf 'fake kubectl: unmodelled call: %s\n' "$args" >&2 +exit 1 diff --git a/internal/controller/credentialtemplate_controller.go b/internal/controller/credentialtemplate_controller.go index 36e7e6fdc..ebdb2032c 100644 --- a/internal/controller/credentialtemplate_controller.go +++ b/internal/controller/credentialtemplate_controller.go @@ -49,6 +49,7 @@ const CredentialControllerActor = "system:serviceaccount:cozy-system:cozystack-c const ( reasonCredentialReset = "CredentialReset" reasonCredentialAdopted = "CredentialAdopted" + reasonCredentialRevoked = "CredentialRevoked" ) // CredentialTemplateReconciler keeps each CredentialTemplate and its account @@ -87,6 +88,10 @@ func (r *CredentialTemplateReconciler) Reconcile(ctx context.Context, req ctrl.R if !tmpl.DeletionTimestamp.IsZero() { return ctrl.Result{}, nil } + if engineIssued(tmpl) { + // The engine issues these keys; COSICredentialReconciler keeps them. + return ctrl.Result{}, nil + } status := tmpl.Status.DeepCopy() status.ObservedGeneration = tmpl.Generation @@ -312,12 +317,17 @@ func mirror(status *cozyv1alpha1.CredentialTemplateStatus, sec *corev1.Secret) { } func (r *CredentialTemplateReconciler) writeStatus(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate, status *cozyv1alpha1.CredentialTemplateStatus) error { + return writeTemplateStatus(ctx, r.Client, tmpl, status) +} + +// writeTemplateStatus writes a template's status when it changed. +func writeTemplateStatus(ctx context.Context, c client.Client, tmpl *cozyv1alpha1.CredentialTemplate, status *cozyv1alpha1.CredentialTemplateStatus) error { if equality.Semantic.DeepEqual(&tmpl.Status, status) { return nil } updated := tmpl.DeepCopy() updated.Status = *status - return r.Status().Update(ctx, updated) + return c.Status().Update(ctx, updated) } // SetupWithManager registers the reconciler. accountSecrets is a metadata diff --git a/internal/controller/credentialtemplate_cosi.go b/internal/controller/credentialtemplate_cosi.go new file mode 100644 index 000000000..cd22246a0 --- /dev/null +++ b/internal/controller/credentialtemplate_cosi.go @@ -0,0 +1,716 @@ +// SPDX-License-Identifier: Apache-2.0 + +package controller + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "fmt" + "time" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/tools/record" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/builder" + "sigs.k8s.io/controller-runtime/pkg/cache" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/predicate" + "sigs.k8s.io/controller-runtime/pkg/source" + + cosiapi "sigs.k8s.io/container-object-storage-interface-api/apis" + cosiv1alpha1 "sigs.k8s.io/container-object-storage-interface-api/apis/objectstorage/v1alpha1" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" + "github.com/cozystack/cozystack/pkg/credentials/account" +) + +// +kubebuilder:rbac:groups=objectstorage.k8s.io,resources=bucketaccesses,verbs=get;list;watch;create;update;delete +// +kubebuilder:rbac:groups=objectstorage.k8s.io,resources=bucketaccessclasses;bucketclaims,verbs=get + +const ( + // cosiRequeue is how soon the reconciler looks again while the COSI + // sidecar revokes or grants. Both end in a BucketAccess change the + // reconciler watches; the requeue covers the Secret the sidecar writes, + // which it does not. + cosiRequeue = 2 * time.Second + // cosiGrantRequeue is how soon the reconciler looks again at a + // BucketAccess it waits to delete until the sidecar finishes granting it. + // Finishing adds a finalizer, a change the reconciler watches, so this + // only backs the watch up. + cosiGrantRequeue = 30 * time.Second + // bucketAccessFinalizer is what the COSI sidecar puts on a BucketAccess + // once the driver has granted it and the sidecar has written its Secret, + // before it reports AccessGranted; from then on a delete runs the driver + // revoke and removes that Secret (objectstorage-sidecar v0.2.2, + // sidecar/pkg/bucketaccess/bucketaccess_controller.go, Add and + // deleteBucketAccessOp; client/apis/objectstorage/consts BAFinalizer). + bucketAccessFinalizer = "cosi.objectstorage.k8s.io/bucketaccess-protection" + // bucketInfoKey is the one data key of the Secret the COSI sidecar + // writes for a BucketAccess. + bucketInfoKey = "BucketInfo" + // bucketInfoPrefix is how the sidecar names the BucketInfo it writes + // for a BucketAccess, followed by that BucketAccess's UID, which tells a + // Secret of the live grant from one a deleted BucketAccess left behind. + bucketInfoPrefix = "bc-" + // s3Protocol is the protocol the bucket chart has always requested. + s3Protocol = cosiv1alpha1.Protocol("s3") + // templateFinalizer holds a deleted engine-issued template until its + // BucketAccess can be deleted without leaving an identity behind. + templateFinalizer = "credentials.cozystack.io/bucket-access" +) + +// COSICredentialReconciler keeps the account of an engine-issued +// CredentialTemplate, whose keys the COSI driver issues: it creates and owns +// the BucketAccess the template names, adopts one the conversion marked, and +// copies the keys of the live grant into the account Secret. A mint or a +// revoke reaches it as a request id the API writes with the Secret. A +// BucketAccess not created for the current mint is deleted, so the sidecar +// revokes its identity, and a new one is created for the mint. A revoke +// deletes it and creates none, so the account holds no keys until the next +// mint, and the Secret is marked served once the BucketAccess is gone. A +// BucketAccess is deleted only once the sidecar has finalized its grant, or +// once the sidecar can no longer grant it: a delete inside the grant window +// skips the driver revoke and leaves the identity behind. That holds for a +// deleted template too, which a finalizer keeps until its BucketAccess is +// deleted that way; the cleanup of a template that was deleted before it got +// the finalizer, and the garbage collection through the owner reference, do +// not check it. A revoke is recorded in the account Secret and mirrored into +// the template's status; an account Secret lost after a revoke is written +// again from that status as revoked, so the account gets no keys until the +// next mint. The template's status mirrors the account Secret as the latest request left it, +// granted or not, so a request that never completes does not block the next +// one. A grant the template's claim or class no longer matches, after a change +// of the user's readonly flag or of the storage pool, is recorded as a revoke +// by the controller: the BucketAccess goes, none replaces it, and the account +// holds no keys until the next mint, which is granted under the new class. +// CredentialTemplateReconciler skips these templates. See +// design-proposals/user-secrets-api in cozystack/community. +// +// Secrets are read through Reader, uncached, for the reason +// CredentialTemplateReconciler gives. +type COSICredentialReconciler struct { + client.Client + Reader client.Reader + Scheme *runtime.Scheme + Recorder record.EventRecorder + Now func() time.Time +} + +func (r *COSICredentialReconciler) now() metav1.Time { + if r.Now != nil { + return metav1.NewTime(r.Now()) + } + return metav1.Now() +} + +// engineIssued reports whether the COSI driver issues a template's keys, +// which a template says by naming a BucketAccess, whatever its format. +func engineIssued(tmpl *cozyv1alpha1.CredentialTemplate) bool { + return tmpl.Spec.BucketAccess != nil +} + +func (r *COSICredentialReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + tmpl := &cozyv1alpha1.CredentialTemplate{} + if err := r.Get(ctx, req.NamespacedName, tmpl); err != nil { + if apierrors.IsNotFound(err) { + return ctrl.Result{}, r.cleanup(ctx, req.NamespacedName) + } + return ctrl.Result{}, err + } + if !tmpl.DeletionTimestamp.IsZero() { + return r.finalize(ctx, tmpl) + } + if !engineIssued(tmpl) { + return ctrl.Result{}, nil + } + if !controllerutil.ContainsFinalizer(tmpl, templateFinalizer) { + patch := client.MergeFromWithOptions(tmpl.DeepCopy(), client.MergeFromWithOptimisticLock{}) + controllerutil.AddFinalizer(tmpl, templateFinalizer) + if err := r.Patch(ctx, tmpl, patch); err != nil { + return ctrl.Result{}, err + } + } + status := tmpl.Status.DeepCopy() + status.ObservedGeneration = tmpl.Generation + + sec, err := r.accountSecret(ctx, tmpl) + if err != nil { + return ctrl.Result{}, err + } + if sec != nil && !metav1.IsControlledBy(sec, tmpl) { + meta.SetStatusCondition(&status.Conditions, metav1.Condition{ + Type: cozyv1alpha1.CredentialTemplateSecretConflict, + Status: metav1.ConditionTrue, + Reason: "ForeignSecret", + Message: fmt.Sprintf("Secret %s exists and was not created for this template; remove it to let the account be issued", sec.Name), + }) + mirror(status, nil) + return ctrl.Result{}, writeTemplateStatus(ctx, r.Client, tmpl, status) + } + meta.RemoveStatusCondition(&status.Conditions, cozyv1alpha1.CredentialTemplateSecretConflict) + + if sec == nil && tmpl.Status.Password.Origin == string(corev1alpha1.CredentialOriginRevoked) { + // The revoke the status mirrors is the account's latest request, and + // its Secret is gone: without it the create branch below would grant + // working keys nobody asked for. A mint writes the Secret, so none + // is pending. + if err := r.restoreRevoked(ctx, tmpl); err != nil { + return ctrl.Result{}, err + } + return ctrl.Result{Requeue: true}, nil + } + + ba, err := r.bucketAccess(ctx, tmpl) + if err != nil { + return ctrl.Result{}, err + } + request := "" + switch { + case sec != nil: + request = sec.Annotations[account.RequestAnnotation] + case ba != nil && metav1.IsControlledBy(ba, tmpl): + // The account Secret is gone while its grant lives on: the Secret is + // written again from that grant, rather than the BucketAccess being + // re-created under the clients that hold its keys. + request = ba.Annotations[account.RequestAnnotation] + } + revoked := sec != nil && request != "" && account.ReadRecord(sec).Origin == corev1alpha1.CredentialOriginRevoked + // waiting mirrors the account Secret as the latest request left it, so + // the next mint or revoke writes over that version instead of failing on + // the one before a request that has not completed. + waiting := func(after time.Duration) (ctrl.Result, error) { + mirror(status, sec) + return ctrl.Result{RequeueAfter: after}, writeTemplateStatus(ctx, r.Client, tmpl, status) + } + + switch { + case ba == nil && revoked: + served, err := r.store(ctx, tmpl, sec, nil, nil, request) + if err != nil { + return ctrl.Result{}, err + } + mirror(status, served) + return ctrl.Result{}, writeTemplateStatus(ctx, r.Client, tmpl, status) + case ba == nil: + if err := r.createBucketAccess(ctx, tmpl, request); err != nil { + return ctrl.Result{}, err + } + return waiting(cosiRequeue) + case !ba.DeletionTimestamp.IsZero(): + // The sidecar is revoking it. + return waiting(cosiRequeue) + case !metav1.IsControlledBy(ba, tmpl): + if !bucketAccessAdoptable(ba, tmpl) { + meta.SetStatusCondition(&status.Conditions, metav1.Condition{ + Type: cozyv1alpha1.CredentialTemplateBucketAccessConflict, + Status: metav1.ConditionTrue, + Reason: "ForeignBucketAccess", + Message: fmt.Sprintf("BucketAccess %s exists and was not created for this template", ba.Name), + }) + mirror(status, sec) + return ctrl.Result{}, writeTemplateStatus(ctx, r.Client, tmpl, status) + } + if ba, err = r.adopt(ctx, tmpl, ba); err != nil { + return ctrl.Result{}, err + } + } + meta.RemoveStatusCondition(&status.Conditions, cozyv1alpha1.CredentialTemplateBucketAccessConflict) + + if sec != nil && !revoked && ba.Annotations[account.RequestAnnotation] == request && grantChanged(ba, tmpl) { + revokedSec, err := r.revokeForChange(ctx, tmpl, sec) + if err != nil { + return ctrl.Result{}, err + } + sec = revokedSec + return waiting(cosiRequeue) + } + if revoked || stale(ba, tmpl, request) { + if !controllerutil.ContainsFinalizer(ba, bucketAccessFinalizer) { + // The driver may already have granted an identity the sidecar + // has not finalized yet; deleting now would skip its revoke. + return waiting(cosiGrantRequeue) + } + // Deleting it makes the sidecar revoke the identity behind the keys + // the account held; for a mint, the next pass creates one for the + // request. + if err := r.Delete(ctx, ba, client.Preconditions{UID: &ba.UID}); client.IgnoreNotFound(err) != nil { + return ctrl.Result{}, err + } + return waiting(cosiRequeue) + } + if !ba.Status.AccessGranted { + return waiting(cosiRequeue) + } + keys, err := r.issuedKeys(ctx, ba) + if err != nil { + return ctrl.Result{}, err + } + if keys == nil { + return waiting(cosiRequeue) + } + stored, err := r.store(ctx, tmpl, sec, ba, keys, request) + if err != nil { + return ctrl.Result{}, err + } + if stored == nil { + // A mint created the Secret in between; serve its request next. + return ctrl.Result{Requeue: true}, nil + } + mirror(status, stored) + return ctrl.Result{}, writeTemplateStatus(ctx, r.Client, tmpl, status) +} + +func (r *COSICredentialReconciler) accountSecret(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate) (*corev1.Secret, error) { + sec := &corev1.Secret{} + err := r.Reader.Get(ctx, types.NamespacedName{Namespace: tmpl.Namespace, Name: tmpl.Name + account.SecretSuffix}, sec) + if apierrors.IsNotFound(err) { + return nil, nil + } + if err != nil { + return nil, err + } + return sec, nil +} + +func (r *COSICredentialReconciler) bucketAccess(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate) (*cosiv1alpha1.BucketAccess, error) { + ba := &cosiv1alpha1.BucketAccess{} + err := r.Get(ctx, types.NamespacedName{Namespace: tmpl.Namespace, Name: tmpl.Spec.BucketAccess.Name}, ba) + if apierrors.IsNotFound(err) { + return nil, nil + } + if err != nil { + return nil, err + } + return ba, nil +} + +// createBucketAccess creates the BucketAccess of a template for a request. +// The request annotation is present even when empty, which tells a +// BucketAccess the controller created from one it adopted. +func (r *COSICredentialReconciler) createBucketAccess(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate, request string) error { + spec := tmpl.Spec.BucketAccess + ba := &cosiv1alpha1.BucketAccess{ + ObjectMeta: metav1.ObjectMeta{ + Name: spec.Name, + Namespace: tmpl.Namespace, + Annotations: map[string]string{account.RequestAnnotation: request}, + }, + Spec: cosiv1alpha1.BucketAccessSpec{ + BucketClaimName: spec.BucketClaimName, + BucketAccessClassName: spec.BucketAccessClassName, + CredentialsSecretName: spec.Name, + Protocol: s3Protocol, + }, + } + if err := controllerutil.SetControllerReference(tmpl, ba, r.Scheme); err != nil { + return err + } + if err := r.Create(ctx, ba); err != nil && !apierrors.IsAlreadyExists(err) { + return err + } + return nil +} + +// bucketAccessAdoptable reports whether a BucketAccess the controller did not +// create is one the conversion marked for this template: the marker, no +// controller, and the template's own claim and class. +func bucketAccessAdoptable(ba *cosiv1alpha1.BucketAccess, tmpl *cozyv1alpha1.CredentialTemplate) bool { + return ba.Labels[account.AdoptLabel] == "true" && + metav1.GetControllerOf(ba) == nil && + ba.Spec.BucketClaimName == tmpl.Spec.BucketAccess.BucketClaimName && + ba.Spec.BucketAccessClassName == tmpl.Spec.BucketAccess.BucketAccessClassName +} + +// adopt takes over a BucketAccess the chart rendered before the conversion, +// keeping its grant and so its keys. It carries no request annotation, which +// is how the first copy of its keys is recorded as migrated. +func (r *COSICredentialReconciler) adopt(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate, ba *cosiv1alpha1.BucketAccess) (*cosiv1alpha1.BucketAccess, error) { + updated := ba.DeepCopy() + if err := controllerutil.SetControllerReference(tmpl, updated, r.Scheme); err != nil { + return nil, err + } + if err := r.Update(ctx, updated); err != nil { + return nil, err + } + if r.Recorder != nil { + r.Recorder.Event(tmpl, corev1.EventTypeNormal, reasonCredentialAdopted, "adopted the BucketAccess the conversion marked, keeping its keys") + } + return updated, nil +} + +// stale reports whether a BucketAccess no longer serves its template: it was +// created for another request than the account Secret's latest, or for +// another claim or class. +func stale(ba *cosiv1alpha1.BucketAccess, tmpl *cozyv1alpha1.CredentialTemplate, request string) bool { + return ba.Annotations[account.RequestAnnotation] != request || grantChanged(ba, tmpl) +} + +// grantChanged reports whether a BucketAccess was created for another claim +// or class than the template now names, as after a change of the user's +// readonly flag or of the bucket's storage pool. +func grantChanged(ba *cosiv1alpha1.BucketAccess, tmpl *cozyv1alpha1.CredentialTemplate) bool { + return ba.Spec.BucketClaimName != tmpl.Spec.BucketAccess.BucketClaimName || + ba.Spec.BucketAccessClassName != tmpl.Spec.BucketAccess.BucketAccessClassName +} + +// revokeForChange records a grant the template no longer matches as a revoke +// by the controller and returns the Secret as written. The account Secret +// loses its keys and gets a request id of its own, as a revoke through the API +// writes it, so the revoke path deletes the BucketAccess and creates none: +// the new class takes effect with the next mint, whose keys are the first +// anyone is shown. Re-granting at once instead would leave keys nobody was +// shown behind a record that says the last mint issued the live ones. A +// request the Secret already carries is served first: a pending mint creates +// its BucketAccess with the new class anyway. +func (r *COSICredentialReconciler) revokeForChange(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate, sec *corev1.Secret) (*corev1.Secret, error) { + id, err := requestID() + if err != nil { + return nil, err + } + updated := sec.DeepCopy() + updated.Data = map[string][]byte{account.UsernameKey: []byte(tmpl.Spec.Username)} + if updated.Annotations == nil { + updated.Annotations = map[string]string{} + } + updated.Annotations[account.RequestAnnotation] = id + account.WriteRecord(updated, account.ReadRecord(sec).Apply(corev1alpha1.CredentialOperationRevoke, r.now(), CredentialControllerActor)) + // Written under the version read at the start of this pass: a mint in + // between fails it, and the next pass serves that mint instead. + if err := r.Update(ctx, updated); err != nil { + return nil, err + } + if r.Recorder != nil { + r.Recorder.Event(tmpl, corev1.EventTypeNormal, reasonCredentialRevoked, + "the bucket access class or claim changed: revoked the keys of the old grant; mint to get keys under the new one") + } + return updated, nil +} + +func requestID() (string, error) { + b := make([]byte, 16) + if _, err := rand.Read(b); err != nil { + return "", err + } + return hex.EncodeToString(b), nil +} + +// s3Keys is one issued key pair. +type s3Keys struct { + accessKeyID string + secretKey string +} + +// issuedKeys reads the keys of a granted BucketAccess from the Secret the +// sidecar wrote for it; nil while that Secret is missing, or is one an +// earlier BucketAccess of the same name left behind. +func (r *COSICredentialReconciler) issuedKeys(ctx context.Context, ba *cosiv1alpha1.BucketAccess) (*s3Keys, error) { + src := &corev1.Secret{} + err := r.Reader.Get(ctx, types.NamespacedName{Namespace: ba.Namespace, Name: ba.Spec.CredentialsSecretName}, src) + if apierrors.IsNotFound(err) { + return nil, nil + } + if err != nil { + return nil, err + } + info := cosiapi.BucketInfo{} + if err := json.Unmarshal(src.Data[bucketInfoKey], &info); err != nil { + return nil, fmt.Errorf("secret %s/%s: decode %s: %w", src.Namespace, src.Name, bucketInfoKey, err) + } + if info.Name != bucketInfoPrefix+string(ba.UID) || info.Spec.S3 == nil || + info.Spec.S3.AccessKeyID == "" || info.Spec.S3.AccessSecretKey == "" { + return nil, nil + } + return &s3Keys{accessKeyID: info.Spec.S3.AccessKeyID, secretKey: info.Spec.S3.AccessSecretKey}, nil +} + +// store writes the keys into the account Secret, marked as served for the +// request, and returns the Secret as written; nil when a mint created it in +// between. Without keys, for a revoke whose BucketAccess is gone, the Secret +// keeps the user name only. A new Secret records a Create, or a Migrate when +// the keys belong to an adopted BucketAccess, and carries the request of the +// BucketAccess it was written from; an existing one keeps the record the mint +// or revoke wrote. +func (r *COSICredentialReconciler) store(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate, sec *corev1.Secret, ba *cosiv1alpha1.BucketAccess, keys *s3Keys, request string) (*corev1.Secret, error) { + data := map[string][]byte{account.UsernameKey: []byte(tmpl.Spec.Username)} + if keys != nil { + data[account.PasswordKey] = []byte(keys.secretKey) + data[account.AccessKeyIDKey] = []byte(keys.accessKeyID) + } + labels := account.Labels(tmpl.Spec.Secret.Labels) + if sec == nil { + op := corev1alpha1.CredentialOperationCreate + if _, created := ba.Annotations[account.RequestAnnotation]; !created { + op = corev1alpha1.CredentialOperationMigrate + } + sec = &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: tmpl.Name + account.SecretSuffix, + Namespace: tmpl.Namespace, + Labels: labels, + Annotations: map[string]string{ + account.FormatAnnotation: tmpl.Spec.Format.Name, + account.BucketAccessAnnotation: tmpl.Spec.BucketAccess.Name, + account.GrantedAnnotation: request, + }, + }, + Type: corev1.SecretTypeBasicAuth, + Data: data, + } + if request != "" { + sec.Annotations[account.RequestAnnotation] = request + } + account.WriteRecord(sec, account.Record{}.Apply(op, r.now(), CredentialControllerActor)) + if err := controllerutil.SetControllerReference(tmpl, sec, r.Scheme); err != nil { + return nil, err + } + if err := r.Create(ctx, sec); err != nil { + if apierrors.IsAlreadyExists(err) { + return nil, nil + } + return nil, err + } + return sec, nil + } + if sec.Annotations[account.GrantedAnnotation] == request && sec.Annotations[account.FormatAnnotation] == tmpl.Spec.Format.Name && + sec.Annotations[account.BucketAccessAnnotation] == tmpl.Spec.BucketAccess.Name && + equalData(sec.Data, data) && equalStrings(sec.Labels, labels) { + return sec, nil + } + updated := sec.DeepCopy() + updated.Data = data + updated.Labels = labels + if updated.Annotations == nil { + updated.Annotations = map[string]string{} + } + updated.Annotations[account.FormatAnnotation] = tmpl.Spec.Format.Name + updated.Annotations[account.BucketAccessAnnotation] = tmpl.Spec.BucketAccess.Name + updated.Annotations[account.GrantedAnnotation] = request + // Written under the version read at the start of this pass: a mint in + // between fails it, and the next pass serves that mint's request. + if err := r.Update(ctx, updated); err != nil { + return nil, err + } + return updated, nil +} + +func equalData(a, b map[string][]byte) bool { + if len(a) != len(b) { + return false + } + for k, v := range a { + if w, ok := b[k]; !ok || string(v) != string(w) { + return false + } + } + return true +} + +func equalStrings(a, b map[string]string) bool { + if len(a) != len(b) { + return false + } + for k, v := range a { + if w, ok := b[k]; !ok || v != w { + return false + } + } + return true +} + +// restoreRevoked writes the account Secret of a revoked account again, from +// the record the template's status mirrors, without keys and with a request +// id of its own, as a revoke writes it. The revoke path then serves it: +// a BucketAccess still there is deleted once the sidecar has finalized it, +// and none is created, so the account holds no keys until the next mint. +func (r *COSICredentialReconciler) restoreRevoked(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate) error { + id, err := requestID() + if err != nil { + return err + } + sec := &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: tmpl.Name + account.SecretSuffix, + Namespace: tmpl.Namespace, + Labels: account.Labels(tmpl.Spec.Secret.Labels), + Annotations: map[string]string{ + account.FormatAnnotation: tmpl.Spec.Format.Name, + account.BucketAccessAnnotation: tmpl.Spec.BucketAccess.Name, + account.RequestAnnotation: id, + }, + }, + Type: corev1.SecretTypeBasicAuth, + Data: map[string][]byte{account.UsernameKey: []byte(tmpl.Spec.Username)}, + } + account.WriteRecord(sec, statusRecord(&tmpl.Status)) + if err := controllerutil.SetControllerReference(tmpl, sec, r.Scheme); err != nil { + return err + } + if err := r.Create(ctx, sec); err != nil { + // A mint created it in between; the next pass serves that. + if apierrors.IsAlreadyExists(err) { + return nil + } + return err + } + if r.Recorder != nil { + r.Recorder.Event(tmpl, corev1.EventTypeWarning, reasonCredentialRevoked, + "the account Secret of a revoked account was missing; wrote it again as revoked, mint to get keys") + } + return nil +} + +// statusRecord returns the record a template's status mirrors. +func statusRecord(st *cozyv1alpha1.CredentialTemplateStatus) account.Record { + rec := account.Record{Origin: corev1alpha1.CredentialOrigin(st.Password.Origin), By: st.Password.By} + if st.Password.At != nil { + rec.At = *st.Password.At + } + for _, h := range st.History { + rec.History = append(rec.History, corev1alpha1.CredentialHistoryEntry{Operation: corev1alpha1.CredentialOperation(h.Operation), At: h.At, By: h.By}) + } + return rec +} + +// finalize releases a deleted template once no BucketAccess it owns can be +// left in the grant window: each is deleted once the sidecar has finalized +// it, or once the sidecar can no longer grant it. A template deleted before +// any grant owns none and is released at once. The account Secret goes with +// it. +func (r *COSICredentialReconciler) finalize(ctx context.Context, tmpl *cozyv1alpha1.CredentialTemplate) (ctrl.Result, error) { + if !controllerutil.ContainsFinalizer(tmpl, templateFinalizer) { + return ctrl.Result{}, nil + } + accesses := &cosiv1alpha1.BucketAccessList{} + if err := r.List(ctx, accesses, client.InNamespace(tmpl.Namespace)); err != nil { + return ctrl.Result{}, err + } + granting := false + for i := range accesses.Items { + ba := &accesses.Items[i] + if !metav1.IsControlledBy(ba, tmpl) || !ba.DeletionTimestamp.IsZero() { + continue + } + if !controllerutil.ContainsFinalizer(ba, bucketAccessFinalizer) { + can, err := r.canGrant(ctx, ba) + if err != nil { + return ctrl.Result{}, err + } + if can { + granting = true + continue + } + } + if err := r.Delete(ctx, ba, client.Preconditions{UID: &ba.UID}); client.IgnoreNotFound(err) != nil { + return ctrl.Result{}, err + } + } + if granting { + return ctrl.Result{RequeueAfter: cosiGrantRequeue}, nil + } + if err := r.deleteAccountSecret(ctx, client.ObjectKeyFromObject(tmpl)); err != nil { + return ctrl.Result{}, err + } + patch := client.MergeFromWithOptions(tmpl.DeepCopy(), client.MergeFromWithOptimisticLock{}) + controllerutil.RemoveFinalizer(tmpl, templateFinalizer) + return ctrl.Result{}, client.IgnoreNotFound(r.Patch(ctx, tmpl, patch)) +} + +// canGrant reports whether the sidecar may still have the driver grant a +// BucketAccess it has not finalized. It fetches the class and the claim and +// needs the claim's bucket ready before it calls the driver +// (objectstorage-sidecar, sidecar/pkg/bucketaccess/bucketaccess_controller.go +// Add), so without them it cannot grant, and a delete leaves nothing behind. +func (r *COSICredentialReconciler) canGrant(ctx context.Context, ba *cosiv1alpha1.BucketAccess) (bool, error) { + class := &cosiv1alpha1.BucketAccessClass{} + if err := r.Reader.Get(ctx, types.NamespacedName{Name: ba.Spec.BucketAccessClassName}, class); err != nil { + if apierrors.IsNotFound(err) { + return false, nil + } + return false, err + } + claim := &cosiv1alpha1.BucketClaim{} + if err := r.Reader.Get(ctx, types.NamespacedName{Namespace: ba.Namespace, Name: ba.Spec.BucketClaimName}, claim); err != nil { + if apierrors.IsNotFound(err) { + return false, nil + } + return false, err + } + return claim.Status.BucketReady && claim.Status.BucketName != "", nil +} + +// cleanup removes what an engine-issued template deleted without the +// finalizer owned, as one deleted before this controller first reconciled it: +// its BucketAccess, whose deletion makes the sidecar revoke the identity, and +// its account Secret. The garbage collector would remove both through their +// owner reference; doing it here revokes the keys without waiting for it. It +// deletes a BucketAccess the sidecar has not finalized as well, since the +// garbage collector would. +func (r *COSICredentialReconciler) cleanup(ctx context.Context, nn types.NamespacedName) error { + accesses := &cosiv1alpha1.BucketAccessList{} + if err := r.List(ctx, accesses, client.InNamespace(nn.Namespace)); err != nil { + return err + } + for i := range accesses.Items { + ba := &accesses.Items[i] + if ownedByTemplate(ba, nn.Name) && ba.DeletionTimestamp.IsZero() { + if err := r.Delete(ctx, ba); client.IgnoreNotFound(err) != nil { + return err + } + } + } + return r.deleteAccountSecret(ctx, nn) +} + +// deleteAccountSecret deletes the engine-issued account Secret of a template. +func (r *COSICredentialReconciler) deleteAccountSecret(ctx context.Context, nn types.NamespacedName) error { + sec := &corev1.Secret{} + err := r.Reader.Get(ctx, types.NamespacedName{Namespace: nn.Namespace, Name: nn.Name + account.SecretSuffix}, sec) + if apierrors.IsNotFound(err) { + return nil + } + if err != nil { + return err + } + if !ownedByTemplate(sec, nn.Name) || !account.IsEngineIssued(sec) { + return nil + } + return client.IgnoreNotFound(r.Delete(ctx, sec)) +} + +func ownedByTemplate(o metav1.Object, name string) bool { + ref := metav1.GetControllerOf(o) + return ref != nil && ref.Kind == "CredentialTemplate" && ref.APIVersion == cozyv1alpha1.GroupVersion.String() && ref.Name == name +} + +// SetupWithManager registers the reconciler. accountSecrets is the same +// metadata cache of Secrets CredentialTemplateReconciler watches; only +// engine-issued account Secrets reach this reconciler. +func (r *COSICredentialReconciler) SetupWithManager(mgr ctrl.Manager, accountSecrets cache.Cache) error { + cosiTemplate := predicate.NewPredicateFuncs(func(o client.Object) bool { + tmpl, ok := o.(*cozyv1alpha1.CredentialTemplate) + return ok && (engineIssued(tmpl) || controllerutil.ContainsFinalizer(tmpl, templateFinalizer)) + }) + secretMeta := &metav1.PartialObjectMetadata{} + secretMeta.SetGroupVersionKind(corev1.SchemeGroupVersion.WithKind("Secret")) + isCOSIAccount := predicate.NewTypedPredicateFuncs(func(o *metav1.PartialObjectMetadata) bool { + return o.GetLabels()[account.AccountLabel] == "true" && o.GetAnnotations()[account.BucketAccessAnnotation] != "" + }) + owner := handler.TypedEnqueueRequestForOwner[*metav1.PartialObjectMetadata]( + mgr.GetScheme(), mgr.GetRESTMapper(), &cozyv1alpha1.CredentialTemplate{}, handler.OnlyControllerOwner()) + return ctrl.NewControllerManagedBy(mgr). + Named("credentialtemplate-cosi"). + For(&cozyv1alpha1.CredentialTemplate{}, builder.WithPredicates(predicate.GenerationChangedPredicate{}, cosiTemplate)). + Owns(&cosiv1alpha1.BucketAccess{}). + WatchesRawSource(source.Kind(accountSecrets, secretMeta, owner, isCOSIAccount)). + Complete(r) +} diff --git a/internal/controller/credentialtemplate_cosi_test.go b/internal/controller/credentialtemplate_cosi_test.go new file mode 100644 index 000000000..8b693cec4 --- /dev/null +++ b/internal/controller/credentialtemplate_cosi_test.go @@ -0,0 +1,868 @@ +// SPDX-License-Identifier: Apache-2.0 + +package controller + +import ( + "context" + "encoding/json" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/tools/record" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + cosiapi "sigs.k8s.io/container-object-storage-interface-api/apis" + cosiv1alpha1 "sigs.k8s.io/container-object-storage-interface-api/apis/objectstorage/v1alpha1" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" + "github.com/cozystack/cozystack/pkg/credentials/account" + "github.com/cozystack/cozystack/pkg/credentials/format" +) + +const ( + cosiRelease = "bucket-photos" + cosiName = cosiRelease + ".web" + cosiAccess = cosiRelease + "-web" + cosiClass = "seaweedfs" +) + +type cosiFixture struct { + c client.Client + r *COSICredentialReconciler + recorder *record.FakeRecorder + uids int +} + +func newCOSIFixture(t *testing.T, objs ...client.Object) *cosiFixture { + t.Helper() + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, cozyv1alpha1.AddToScheme, cosiv1alpha1.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + c := fake.NewClientBuilder().WithScheme(scheme). + WithObjects(objs...). + WithStatusSubresource(&cozyv1alpha1.CredentialTemplate{}, &cosiv1alpha1.BucketAccess{}). + Build() + rec := record.NewFakeRecorder(10) + return &cosiFixture{ + c: c, + recorder: rec, + r: &COSICredentialReconciler{ + Client: c, Reader: c, Scheme: scheme, Recorder: rec, + Now: func() time.Time { return time.Date(2026, 11, 21, 9, 0, 0, 0, time.UTC) }, + }, + } +} + +func cosiTemplate() *cozyv1alpha1.CredentialTemplate { + return &cozyv1alpha1.CredentialTemplate{ + ObjectMeta: metav1.ObjectMeta{ + Name: cosiName, Namespace: ctNamespace, UID: "cosi-tmpl-uid", + Annotations: map[string]string{account.ReleaseNameAnnotation: cosiRelease}, + }, + Spec: cozyv1alpha1.CredentialTemplateSpec{ + Username: "web", + Format: cozyv1alpha1.CredentialTemplateFormat{Name: format.Plaintext}, + BucketAccess: &cozyv1alpha1.CredentialTemplateBucketAccess{ + Name: cosiAccess, BucketClaimName: cosiRelease, BucketAccessClassName: cosiClass, + }, + }, + } +} + +func (f *cosiFixture) reconcile(t *testing.T) reconcile.Result { + t.Helper() + res, err := f.r.Reconcile(context.Background(), reconcile.Request{NamespacedName: types.NamespacedName{Namespace: ctNamespace, Name: cosiName}}) + if err != nil { + t.Fatalf("reconcile: %v", err) + } + return res +} + +func (f *cosiFixture) bucketAccess(t *testing.T) *cosiv1alpha1.BucketAccess { + t.Helper() + ba := &cosiv1alpha1.BucketAccess{} + err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: cosiAccess}, ba) + if apierrors.IsNotFound(err) { + return nil + } + if err != nil { + t.Fatal(err) + } + return ba +} + +func (f *cosiFixture) account(t *testing.T) *corev1.Secret { + t.Helper() + sec := &corev1.Secret{} + err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: cosiName + account.SecretSuffix}, sec) + if apierrors.IsNotFound(err) { + return nil + } + if err != nil { + t.Fatal(err) + } + return sec +} + +// grant does what the COSI sidecar does for a BucketAccess: it writes the +// Secret holding the BucketInfo of the grant, puts its finalizer on the +// BucketAccess and reports access granted. The fake client assigns no UID, so +// grant gives the BucketAccess one. +func (f *cosiFixture) grant(t *testing.T, accessKey, secretKey string) { + t.Helper() + f.grantUnfinalized(t, accessKey, secretKey) + ctx := context.Background() + ba := f.bucketAccess(t) + ba.Finalizers = append(ba.Finalizers, bucketAccessFinalizer) + if err := f.c.Update(ctx, ba); err != nil { + t.Fatal(err) + } + ba.Status.AccessGranted = true + ba.Status.AccountID = "ba-" + string(ba.UID) + if err := f.c.Status().Update(ctx, ba); err != nil { + t.Fatal(err) + } +} + +// grantUnfinalized stops the sidecar's grant where the driver has issued the +// keys and their Secret is written, before the finalizer goes on. +func (f *cosiFixture) grantUnfinalized(t *testing.T, accessKey, secretKey string) { + t.Helper() + ctx := context.Background() + ba := f.bucketAccess(t) + if ba == nil { + t.Fatal("no BucketAccess to grant") + } + if ba.UID == "" { + f.uids++ + ba.UID = types.UID("ba-uid-" + string(rune('a'+f.uids))) + if err := f.c.Update(ctx, ba); err != nil { + t.Fatal(err) + } + } + info, _ := json.Marshal(cosiapi.BucketInfo{ + ObjectMeta: metav1.ObjectMeta{Name: bucketInfoPrefix + string(ba.UID)}, + Spec: cosiapi.BucketInfoSpec{ + BucketName: "bucket-claim-uid", + S3: &cosiapi.SecretS3{Endpoint: "https://s3.example.org", AccessKeyID: accessKey, AccessSecretKey: secretKey}, + }, + }) + src := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: ba.Spec.CredentialsSecretName, Namespace: ctNamespace}, Data: map[string][]byte{bucketInfoKey: info}} + _ = f.c.Delete(ctx, src) + if err := f.c.Create(ctx, src); err != nil { + t.Fatal(err) + } +} + +// finalize does what the COSI sidecar does once a BucketAccess is being +// deleted: the driver revokes the identity, and the sidecar removes the +// Secret it wrote and its finalizer, which lets the deletion complete. +func (f *cosiFixture) finalize(t *testing.T) { + t.Helper() + ctx := context.Background() + ba := f.bucketAccess(t) + if ba == nil || ba.DeletionTimestamp.IsZero() { + t.Fatalf("BucketAccess = %+v, want one being deleted", ba) + } + _ = f.c.Delete(ctx, &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: ba.Spec.CredentialsSecretName, Namespace: ctNamespace}}) + ba.Finalizers = nil + if err := f.c.Update(ctx, ba); err != nil { + t.Fatal(err) + } + if f.bucketAccess(t) != nil { + t.Fatal("the BucketAccess outlived its finalizer") + } +} + +func (f *cosiFixture) template(t *testing.T) *cozyv1alpha1.CredentialTemplate { + t.Helper() + tmpl := &cozyv1alpha1.CredentialTemplate{} + if err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: cosiName}, tmpl); err != nil { + t.Fatal(err) + } + return tmpl +} + +// request writes the account Secret the way a mint or a revoke does: rebuilt +// without keys, carrying a request id and the operation in its record. +func (f *cosiFixture) createRequest(t *testing.T, id string, op corev1alpha1.CredentialOperation) { + t.Helper() + controller := true + sec := &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: cosiName + account.SecretSuffix, Namespace: ctNamespace, + Labels: account.Labels(nil), + Annotations: map[string]string{account.FormatAnnotation: format.Plaintext, account.BucketAccessAnnotation: cosiAccess, account.RequestAnnotation: id}, + OwnerReferences: []metav1.OwnerReference{{ + APIVersion: cozyv1alpha1.GroupVersion.String(), Kind: "CredentialTemplate", + Name: cosiName, UID: "cosi-tmpl-uid", Controller: &controller, + }}, + }, + Data: map[string][]byte{account.UsernameKey: []byte("web")}, + } + account.WriteRecord(sec, account.Record{}.Apply(op, metav1.NewTime(time.Date(2026, 11, 21, 10, 0, 0, 0, time.UTC)), "jane@example.org")) + if err := f.c.Create(context.Background(), sec); err != nil { + t.Fatal(err) + } +} + +func (f *cosiFixture) request(t *testing.T, id string, op corev1alpha1.CredentialOperation) { + t.Helper() + sec := f.account(t) + rec := account.ReadRecord(sec).Apply(op, metav1.NewTime(time.Date(2026, 11, 21, 10, 0, 0, 0, time.UTC)), "jane@example.org") + updated := sec.DeepCopy() + updated.Data = map[string][]byte{account.UsernameKey: []byte("web")} + updated.Annotations = map[string]string{account.FormatAnnotation: format.Plaintext, account.BucketAccessAnnotation: cosiAccess, account.RequestAnnotation: id} + account.WriteRecord(updated, rec) + if err := f.c.Update(context.Background(), updated); err != nil { + t.Fatal(err) + } +} + +func TestCOSICreatesTheBucketAccessOfATemplate(t *testing.T) { + f := newCOSIFixture(t, cosiTemplate()) + if res := f.reconcile(t); res.RequeueAfter == 0 { + t.Error("expected a requeue while the grant is pending") + } + ba := f.bucketAccess(t) + if ba == nil { + t.Fatal("no BucketAccess was created") + } + if ba.Spec.BucketClaimName != cosiRelease || ba.Spec.BucketAccessClassName != cosiClass || ba.Spec.CredentialsSecretName != cosiAccess || ba.Spec.Protocol != "s3" { + t.Errorf("spec = %+v", ba.Spec) + } + if ref := metav1.GetControllerOf(ba); ref == nil || ref.Name != cosiName || ref.Kind != "CredentialTemplate" { + t.Errorf("controller = %v, want the template", ref) + } + if v, ok := ba.Annotations[account.RequestAnnotation]; !ok || v != "" { + t.Errorf("request annotation = %q, %v; want present and empty", v, ok) + } + if f.account(t) != nil { + t.Error("an account Secret exists before the grant") + } +} + +func TestCOSICopiesTheIssuedKeysIntoTheAccountSecret(t *testing.T) { + f := newCOSIFixture(t, cosiTemplate()) + f.reconcile(t) + f.grant(t, "AKIAFIRST", "first-secret") + f.reconcile(t) + + sec := f.account(t) + if sec == nil { + t.Fatal("no account Secret") + } + if string(sec.Data[account.UsernameKey]) != "web" || string(sec.Data[account.PasswordKey]) != "first-secret" || string(sec.Data[account.AccessKeyIDKey]) != "AKIAFIRST" { + t.Errorf("data = %v", sec.Data) + } + if sec.Labels[account.AccountLabel] != "true" || sec.Annotations[account.FormatAnnotation] != format.Plaintext || sec.Annotations[account.BucketAccessAnnotation] != cosiAccess { + t.Errorf("labels = %v, annotations = %v", sec.Labels, sec.Annotations) + } + if ref := metav1.GetControllerOf(sec); ref == nil || ref.Name != cosiName { + t.Errorf("controller = %v, want the template", ref) + } + if rec := account.ReadRecord(sec); rec.Origin != corev1alpha1.CredentialOriginNotIssued || len(rec.History) != 1 || rec.History[0].Operation != corev1alpha1.CredentialOperationCreate { + t.Errorf("record = %+v, want one Create", rec) + } + tmpl := &cozyv1alpha1.CredentialTemplate{} + if err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: cosiName}, tmpl); err != nil { + t.Fatal(err) + } + if tmpl.Status.SecretResourceVersion != sec.ResourceVersion { + t.Errorf("status mirrors %q, Secret is at %q", tmpl.Status.SecretResourceVersion, sec.ResourceVersion) + } +} + +func TestCOSIMintReCreatesTheBucketAccessAndStoresTheNewKeysForItsRequest(t *testing.T) { + f := newCOSIFixture(t, cosiTemplate()) + f.reconcile(t) + f.grant(t, "AKIAFIRST", "first-secret") + f.reconcile(t) + firstUID := f.bucketAccess(t).UID + + f.request(t, "req-1", corev1alpha1.CredentialOperationMint) + f.reconcile(t) + if ba := f.bucketAccess(t); ba == nil || ba.DeletionTimestamp.IsZero() { + t.Fatalf("BucketAccess = %+v, want the one of the old keys deleted", ba) + } + f.finalize(t) + f.reconcile(t) + ba := f.bucketAccess(t) + if ba == nil || ba.Annotations[account.RequestAnnotation] != "req-1" { + t.Fatalf("BucketAccess = %+v, want one created for req-1", ba) + } + if sec := f.account(t); sec.Annotations[account.GrantedAnnotation] == "req-1" { + t.Error("the Secret is marked issued before the new grant") + } + f.grant(t, "AKIASECOND", "second-secret") + if f.bucketAccess(t).UID == firstUID { + t.Fatal("the test grant reused the old UID") + } + f.reconcile(t) + + sec := f.account(t) + if string(sec.Data[account.PasswordKey]) != "second-secret" || string(sec.Data[account.AccessKeyIDKey]) != "AKIASECOND" { + t.Errorf("data = %v, want the keys of the new grant", sec.Data) + } + if sec.Annotations[account.GrantedAnnotation] != "req-1" { + t.Errorf("granted = %q, want req-1", sec.Annotations[account.GrantedAnnotation]) + } + if rec := account.ReadRecord(sec); rec.Origin != corev1alpha1.CredentialOriginMinted || rec.By != "jane@example.org" { + t.Errorf("record = %+v, want the mint's", rec) + } + // A later pass leaves a served request alone. + f.reconcile(t) + if f.bucketAccess(t).Annotations[account.RequestAnnotation] != "req-1" { + t.Error("a served request was re-granted") + } +} + +// A revoke locks the account out: the BucketAccess goes, none replaces it, +// and the Secret is served without keys until the next mint. +func TestCOSIRevokeDeletesTheBucketAccessAndIssuesNoKeys(t *testing.T) { + f := newCOSIFixture(t, cosiTemplate()) + f.reconcile(t) + f.grant(t, "AKIAFIRST", "first-secret") + f.reconcile(t) + + f.request(t, "req-r", corev1alpha1.CredentialOperationRevoke) + f.reconcile(t) + if sec := f.account(t); sec.Annotations[account.GrantedAnnotation] == "req-r" { + t.Error("the revoke is marked served while its BucketAccess lives") + } + f.finalize(t) + f.reconcile(t) + f.reconcile(t) + if ba := f.bucketAccess(t); ba != nil { + t.Fatalf("a revoke created BucketAccess %+v", ba) + } + sec := f.account(t) + if _, ok := sec.Data[account.PasswordKey]; ok || len(sec.Data[account.AccessKeyIDKey]) > 0 || string(sec.Data[account.UsernameKey]) != "web" { + t.Errorf("data = %v, want the user name only", sec.Data) + } + if sec.Annotations[account.GrantedAnnotation] != "req-r" { + t.Errorf("granted = %q, want req-r", sec.Annotations[account.GrantedAnnotation]) + } + tmpl := f.template(t) + if tmpl.Status.Password.Origin != string(corev1alpha1.CredentialOriginRevoked) || tmpl.Status.SecretResourceVersion != sec.ResourceVersion { + t.Errorf("status = %+v, want Revoked at %s", tmpl.Status, sec.ResourceVersion) + } + + // The next mint issues keys again. + f.request(t, "req-2", corev1alpha1.CredentialOperationMint) + f.reconcile(t) + if ba := f.bucketAccess(t); ba == nil || ba.Annotations[account.RequestAnnotation] != "req-2" { + t.Fatalf("BucketAccess = %+v, want one created for req-2", ba) + } + f.grant(t, "AKIATHIRD", "third-secret") + f.reconcile(t) + if sec := f.account(t); string(sec.Data[account.PasswordKey]) != "third-secret" || sec.Annotations[account.GrantedAnnotation] != "req-2" { + t.Errorf("data = %v, annotations = %v", sec.Data, sec.Annotations) + } +} + +// The sidecar has the driver grant an identity before it puts its finalizer +// on the BucketAccess; a delete in between skips the driver revoke and leaves +// that identity behind, so the reconciler waits for the finalizer. +func TestCOSIWaitsForTheSidecarToFinalizeBeforeDeleting(t *testing.T) { + f := newCOSIFixture(t, cosiTemplate()) + f.reconcile(t) + f.grantUnfinalized(t, "AKIAFIRST", "first-secret") + f.reconcile(t) + // A mint on an account that has no Secret yet creates it. + f.createRequest(t, "req-1", corev1alpha1.CredentialOperationMint) + if res := f.reconcile(t); res.RequeueAfter != cosiGrantRequeue { + t.Errorf("requeue = %v, want %v", res.RequeueAfter, cosiGrantRequeue) + } + if ba := f.bucketAccess(t); ba == nil || !ba.DeletionTimestamp.IsZero() { + t.Fatalf("BucketAccess = %+v, want it kept until the sidecar finalizes it", ba) + } + f.grant(t, "AKIAFIRST", "first-secret") + f.reconcile(t) + if ba := f.bucketAccess(t); ba == nil || ba.DeletionTimestamp.IsZero() { + t.Fatalf("BucketAccess = %+v, want it deleted once finalized", ba) + } +} + +// The template's status follows the account Secret while a request waits, +// so a request that never completes leaves the next one a version to write +// over rather than a conflict on every attempt. +func TestCOSIStatusMirrorsAPendingRequest(t *testing.T) { + f := newCOSIFixture(t, cosiTemplate()) + f.reconcile(t) + f.grant(t, "AKIAFIRST", "first-secret") + f.reconcile(t) + + f.request(t, "req-1", corev1alpha1.CredentialOperationMint) + f.reconcile(t) + sec := f.account(t) + tmpl := f.template(t) + if tmpl.Status.SecretResourceVersion != sec.ResourceVersion || tmpl.Status.Password.Origin != string(corev1alpha1.CredentialOriginMinted) { + t.Fatalf("status = %+v, want the pending mint at %s", tmpl.Status, sec.ResourceVersion) + } + // A retry supersedes it, and the reconciler serves the retry. + f.request(t, "req-2", corev1alpha1.CredentialOperationMint) + f.finalize(t) + f.reconcile(t) + if ba := f.bucketAccess(t); ba == nil || ba.Annotations[account.RequestAnnotation] != "req-2" { + t.Fatalf("BucketAccess = %+v, want one created for req-2", ba) + } +} + +// changeClass points the template at another class, as the chart renders it +// when a user's readonly flag or the bucket's storage pool changes. +func (f *cosiFixture) changeClass(t *testing.T, class string) { + t.Helper() + tmpl := f.template(t) + tmpl.Spec.BucketAccess.BucketAccessClassName = class + if err := f.c.Update(context.Background(), tmpl); err != nil { + t.Fatal(err) + } +} + +// A class change re-grants the account, and nobody is shown the keys of that +// grant, so it is recorded as a revoke by the controller: the old grant goes, +// none replaces it, and the next mint is granted under the new class. +func TestCOSIClassChangeIsRecordedAsARevokeByTheController(t *testing.T) { + f := newCOSIFixture(t, cosiTemplate()) + f.reconcile(t) + f.grant(t, "AKIAFIRST", "first-secret") + f.reconcile(t) + f.request(t, "req-1", corev1alpha1.CredentialOperationMint) + f.reconcile(t) + f.finalize(t) + f.reconcile(t) + f.grant(t, "AKIASECOND", "second-secret") + f.reconcile(t) + if rec := account.ReadRecord(f.account(t)); rec.Origin != corev1alpha1.CredentialOriginMinted { + t.Fatalf("record = %+v, want the mint before the change", rec) + } + + f.changeClass(t, "seaweedfs-readonly") + f.reconcile(t) + sec := f.account(t) + if _, ok := sec.Data[account.PasswordKey]; ok || len(sec.Data[account.AccessKeyIDKey]) > 0 { + t.Errorf("data = %v, want the keys of the old grant gone", sec.Data) + } + id := sec.Annotations[account.RequestAnnotation] + if id == "" || id == "req-1" { + t.Errorf("request = %q, want a new one of the controller's", id) + } + rec := account.ReadRecord(sec) + if rec.Origin != corev1alpha1.CredentialOriginRevoked || rec.By != CredentialControllerActor || + len(rec.History) < 2 || rec.History[0].Operation != corev1alpha1.CredentialOperationRevoke || rec.History[0].By != CredentialControllerActor || + rec.History[1].Operation != corev1alpha1.CredentialOperationMint { + t.Errorf("record = %+v, want a revoke by the controller on top of the mint", rec) + } + if tmpl := f.template(t); tmpl.Status.Password.Origin != string(corev1alpha1.CredentialOriginRevoked) || tmpl.Status.Password.By != CredentialControllerActor { + t.Errorf("status = %+v, want Revoked by the controller", tmpl.Status.Password) + } + select { + case ev := <-f.recorder.Events: + if ev == "" { + t.Error("empty event") + } + default: + t.Error("no event for the revoke") + } + + // The revoke path takes it from here: the old grant goes, none replaces it. + f.reconcile(t) + if ba := f.bucketAccess(t); ba == nil || ba.DeletionTimestamp.IsZero() { + t.Fatalf("BucketAccess = %+v, want the old grant deleted", ba) + } + f.finalize(t) + f.reconcile(t) + f.reconcile(t) + if ba := f.bucketAccess(t); ba != nil { + t.Fatalf("a class change created BucketAccess %+v before any mint", ba) + } + if sec := f.account(t); sec.Annotations[account.GrantedAnnotation] != id { + t.Errorf("granted = %q, want %q", sec.Annotations[account.GrantedAnnotation], id) + } + if rec := account.ReadRecord(f.account(t)); len(rec.History) != 3 { + t.Errorf("history = %+v, want one revoke recorded once", rec.History) + } + + // The next mint is granted under the new class. + f.request(t, "req-2", corev1alpha1.CredentialOperationMint) + f.reconcile(t) + ba := f.bucketAccess(t) + if ba == nil || ba.Annotations[account.RequestAnnotation] != "req-2" || ba.Spec.BucketAccessClassName != "seaweedfs-readonly" { + t.Fatalf("BucketAccess = %+v, want one for req-2 under the new class", ba) + } +} + +// A mint the Secret already carries is served under the new class and keeps +// its record: its caller is the one shown the keys. +func TestCOSIClassChangeDuringAMintServesTheMint(t *testing.T) { + f := newCOSIFixture(t, cosiTemplate()) + f.reconcile(t) + f.grant(t, "AKIAFIRST", "first-secret") + f.reconcile(t) + + f.request(t, "req-1", corev1alpha1.CredentialOperationMint) + f.changeClass(t, "seaweedfs-readonly") + f.reconcile(t) + if sec := f.account(t); sec.Annotations[account.RequestAnnotation] != "req-1" { + t.Fatalf("request = %q, want the mint's req-1 kept", sec.Annotations[account.RequestAnnotation]) + } + f.finalize(t) + f.reconcile(t) + ba := f.bucketAccess(t) + if ba == nil || ba.Annotations[account.RequestAnnotation] != "req-1" || ba.Spec.BucketAccessClassName != "seaweedfs-readonly" { + t.Fatalf("BucketAccess = %+v, want one for req-1 under the new class", ba) + } + f.grant(t, "AKIASECOND", "second-secret") + f.reconcile(t) + sec := f.account(t) + if rec := account.ReadRecord(sec); rec.Origin != corev1alpha1.CredentialOriginMinted || rec.By != "jane@example.org" { + t.Errorf("record = %+v, want the mint's", rec) + } + if string(sec.Data[account.PasswordKey]) != "second-secret" || sec.Annotations[account.GrantedAnnotation] != "req-1" { + t.Errorf("data = %v, annotations = %v", sec.Data, sec.Annotations) + } +} + +// A revoked account has no grant to change: a class change adds no entry. +func TestCOSIClassChangeOnARevokedAccountAddsNoEntry(t *testing.T) { + f := newCOSIFixture(t, cosiTemplate()) + f.reconcile(t) + f.grant(t, "AKIAFIRST", "first-secret") + f.reconcile(t) + f.request(t, "req-r", corev1alpha1.CredentialOperationRevoke) + f.reconcile(t) + f.finalize(t) + f.reconcile(t) + before := account.ReadRecord(f.account(t)) + + f.changeClass(t, "seaweedfs-readonly") + f.reconcile(t) + f.reconcile(t) + sec := f.account(t) + if rec := account.ReadRecord(sec); len(rec.History) != len(before.History) || rec.By != "jane@example.org" { + t.Errorf("record = %+v, want it unchanged from %+v", rec, before) + } + if sec.Annotations[account.RequestAnnotation] != "req-r" { + t.Errorf("request = %q, want req-r", sec.Annotations[account.RequestAnnotation]) + } + if ba := f.bucketAccess(t); ba != nil { + t.Errorf("BucketAccess = %+v, want none", ba) + } +} + +// A lost account Secret is written again from the live grant instead of +// rotating the keys its clients use. +func TestCOSIRewritesALostAccountSecretFromTheLiveGrant(t *testing.T) { + f := newCOSIFixture(t, cosiTemplate()) + f.reconcile(t) + f.grant(t, "AKIAFIRST", "first-secret") + f.reconcile(t) + f.request(t, "req-1", corev1alpha1.CredentialOperationMint) + f.reconcile(t) + f.finalize(t) + f.reconcile(t) + f.grant(t, "AKIASECOND", "second-secret") + f.reconcile(t) + uid := f.bucketAccess(t).UID + + if err := f.c.Delete(context.Background(), f.account(t)); err != nil { + t.Fatal(err) + } + f.reconcile(t) + f.reconcile(t) + ba := f.bucketAccess(t) + if ba == nil || ba.UID != uid || !ba.DeletionTimestamp.IsZero() { + t.Fatalf("BucketAccess = %+v, want the live grant kept", ba) + } + sec := f.account(t) + if sec == nil || string(sec.Data[account.PasswordKey]) != "second-secret" || sec.Annotations[account.RequestAnnotation] != "req-1" || sec.Annotations[account.GrantedAnnotation] != "req-1" { + t.Fatalf("account Secret = %+v, want the keys of the live grant for req-1", sec) + } +} + +func TestCOSIAdoptsAMarkedBucketAccessKeepingItsKeys(t *testing.T) { + legacy := &cosiv1alpha1.BucketAccess{ + ObjectMeta: metav1.ObjectMeta{ + Name: cosiAccess, Namespace: ctNamespace, UID: "legacy-uid", + Labels: map[string]string{account.AdoptLabel: "true"}, + Annotations: map[string]string{"meta.helm.sh/release-name": cosiRelease, "helm.sh/resource-policy": "keep"}, + }, + Spec: cosiv1alpha1.BucketAccessSpec{BucketClaimName: cosiRelease, BucketAccessClassName: cosiClass, CredentialsSecretName: cosiAccess, Protocol: "s3"}, + } + f := newCOSIFixture(t, cosiTemplate(), legacy) + f.grant(t, "AKIALEGACY", "legacy-secret") + f.reconcile(t) + + ba := f.bucketAccess(t) + if ba == nil || ba.UID != "legacy-uid" { + t.Fatalf("BucketAccess = %+v, want the legacy one kept", ba) + } + if ref := metav1.GetControllerOf(ba); ref == nil || ref.Name != cosiName { + t.Errorf("controller = %v, want the template", ref) + } + sec := f.account(t) + if sec == nil || string(sec.Data[account.PasswordKey]) != "legacy-secret" || string(sec.Data[account.AccessKeyIDKey]) != "AKIALEGACY" { + t.Fatalf("account Secret = %v, want the legacy keys", sec) + } + if rec := account.ReadRecord(sec); rec.Origin != corev1alpha1.CredentialOriginMigrated { + t.Errorf("record = %+v, want Migrated", rec) + } +} + +func TestCOSILeavesAnUnmarkedBucketAccessAlone(t *testing.T) { + foreign := &cosiv1alpha1.BucketAccess{ + ObjectMeta: metav1.ObjectMeta{Name: cosiAccess, Namespace: ctNamespace, UID: "foreign-uid"}, + Spec: cosiv1alpha1.BucketAccessSpec{BucketClaimName: cosiRelease, BucketAccessClassName: cosiClass, CredentialsSecretName: cosiAccess}, + } + f := newCOSIFixture(t, cosiTemplate(), foreign) + f.reconcile(t) + if ba := f.bucketAccess(t); ba == nil || metav1.GetControllerOf(ba) != nil { + t.Errorf("BucketAccess = %+v, want it untouched", ba) + } + if f.account(t) != nil { + t.Error("keys of a foreign BucketAccess were copied") + } + tmpl := &cozyv1alpha1.CredentialTemplate{} + if err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: cosiName}, tmpl); err != nil { + t.Fatal(err) + } + if !meta.IsStatusConditionTrue(tmpl.Status.Conditions, cozyv1alpha1.CredentialTemplateBucketAccessConflict) { + t.Errorf("conditions = %v, want BucketAccessConflict", tmpl.Status.Conditions) + } +} + +func TestCOSIRemovingTheUserRemovesItsBucketAccessAndSecret(t *testing.T) { + f := newCOSIFixture(t, cosiTemplate()) + f.reconcile(t) + f.grant(t, "AKIAFIRST", "first-secret") + f.reconcile(t) + + if err := f.c.Delete(context.Background(), cosiTemplate()); err != nil { + t.Fatal(err) + } + f.reconcile(t) + f.finalize(t) + if sec := f.account(t); sec != nil { + t.Error("the account Secret outlived its template") + } +} + +func TestPasswordReconcilerSkipsACOSITemplate(t *testing.T) { + tmpl := cosiTemplate() + tmpl.Name = ctName + tmpl.Annotations[account.ReleaseNameAnnotation] = ctRelease + f := newCTFixture(t, true, tmpl) + f.reconcile(t) + sec := &corev1.Secret{} + if err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: ctName + account.SecretSuffix}, sec); !apierrors.IsNotFound(err) { + t.Errorf("the password reconciler seeded an engine-issued account: %v", err) + } + got := &cozyv1alpha1.CredentialTemplate{} + if err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: ctName}, got); err != nil { + t.Fatal(err) + } + if len(got.Status.Conditions) != 0 { + t.Errorf("conditions = %v, want none", got.Status.Conditions) + } +} + +// A revoke is the account's latest request also once its Secret is lost: +// the Secret is written again as revoked, and no keys are granted until the +// next mint. +func TestCOSIALostSecretAfterARevokeGrantsNoKeys(t *testing.T) { + f := newCOSIFixture(t, cosiTemplate()) + f.reconcile(t) + f.grant(t, "AKIAFIRST", "first-secret") + f.reconcile(t) + f.request(t, "req-r", corev1alpha1.CredentialOperationRevoke) + f.reconcile(t) + f.finalize(t) + f.reconcile(t) + f.reconcile(t) + if sec := f.account(t); sec.Annotations[account.GrantedAnnotation] != "req-r" { + t.Fatalf("annotations = %v, want the revoke served", sec.Annotations) + } + + if err := f.c.Delete(context.Background(), f.account(t)); err != nil { + t.Fatal(err) + } + for range 3 { + f.reconcile(t) + } + if ba := f.bucketAccess(t); ba != nil { + t.Fatalf("BucketAccess = %+v, want none after a revoke", ba) + } + sec := f.account(t) + if sec == nil { + t.Fatal("the account Secret was not written again") + } + if _, ok := sec.Data[account.PasswordKey]; ok || len(sec.Data[account.AccessKeyIDKey]) > 0 { + t.Errorf("data = %v, want the user name only", sec.Data) + } + rec := account.ReadRecord(sec) + if rec.Origin != corev1alpha1.CredentialOriginRevoked || len(rec.History) == 0 || rec.History[0].Operation != corev1alpha1.CredentialOperationRevoke { + t.Errorf("record = %+v, want the revoke kept", rec) + } + if id := sec.Annotations[account.RequestAnnotation]; id == "" || sec.Annotations[account.GrantedAnnotation] != id { + t.Errorf("annotations = %v, want a served request of its own", sec.Annotations) + } + if tmpl := f.template(t); tmpl.Status.SecretResourceVersion != sec.ResourceVersion || tmpl.Status.Password.Origin != string(corev1alpha1.CredentialOriginRevoked) { + t.Errorf("status = %+v, want Revoked at %s", tmpl.Status, sec.ResourceVersion) + } + + // The next mint grants keys again. + f.request(t, "req-2", corev1alpha1.CredentialOperationMint) + f.reconcile(t) + if ba := f.bucketAccess(t); ba == nil || ba.Annotations[account.RequestAnnotation] != "req-2" { + t.Fatalf("BucketAccess = %+v, want one created for req-2", ba) + } +} + +// A Secret lost while a revoke waits for its BucketAccess to go still ends +// in the revoke: the live grant is deleted, not copied back. +func TestCOSIALostSecretDuringARevokeFinishesTheRevoke(t *testing.T) { + f := newCOSIFixture(t, cosiTemplate()) + f.reconcile(t) + f.grant(t, "AKIAFIRST", "first-secret") + f.reconcile(t) + // The revoke is mirrored and its BucketAccess deleted; the sidecar has + // not revoked it yet. + f.request(t, "req-r", corev1alpha1.CredentialOperationRevoke) + f.reconcile(t) + + if err := f.c.Delete(context.Background(), f.account(t)); err != nil { + t.Fatal(err) + } + f.reconcile(t) + f.reconcile(t) + if sec := f.account(t); sec == nil || len(sec.Data[account.PasswordKey]) > 0 || account.ReadRecord(sec).Origin != corev1alpha1.CredentialOriginRevoked { + t.Fatalf("account Secret = %+v, want it revoked without keys", sec) + } + f.finalize(t) + f.reconcile(t) + if ba := f.bucketAccess(t); ba != nil { + t.Fatalf("BucketAccess = %+v, want none after the revoke", ba) + } + if sec := f.account(t); len(sec.Data[account.PasswordKey]) > 0 { + t.Errorf("data = %v, want no keys", sec.Data) + } +} + +// cosiStorage is the claim and class the sidecar needs before it can grant. +func cosiStorage(ready bool) []client.Object { + claim := &cosiv1alpha1.BucketClaim{ObjectMeta: metav1.ObjectMeta{Name: cosiRelease, Namespace: ctNamespace}} + if ready { + claim.Status = cosiv1alpha1.BucketClaimStatus{BucketReady: true, BucketName: "bc-claim-uid"} + } + return []client.Object{claim, &cosiv1alpha1.BucketAccessClass{ObjectMeta: metav1.ObjectMeta{Name: cosiClass}, DriverName: "seaweedfs"}} +} + +func (f *cosiFixture) deleteTemplate(t *testing.T) { + t.Helper() + if err := f.c.Delete(context.Background(), f.template(t)); err != nil { + t.Fatal(err) + } +} + +func (f *cosiFixture) templateGone(t *testing.T) bool { + t.Helper() + err := f.c.Get(context.Background(), types.NamespacedName{Namespace: ctNamespace, Name: cosiName}, &cozyv1alpha1.CredentialTemplate{}) + if err != nil && !apierrors.IsNotFound(err) { + t.Fatal(err) + } + return apierrors.IsNotFound(err) +} + +func TestCOSIPutsAFinalizerOnTheTemplate(t *testing.T) { + f := newCOSIFixture(t, cosiTemplate()) + f.reconcile(t) + if tmpl := f.template(t); !controllerutil.ContainsFinalizer(tmpl, templateFinalizer) { + t.Errorf("finalizers = %v, want %s", tmpl.Finalizers, templateFinalizer) + } +} + +// A template deleted while the sidecar may still be granting keeps its +// BucketAccess until the sidecar finalizes it, so the delete runs the driver +// revoke, and is released only then. +func TestCOSIDeletedTemplateWaitsOutTheGrantWindow(t *testing.T) { + f := newCOSIFixture(t, append(cosiStorage(true), cosiTemplate())...) + f.reconcile(t) + f.grantUnfinalized(t, "AKIAFIRST", "first-secret") + f.deleteTemplate(t) + if res := f.reconcile(t); res.RequeueAfter != cosiGrantRequeue { + t.Errorf("requeue = %v, want %v", res.RequeueAfter, cosiGrantRequeue) + } + if ba := f.bucketAccess(t); ba == nil || !ba.DeletionTimestamp.IsZero() { + t.Fatalf("BucketAccess = %+v, want it kept until the sidecar finalizes it", ba) + } + if f.templateGone(t) { + t.Fatal("the template was released inside the grant window") + } + + f.grant(t, "AKIAFIRST", "first-secret") + f.reconcile(t) + if ba := f.bucketAccess(t); ba == nil || ba.DeletionTimestamp.IsZero() { + t.Fatalf("BucketAccess = %+v, want it deleted once finalized", ba) + } + if !f.templateGone(t) { + t.Fatal("the template was not released") + } + f.finalize(t) +} + +// A BucketAccess the sidecar can no longer grant, its claim gone or not +// ready, is deleted without waiting: nothing was granted for it. +func TestCOSIDeletedTemplateDeletesABucketAccessThatCannotBeGranted(t *testing.T) { + for name, objs := range map[string][]client.Object{ + "no claim": cosiStorage(true)[1:], + "claim not ready": cosiStorage(false), + "no class": cosiStorage(true)[:1], + } { + t.Run(name, func(t *testing.T) { + f := newCOSIFixture(t, append(objs, cosiTemplate())...) + f.reconcile(t) + if f.bucketAccess(t) == nil { + t.Fatal("no BucketAccess was created") + } + f.deleteTemplate(t) + if res := f.reconcile(t); res.RequeueAfter != 0 { + t.Errorf("requeue = %v, want none", res.RequeueAfter) + } + if ba := f.bucketAccess(t); ba != nil { + t.Fatalf("BucketAccess = %+v, want it deleted", ba) + } + if !f.templateGone(t) { + t.Fatal("the template was not released") + } + }) + } +} + +// A template deleted before it ever had a BucketAccess is released at once. +func TestCOSIDeletedTemplateWithoutAGrantIsReleased(t *testing.T) { + tmpl := cosiTemplate() + tmpl.Finalizers = []string{templateFinalizer} + f := newCOSIFixture(t, tmpl) + f.deleteTemplate(t) + f.reconcile(t) + if !f.templateGone(t) { + t.Fatal("the template was not released") + } + if ba := f.bucketAccess(t); ba != nil { + t.Fatalf("BucketAccess = %+v, want none", ba) + } +} diff --git a/internal/controller/credentialtemplate_crd_test.go b/internal/controller/credentialtemplate_crd_test.go new file mode 100644 index 000000000..9d029f90b --- /dev/null +++ b/internal/controller/credentialtemplate_crd_test.go @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: Apache-2.0 + +package controller + +import ( + "context" + "os" + "testing" + + apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "k8s.io/apiextensions-apiserver/pkg/apiserver/schema" + schemacel "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel" + "k8s.io/apimachinery/pkg/util/validation/field" + celconfig "k8s.io/apiserver/pkg/apis/cel" + "sigs.k8s.io/yaml" +) + +// credentialTemplateCRD is the generated CRD cozystack-controller ships. +// Reading it rather than restating the rule catches a marker that did not +// generate. +const credentialTemplateCRD = "../../packages/system/cozystack-controller/definitions/cozystack.io_credentialtemplates.yaml" + +// An engine-issued template, one that names a BucketAccess, stores the keys +// as they are issued, so its format must be plaintext; a template without a +// BucketAccess may use any format. +func TestCredentialTemplateCRDTiesBucketAccessToPlaintext(t *testing.T) { + raw, err := os.ReadFile(credentialTemplateCRD) + if err != nil { + t.Fatal(err) + } + var crd apiextensionsv1.CustomResourceDefinition + if err := yaml.Unmarshal(raw, &crd); err != nil { + t.Fatal(err) + } + var spec *apiextensionsv1.JSONSchemaProps + for i := range crd.Spec.Versions { + if v := crd.Spec.Versions[i]; v.Name == "v1alpha1" && v.Schema != nil && v.Schema.OpenAPIV3Schema != nil { + if p, ok := v.Schema.OpenAPIV3Schema.Properties["spec"]; ok { + spec = &p + } + } + } + if spec == nil || len(spec.XValidations) == 0 { + t.Fatal("v1alpha1 spec schema with x-kubernetes-validations not found in the CRD") + } + var internal apiextensions.JSONSchemaProps + if err := apiextensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(spec, &internal, nil); err != nil { + t.Fatal(err) + } + structural, err := schema.NewStructural(&internal) + if err != nil { + t.Fatal(err) + } + validator := schemacel.NewValidator(structural, true, celconfig.PerCallLimit) + + access := map[string]any{"name": "bucket-photos-web", "bucketClaimName": "bucket-photos", "bucketAccessClassName": "seaweedfs"} + for _, tc := range []struct { + name string + spec map[string]any + accept bool + }{ + {"bucketAccess with plaintext", map[string]any{"username": "web", "format": map[string]any{"name": "plaintext"}, "bucketAccess": access}, true}, + {"bucketAccess with another format", map[string]any{"username": "web", "format": map[string]any{"name": "scram-sha-256"}, "bucketAccess": access}, false}, + {"bucketAccess with a format named cosi", map[string]any{"username": "web", "format": map[string]any{"name": "cosi"}, "bucketAccess": access}, false}, + {"plaintext without bucketAccess", map[string]any{"username": "web", "format": map[string]any{"name": "plaintext"}}, true}, + {"another format without bucketAccess", map[string]any{"username": "web", "format": map[string]any{"name": "sha256"}}, true}, + } { + t.Run(tc.name, func(t *testing.T) { + errs, _ := validator.Validate(context.TODO(), field.NewPath("spec"), structural, tc.spec, nil, celconfig.RuntimeCELCostBudget) + if accepted := len(errs) == 0; accepted != tc.accept { + t.Errorf("accepted = %v, want %v: %v", accepted, tc.accept, errs) + } + }) + } +} diff --git a/internal/lineagecontrollerwebhook/matcher.go b/internal/lineagecontrollerwebhook/matcher.go index 6e7bd3188..cabeb070e 100644 --- a/internal/lineagecontrollerwebhook/matcher.go +++ b/internal/lineagecontrollerwebhook/matcher.go @@ -3,6 +3,7 @@ package lineagecontrollerwebhook import ( "bytes" "context" + "strings" "text/template" cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" @@ -71,3 +72,21 @@ func matchResourceToExcludeInclude(ctx context.Context, name string, templateCon } return matchResourceToSelectorArray(ctx, name, templateContext, l, resources.Include) } + +// SecretTenantVisible reports whether the webhook stamps a Secret of the +// named application tenant-visible under the definition's selectors, the way +// computeLabels evaluates them on admission. Callers outside the webhook use +// it to tell whether a definition already in the API hides a Secret before +// they label it, since the webhook re-evaluates on every write that drops the +// lineage labels. +func SecretTenantVisible(ctx context.Context, appDef *cozyv1alpha1.ApplicationDefinition, appName, namespace, secretName string, secretLabels map[string]string) bool { + if appDef == nil { + return false + } + templateContext := map[string]string{ + "kind": strings.ToLower(appDef.Spec.Application.Kind), + "name": appName, + "namespace": namespace, + } + return matchResourceToExcludeInclude(ctx, secretName, templateContext, secretLabels, &appDef.Spec.Secrets) +} diff --git a/internal/lineagecontrollerwebhook/secret_visible_test.go b/internal/lineagecontrollerwebhook/secret_visible_test.go new file mode 100644 index 000000000..4eae83115 --- /dev/null +++ b/internal/lineagecontrollerwebhook/secret_visible_test.go @@ -0,0 +1,62 @@ +package lineagecontrollerwebhook + +import ( + "context" + "os" + "testing" + + "sigs.k8s.io/yaml" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" +) + +func loadDefinition(t *testing.T, path string) *cozyv1alpha1.ApplicationDefinition { + t.Helper() + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + def := &cozyv1alpha1.ApplicationDefinition{} + if err := yaml.Unmarshal(raw, def); err != nil { + t.Fatal(err) + } + return def +} + +// The platform Secrets a converted engine keeps must stay hidden on every +// write that drops their lineage labels, not only until an operator rewrites +// them: the webhook stamps them from these definitions each time. +func TestConvertedDefinitionsHidePlatformSecrets(t *testing.T) { + ctx := context.Background() + for _, c := range []struct{ rd, secret string }{ + {"rabbitmq", "rabbitmq-rmq-default-user"}, + {"mongodb", "mongodb-rmq-credentials"}, + {"mongodb", "mongodb-rmq-percona-server-mongodb-users"}, + {"mariadb", "mariadb-rmq-credentials"}, + {"clickhouse", "clickhouse-rmq-credentials"}, + } { + def := loadDefinition(t, "../../packages/system/"+c.rd+"-rd/cozyrds/"+c.rd+".yaml") + // An operator's rewrite carries its own labels, none of the lineage ones. + if SecretTenantVisible(ctx, def, "rmq", "tenant-foo", c.secret, map[string]string{"app.kubernetes.io/name": "rmq"}) { + t.Errorf("%s: the definition stamps %s tenant-visible", c.rd, c.secret) + } + } +} + +func TestSecretTenantVisibleFollowsIncludeAndExclude(t *testing.T) { + ctx := context.Background() + sel := []*cozyv1alpha1.ApplicationDefinitionResourceSelector{{ResourceNames: []string{"{{ .kind }}-{{ .name }}-default-user"}}} + def := &cozyv1alpha1.ApplicationDefinition{} + def.Spec.Application.Kind = "RabbitMQ" + def.Spec.Secrets.Include = sel + if !SecretTenantVisible(ctx, def, "rmq", "tenant-foo", "rabbitmq-rmq-default-user", nil) { + t.Fatal("an included Secret must be visible") + } + def.Spec.Secrets.Exclude = sel + if SecretTenantVisible(ctx, def, "rmq", "tenant-foo", "rabbitmq-rmq-default-user", nil) { + t.Fatal("exclude must win over include") + } + if SecretTenantVisible(ctx, nil, "rmq", "tenant-foo", "rabbitmq-rmq-default-user", nil) { + t.Fatal("a kind with no definition stamps nothing visible") + } +} diff --git a/packages/apps/bucket/README.md b/packages/apps/bucket/README.md index 8487c68c4..e14c50571 100644 --- a/packages/apps/bucket/README.md +++ b/packages/apps/bucket/README.md @@ -13,5 +13,6 @@ | `publicRead` | Serves the bucket's objects to anyone without credentials at `//`. Anonymous callers can read objects but cannot list the bucket or write to it. | `bool` | `false` | | `users` | Users configuration map. | `map[string]object` | `{}` | | `users[name].readonly` | Whether the user has read-only access. | `bool` | `false` | +| `users[name].platform` | Marks a platform account, such as the `system` user of the backup bucket, which backupstrategy-controller sets. Its keys stay in the `--credentials` Secret, which no tenant can read, and are never minted. Clearing it drops the chart-rendered BucketAccess, which revokes those keys, and the user becomes a normal account whose keys are minted through its Credential. Leave it unset for your own users. | `bool` | `false` | | `schedulingClass` | Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant. | `string` | `""` | diff --git a/packages/apps/bucket/templates/_accounts.tpl b/packages/apps/bucket/templates/_accounts.tpl new file mode 100644 index 000000000..de45a12c5 --- /dev/null +++ b/packages/apps/bucket/templates/_accounts.tpl @@ -0,0 +1,52 @@ +{{/* + Account naming, which must match pkg/credentials/account.MapName: the + credential of a user is ., where is the user + name lowercased with every character outside [a-z0-9-] replaced by "-". +*/}} +{{- define "bucket.accountName" -}} +{{- regexReplaceAll "[^a-z0-9-]" (lower .) "-" -}} +{{- end -}} + +{{/* + The BucketAccess of a tenant user, which also names the Secret the COSI + sidecar writes for it: -, as the chart named it before the + conversion, so that platform migration 71 hands the existing one, and its + keys, to the template; or - when - is not + a valid object name, since no BucketAccess was ever created under it. +*/}} +{{- define "bucket.accessName" -}} +{{- $root := index . 0 -}} +{{- $user := index . 1 -}} +{{- $legacy := printf "%s-%s" $root.Release.Name $user -}} +{{- if and (le (len $legacy) 253) (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$" $legacy) -}} +{{- $legacy -}} +{{- else -}} +{{- printf "%s-%s" $root.Release.Name (include "bucket.accountName" $user) -}} +{{- end -}} +{{- end -}} + +{{/* + The BucketAccessClass a user's grant comes from: the storage pool's, and + its -readonly variant for a read-only user. +*/}} +{{- define "bucket.accessClass" -}} +{{- $root := index . 0 -}} +{{- $user := index . 1 -}} +{{- $root.Values._namespace.seaweedfs }}{{- if $root.Values.storagePool }}-{{ $root.Values.storagePool }}{{- end }}{{- if $user.readonly }}-readonly{{- end }} +{{- end -}} + +{{- define "bucket.accountsGuard" -}} +{{- $seen := dict -}} +{{- range $user, $u := .Values.users -}} + {{- if not (default false $u.platform) -}} + {{- $mapped := include "bucket.accountName" $user -}} + {{- if or (gt (len $mapped) 63) (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $mapped)) -}} + {{- fail (printf "user %q maps to the account name %q, which must be at most 63 characters and start and end with a letter or a digit; rename the user" $user $mapped) -}} + {{- end -}} + {{- with index $seen $mapped -}} + {{- fail (printf "users %q and %q both map to the account name %q; rename one of them" . $user $mapped) -}} + {{- end -}} + {{- $_ := set $seen $mapped $user -}} + {{- end -}} +{{- end -}} +{{- end -}} diff --git a/packages/apps/bucket/templates/bucketclaim.yaml b/packages/apps/bucket/templates/bucketclaim.yaml index 0be116e15..7c06f51b3 100644 --- a/packages/apps/bucket/templates/bucketclaim.yaml +++ b/packages/apps/bucket/templates/bucketclaim.yaml @@ -44,18 +44,25 @@ spec: bucketClassName: {{ $seaweedfs }}{{- if $pool }}-{{ $pool }}{{- end }}{{- if .Values.locking }}-lock{{- if eq (toString .Values.lockingDefaultRetention) "false" }}-noretention{{- end }}{{- end }} protocols: - s3 +{{- /* + Only a platform user's BucketAccess is rendered here. A tenant user's is + created by cozystack-controller from its CredentialTemplate + (credentials.yaml), so that a mint can re-create it and a revoke delete it. +*/}} {{- range $name, $user := .Values.users }} +{{- if default false $user.platform }} --- apiVersion: objectstorage.k8s.io/v1alpha1 kind: BucketAccess metadata: name: {{ $.Release.Name }}-{{ $name }} spec: - bucketAccessClassName: {{ $seaweedfs }}{{- if $pool }}-{{ $pool }}{{- end }}{{- if $user.readonly }}-readonly{{- end }} + bucketAccessClassName: {{ include "bucket.accessClass" (list $ $user) }} bucketClaimName: {{ $.Release.Name }} credentialsSecretName: {{ $.Release.Name }}-{{ $name }} protocol: s3 {{- end }} +{{- end }} {{- if .Values.publicRead }} {{- if hasKey .Values.users "public-read" }} {{- fail "publicRead creates the BucketAccess -public-read, which the user \"public-read\" already owns: rename that user" }} diff --git a/packages/apps/bucket/templates/credentials.yaml b/packages/apps/bucket/templates/credentials.yaml new file mode 100644 index 000000000..7888f8e30 --- /dev/null +++ b/packages/apps/bucket/templates/credentials.yaml @@ -0,0 +1,29 @@ +{{- /* + One CredentialTemplate per tenant user: the account the Cozystack + credentials API mints and revokes through. The COSI driver issues a user's + keys, so the template names the BucketAccess whose grant issues them, and + cozystack-controller creates that BucketAccess, copies its keys into the + account Secret ..account, re-creates it on a mint and + deletes it on a revoke. The keys are stored as the driver issues them, so + the format is plaintext. The chart renders no BucketAccess and no key for + these users. A platform user keeps its chart-rendered BucketAccess in + bucketclaim.yaml. +*/ -}} +{{- include "bucket.accountsGuard" $ }} +{{- range $user, $u := .Values.users }} +{{- if not (default false $u.platform) }} +--- +apiVersion: cozystack.io/v1alpha1 +kind: CredentialTemplate +metadata: + name: {{ printf "%s.%s" $.Release.Name (include "bucket.accountName" $user) | quote }} +spec: + username: {{ $user | quote }} + format: + name: plaintext + bucketAccess: + name: {{ include "bucket.accessName" (list $ $user) | quote }} + bucketClaimName: {{ $.Release.Name | quote }} + bucketAccessClassName: {{ include "bucket.accessClass" (list $ $u) | quote }} +{{- end }} +{{- end }} diff --git a/packages/apps/bucket/tests/credential_templates_test.yaml b/packages/apps/bucket/tests/credential_templates_test.yaml new file mode 100644 index 000000000..eed9a9134 --- /dev/null +++ b/packages/apps/bucket/tests/credential_templates_test.yaml @@ -0,0 +1,143 @@ +suite: bucket credential templates + +templates: + - templates/credentials.yaml + - templates/bucketclaim.yaml + +release: + name: bucket-photos + namespace: tenant-foo + +set: + _namespace: + seaweedfs: tenant-root + +tests: + - it: renders one engine-issued template per tenant user, naming the BucketAccess the controller creates + template: templates/credentials.yaml + set: + users: + web: {} + asserts: + - hasDocuments: + count: 1 + - isKind: + of: CredentialTemplate + - equal: + path: metadata.name + value: bucket-photos.web + - equal: + path: spec + value: + username: web + format: + name: plaintext + bucketAccess: + name: bucket-photos-web + bucketClaimName: bucket-photos + bucketAccessClassName: tenant-root + + - it: takes the read-only class of the storage pool for a read-only user + template: templates/credentials.yaml + set: + storagePool: fast + users: + reader: + readonly: true + asserts: + - equal: + path: spec.bucketAccess.bucketAccessClassName + value: tenant-root-fast-readonly + + - it: renders no BucketAccess for a tenant user + template: templates/bucketclaim.yaml + set: + users: + web: {} + asserts: + - hasDocuments: + count: 1 + - isKind: + of: BucketClaim + + - it: keeps a platform user's BucketAccess in the chart and gives it no template + set: + users: + system: + platform: true + asserts: + - hasDocuments: + count: 0 + template: templates/credentials.yaml + - hasDocuments: + count: 2 + template: templates/bucketclaim.yaml + - equal: + path: spec + value: + bucketAccessClassName: tenant-root + bucketClaimName: bucket-photos + credentialsSecretName: bucket-photos-system + protocol: s3 + template: templates/bucketclaim.yaml + documentSelector: + path: kind + value: BucketAccess + + # The pre-conversion chart named a user's BucketAccess -, + # and migration 71 hands that one over by name, so a user name that is a + # valid object name keeps it. Any other one never had a BucketAccess and + # takes the account name. + - it: names the BucketAccess as the pre-conversion chart did when that name is valid + template: templates/credentials.yaml + set: + users: + archive.v2: {} + asserts: + - equal: + path: metadata.name + value: bucket-photos.archive-v2 + - equal: + path: spec.bucketAccess.name + value: bucket-photos-archive.v2 + + - it: names the BucketAccess after the account when the user name is not a valid object name + template: templates/credentials.yaml + set: + users: + Web_Uploads: {} + asserts: + - equal: + path: metadata.name + value: bucket-photos.web-uploads + - equal: + path: spec.bucketAccess.name + value: bucket-photos-web-uploads + + - it: refuses a user whose account name is not a valid name + template: templates/credentials.yaml + set: + users: + "-web": {} + asserts: + - failedTemplate: + errorPattern: start and end with a letter or a digit + + - it: refuses a user whose account name is longer than a DNS label + template: templates/credentials.yaml + set: + users: + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: {} + asserts: + - failedTemplate: + errorPattern: at most 63 characters + + - it: refuses two users that map to one account + template: templates/credentials.yaml + set: + users: + Web: {} + web: {} + asserts: + - failedTemplate: + errorPattern: both map to the account name "web" diff --git a/packages/apps/bucket/tests/public_read_test.yaml b/packages/apps/bucket/tests/public_read_test.yaml index 1bdf5d82b..87370ba30 100644 --- a/packages/apps/bucket/tests/public_read_test.yaml +++ b/packages/apps/bucket/tests/public_read_test.yaml @@ -61,16 +61,18 @@ tests: path: spec.bucketAccessClassName value: tenant-root-public - - it: keeps the users' BucketAccesses next to the public one + - it: renders only the platform users' BucketAccesses next to the public one set: publicRead: true users: app: {} reader: readonly: true + system: + platform: true asserts: - hasDocuments: - count: 4 + count: 3 - it: refuses a user that would own the public BucketAccess name set: diff --git a/packages/apps/bucket/values.schema.json b/packages/apps/bucket/values.schema.json index 1e1311785..d7aa1d15d 100644 --- a/packages/apps/bucket/values.schema.json +++ b/packages/apps/bucket/values.schema.json @@ -37,6 +37,10 @@ "additionalProperties": { "type": "object", "properties": { + "platform": { + "description": "Marks a platform account, such as the `system` user of the backup bucket, which backupstrategy-controller sets. Its keys stay in the `\u003cbucket\u003e-\u003cuser\u003e-credentials` Secret, which no tenant can read, and are never minted. Clearing it drops the chart-rendered BucketAccess, which revokes those keys, and the user becomes a normal account whose keys are minted through its Credential. Leave it unset for your own users.", + "type": "boolean" + }, "readonly": { "description": "Whether the user has read-only access.", "type": "boolean" diff --git a/packages/apps/bucket/values.yaml b/packages/apps/bucket/values.yaml index 5a6c92ece..5aafb5945 100644 --- a/packages/apps/bucket/values.yaml +++ b/packages/apps/bucket/values.yaml @@ -16,6 +16,7 @@ publicRead: false ## @typedef {struct} User - Bucket user configuration. ## @field {bool} [readonly] - Whether the user has read-only access. +## @field {bool} [platform] - Marks a platform account, such as the `system` user of the backup bucket, which backupstrategy-controller sets. Its keys stay in the `--credentials` Secret, which no tenant can read, and are never minted. Clearing it drops the chart-rendered BucketAccess, which revokes those keys, and the user becomes a normal account whose keys are minted through its Credential. Leave it unset for your own users. ## @param {map[string]User} users - Users configuration map. users: {} diff --git a/packages/apps/rabbitmq/README.md b/packages/apps/rabbitmq/README.md index 85432c4b0..d1cbe6394 100644 --- a/packages/apps/rabbitmq/README.md +++ b/packages/apps/rabbitmq/README.md @@ -40,15 +40,14 @@ The scope is **definitions only** — vhosts, users, permissions, queues, exchan ### Application-specific parameters -| Name | Description | Type | Value | -| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ----- | -| `users` | Users configuration map. | `map[string]object` | `{}` | -| `users[name].password` | Password for the user. | `string` | `""` | -| `vhosts` | Virtual hosts configuration map. | `map[string]object` | `{}` | -| `vhosts[name].roles` | Virtual host roles list. | `object` | `{}` | -| `vhosts[name].roles.admin` | List of admin users. | `[]string` | `[]` | -| `vhosts[name].roles.readonly` | List of readonly users. | `[]string` | `[]` | -| `schedulingClass` | Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant. | `string` | `""` | +| Name | Description | Type | Value | +| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ----- | +| `users` | Users configuration map. Each user is a RabbitMQ user that messaging-topology-operator keeps from an account Secret the platform holds. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. The operator applies either to the broker within seconds. A `password` key here is ignored. The administrator in `-default-user` belongs to the platform and is not shown to tenants. | `map[string]object` | `{}` | +| `vhosts` | Virtual hosts configuration map. | `map[string]object` | `{}` | +| `vhosts[name].roles` | Virtual host roles list. | `object` | `{}` | +| `vhosts[name].roles.admin` | List of admin users. | `[]string` | `[]` | +| `vhosts[name].roles.readonly` | List of readonly users. | `[]string` | `[]` | +| `schedulingClass` | Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant. | `string` | `""` | ## TLS scope @@ -69,7 +68,7 @@ The broker pods roll once, because the operator mounts the new TLS Secret into t And **the published metrics port changes**. The operator exposes *either* `prometheus` (15692) *or* `prometheus-tls` (15691) on its Service, never both — deliberately, so that a scrape config selecting every port does not count each node twice — and that choice keys off TLS alone. Enabling TLS therefore withdraws 15692 from the Service and publishes 15691 in its place. The broker itself keeps listening on 15692, but a `ServiceMonitor` or `VMServiceScrape` selecting the port by the name `prometheus` stops matching. Retarget it to `prometheus-tls`, which is HTTPS under the release CA and so needs a `tlsConfig` carrying the trust anchor described below. The chart does not paper over this by re-adding 15692 through `spec.override.service`: the operator drops any port name it does not own on each reconcile and the override would reinstate it without a NodePort, which on a LoadBalancer means a fresh allocation and another reconcile every round. -And **the connection details handed to clients change**. `-default-user` is the Service Binding object this chart grants to the tenant, and the operator rewrites its `port` key from `5672` to `5671` as soon as `spec.tls.secretName` is set — gated on TLS alone, not on whether the plaintext listener is still open. A client that hardcodes `:5672` keeps working, because that listener does stay open. A client that resolves its endpoint from the binding — the documented way to consume it — follows the change to 5671 and must speak TLS from then on, and it cannot verify the certificate until the trust anchor below is obtainable. Per-plugin port keys (`mqtt-port`, `stomp-port`, `stream-port` and the web variants) move to their TLS values the same way. This is the main reason `tls.enabled` is opt-in rather than something `external` implies: it moves clients that read the binding correctly, and it moves them the instant the flag is set, before any of them has had a chance to pick up the trust anchor. +And **the connection details handed to clients change**. `-default-user` is the operator's Service Binding object, read by platform components such as the backup strategy and no longer by tenants, and the operator rewrites its `port` key from `5672` to `5671` as soon as `spec.tls.secretName` is set — gated on TLS alone, not on whether the plaintext listener is still open. A client that hardcodes `:5672` keeps working, because that listener does stay open. A client that resolves its endpoint from the binding — the documented way to consume it — follows the change to 5671 and must speak TLS from then on, and it cannot verify the certificate until the trust anchor below is obtainable. Per-plugin port keys (`mqtt-port`, `stomp-port`, `stream-port` and the web variants) move to their TLS values the same way. This is the main reason `tls.enabled` is opt-in rather than something `external` implies: it moves clients that read the binding correctly, and it moves them the instant the flag is set, before any of them has had a chance to pick up the trust anchor. **The plaintext management listener is load-bearing.** `messaging-topology-operator` is what reconciles the `User`, `Vhost` and `Permission` objects this chart creates from `users` and `vhosts`, and it talks to the broker over the management API. Once TLS is on it would switch to HTTPS on 15671 and verify the broker against the operator process's system certificate pool, which cannot contain a per-release self-signed CA — so every user and permission would fail to reconcile with `certificate signed by unknown authority`. The chart therefore annotates the cluster with `rabbitmq.com/operator-connection-uri` pointing at plaintext `http://…:15672`, keeping that operator on the in-cluster plaintext port. This affects only the operator's own management connection, never broker traffic, and it is why `tls.disableNonTLSListeners` cannot be combined with `users` or `vhosts`. diff --git a/packages/apps/rabbitmq/templates/_accounts.tpl b/packages/apps/rabbitmq/templates/_accounts.tpl new file mode 100644 index 000000000..e4ccdf9de --- /dev/null +++ b/packages/apps/rabbitmq/templates/_accounts.tpl @@ -0,0 +1,32 @@ +{{/* + Account Secret naming, which must match pkg/credentials/account.MapName: the + credentials API writes ..account, where is the + user name lowercased with every character outside [a-z0-9-] replaced by "-". +*/}} +{{- define "rabbitmq.accountName" -}} +{{- regexReplaceAll "[^a-z0-9-]" (lower .) "-" -}} +{{- end -}} + +{{- define "rabbitmq.accountSecret" -}} +{{- $root := index . 0 -}} +{{- $user := index . 1 -}} +{{- printf "%s.%s.account" $root.Release.Name (include "rabbitmq.accountName" $user) -}} +{{- end -}} + +{{/* + Two users mapping to one account would share one Secret, so the topology + operator would import the same credentials for both User objects. +*/}} +{{- define "rabbitmq.accountsGuard" -}} +{{- $seen := dict -}} +{{- range $user, $_ := .Values.users -}} + {{- $mapped := include "rabbitmq.accountName" $user -}} + {{- if or (gt (len $mapped) 63) (not (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" $mapped)) -}} + {{- fail (printf "user %q maps to the account name %q, which must be at most 63 characters and start and end with a letter or a digit; rename the user" $user $mapped) -}} + {{- end -}} + {{- with index $seen $mapped -}} + {{- fail (printf "users %q and %q both map to the account name %q; rename one of them" . $user $mapped) -}} + {{- end -}} + {{- $_ := set $seen $mapped $user -}} +{{- end -}} +{{- end -}} diff --git a/packages/apps/rabbitmq/templates/credentials.yaml b/packages/apps/rabbitmq/templates/credentials.yaml new file mode 100644 index 000000000..4bd78d5d7 --- /dev/null +++ b/packages/apps/rabbitmq/templates/credentials.yaml @@ -0,0 +1,25 @@ +{{- /* + One CredentialTemplate per user: the account the Cozystack credentials API + mints and revokes through. cozystack-controller keeps its account Secret, + ..account, which the User's importCredentialsSecret names + in rabbitmq.yaml. messaging-topology-operator watches that Secret and puts + the password to the broker again whenever it changes, so a mint applies + without a Helm run. The operator reads the plaintext and hashes it itself, + hence the plaintext format; the label is the one its Secret cache and its + User admission webhook require. The chart renders no password. +*/ -}} +{{- include "rabbitmq.accountsGuard" $ }} +{{- range $user, $_ := .Values.users }} +--- +apiVersion: cozystack.io/v1alpha1 +kind: CredentialTemplate +metadata: + name: {{ printf "%s.%s" $.Release.Name (include "rabbitmq.accountName" $user) | quote }} +spec: + username: {{ $user | quote }} + format: + name: plaintext + secret: + labels: + rabbitmq.com/topology-operator: "true" +{{- end }} diff --git a/packages/apps/rabbitmq/templates/rabbitmq.yaml b/packages/apps/rabbitmq/templates/rabbitmq.yaml index a77ed6a08..24d983e24 100644 --- a/packages/apps/rabbitmq/templates/rabbitmq.yaml +++ b/packages/apps/rabbitmq/templates/rabbitmq.yaml @@ -129,44 +129,24 @@ spec: {{- end }} storage: {{ .Values.size }} -{{- range $user, $u := .Values.users }} - -{{- $password := $u.password }} -{{- if not $password }} -{{- with (dig "data" "password" "" (lookup "v1" "Secret" $.Release.Namespace (printf "%s-%s-credentials" $.Release.Name (kebabcase $user)))) }} -{{- $password = b64dec . }} -{{- end }} -{{- end }} -{{- if not $password }} -{{- $password = (randAlphaNum 16) }} -{{- end }} - +{{- /* The User object keeps its pre-conversion name: renaming it would make + the operator delete the broker user and create it again. Its password + comes from the account Secret of credentials.yaml, which the operator + re-imports on every change. Until the Secret exists the operator's + admission webhook refuses the User, so a release that adds a user + converges on the retry after cozystack-controller has seeded it. */}} +{{- include "rabbitmq.accountsGuard" $ }} +{{- range $user, $_ := .Values.users }} --- apiVersion: rabbitmq.com/v1beta1 kind: User metadata: name: {{ $.Release.Name }}-{{ kebabcase $user }} - annotations: - config: '{{ printf "%s %s" $user $password | sha256sum }}' spec: importCredentialsSecret: - name: {{ $.Release.Name }}-{{ kebabcase $user }}-credentials + name: {{ include "rabbitmq.accountSecret" (list $ $user) | quote }} rabbitmqClusterReference: name: {{ $.Release.Name }} ---- -apiVersion: v1 -kind: Secret -metadata: - name: {{ $.Release.Name }}-{{ kebabcase $user }}-credentials - labels: - apps.cozystack.io/user-secret: "true" - # Topology Operator >= 1.20 caches only Secrets carrying this label, and its User - # admission webhook rejects an importCredentialsSecret that lacks it. - rabbitmq.com/topology-operator: "true" -type: Opaque -stringData: - username: {{ $user }} - password: {{ $password }} {{- end }} {{- range $host, $h := .Values.vhosts }} diff --git a/packages/apps/rabbitmq/tests/credential_templates_test.yaml b/packages/apps/rabbitmq/tests/credential_templates_test.yaml new file mode 100644 index 000000000..a39aedbcc --- /dev/null +++ b/packages/apps/rabbitmq/tests/credential_templates_test.yaml @@ -0,0 +1,84 @@ +suite: one CredentialTemplate per user, naming the account Secret the User imports + +# The template is the account the credentials API mints through; its name plus +# ".account" must be the importCredentialsSecret rabbitmq.yaml gives the User, +# or the topology operator reads a Secret nobody writes. + +templates: + - templates/credentials.yaml + +release: + name: rabbitmq-test + namespace: tenant-test + +tests: + - it: renders nothing without users + asserts: + - hasDocuments: + count: 0 + + - it: renders a template per user, named for the account Secret's mapping + set: + users: + web: {} + Bob.Smith: {} + asserts: + - hasDocuments: + count: 2 + - isKind: + of: CredentialTemplate + - equal: + path: apiVersion + value: cozystack.io/v1alpha1 + - equal: + path: metadata.name + value: rabbitmq-test.bob-smith + documentIndex: 0 + - equal: + path: spec.username + value: Bob.Smith + documentIndex: 0 + - equal: + path: metadata.name + value: rabbitmq-test.web + documentIndex: 1 + + - it: stores the plaintext the operator hashes, labelled for its Secret cache + set: + users: + web: {} + asserts: + - equal: + path: spec.format.name + value: plaintext + - equal: + path: spec.secret.labels + value: + rabbitmq.com/topology-operator: "true" + - notExists: + path: spec.valuesPath + + - it: refuses two users that map to one account + set: + users: + web: {} + Web: {} + asserts: + - failedTemplate: + errorPattern: map to + + - it: refuses a user that maps to no valid account name + set: + users: + "-web": {} + asserts: + - failedTemplate: + errorPattern: start and end with a letter or a digit + + - it: refuses a user whose account name is longer than a DNS label + set: + users: + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: {} + asserts: + - failedTemplate: + errorPattern: at most 63 characters diff --git a/packages/apps/rabbitmq/tests/user_credentials_test.yaml b/packages/apps/rabbitmq/tests/user_credentials_test.yaml index b1a57c8d8..202c7b19d 100644 --- a/packages/apps/rabbitmq/tests/user_credentials_test.yaml +++ b/packages/apps/rabbitmq/tests/user_credentials_test.yaml @@ -1,4 +1,4 @@ -suite: RabbitMQ user credentials Secrets +suite: RabbitMQ users read their password from the account Secret templates: - templates/rabbitmq.yaml @@ -7,20 +7,19 @@ release: name: myrabbitmq namespace: tenant-test -# messaging-topology-operator >= 1.20 caches only Secrets labelled -# rabbitmq.com/topology-operator=true, and its User admission webhook rejects an -# importCredentialsSecret that lacks the label. Losing it rejects every User the -# chart renders. +# messaging-topology-operator re-imports importCredentialsSecret whenever the +# Secret changes, so pointing each User at the account Secret the credentials +# API writes is what makes a mint reach the broker. The User keeps its +# pre-conversion name: renaming it would make the operator delete the broker +# user and create it again. set: users: - alice: - password: alicepassword - bobSmith: - password: bobpassword + alice: {} + bobSmith: {} tests: - - it: points each User at its own credentials Secret + - it: points each User at its account Secret and keeps its name documentSelector: path: metadata.name value: myrabbitmq-bob-smith @@ -29,15 +28,38 @@ tests: of: User - equal: path: spec.importCredentialsSecret.name - value: myrabbitmq-bob-smith-credentials + value: myrabbitmq.bobsmith.account + - notExists: + path: metadata.annotations - - it: labels every credentials Secret for the topology operator's Secret cache - documentSelector: - path: kind - value: Secret - matchMany: true + - it: renders no Secret, so no password reaches the release asserts: - - equal: - path: metadata.labels["rabbitmq.com/topology-operator"] - value: "true" + - containsDocument: + kind: Secret + apiVersion: v1 + not: true + - it: ignores a password left in values + set: + users: + alice: + password: alicepassword + asserts: + - containsDocument: + kind: Secret + apiVersion: v1 + not: true + - notExists: + path: metadata.annotations.config + documentSelector: + path: metadata.name + value: myrabbitmq-alice + + - it: refuses two users that map to one account + set: + users: + web: {} + Web: {} + asserts: + - failedTemplate: + errorPattern: map to diff --git a/packages/apps/rabbitmq/values.schema.json b/packages/apps/rabbitmq/values.schema.json index d5fb22b0b..0f9fb5acc 100644 --- a/packages/apps/rabbitmq/values.schema.json +++ b/packages/apps/rabbitmq/values.schema.json @@ -160,17 +160,11 @@ ] }, "users": { - "description": "Users configuration map.", + "description": "Users configuration map. Each user is a RabbitMQ user that messaging-topology-operator keeps from an account Secret the platform holds. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. The operator applies either to the broker within seconds. A `password` key here is ignored. The administrator in `\u003crelease\u003e-default-user` belongs to the platform and is not shown to tenants.", "type": "object", "default": {}, "additionalProperties": { - "type": "object", - "properties": { - "password": { - "description": "Password for the user.", - "type": "string" - } - } + "type": "object" } }, "vhosts": { diff --git a/packages/apps/rabbitmq/values.yaml b/packages/apps/rabbitmq/values.yaml index 31409587b..e2125af2c 100644 --- a/packages/apps/rabbitmq/values.yaml +++ b/packages/apps/rabbitmq/values.yaml @@ -102,18 +102,13 @@ version: v4.2 ## ## @typedef {struct} User - User configuration. -## @field {string} [password] - Password for the user. -## @param {map[string]User} users - Users configuration map. +## @param {map[string]User} users - Users configuration map. Each user is a RabbitMQ user that messaging-topology-operator keeps from an account Secret the platform holds. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. The operator applies either to the broker within seconds. A `password` key here is ignored. The administrator in `-default-user` belongs to the platform and is not shown to tenants. users: {} ## Example: ## users: -## user1: -## password: strongpassword -## user2: -## password: hackme -## user3: -## password: testtest +## user1: {} +## user2: {} ## @typedef {struct} Roles - Virtual host roles. ## @field {[]string} [admin] - List of admin users. diff --git a/packages/apps/redis/README.md b/packages/apps/redis/README.md index 0986a3e13..12a231d96 100644 --- a/packages/apps/redis/README.md +++ b/packages/apps/redis/README.md @@ -44,7 +44,7 @@ Service utilizes the freshworks-oss Redis Operator (a maintained fork of the arc | Name | Description | Type | Value | | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------ | -| `authEnabled` | Enable password generation. | `bool` | `true` | +| `authEnabled` | Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password. | `bool` | `true` | | `minReplicasToWrite` | Redis `min-replicas-to-write`: the master refuses writes unless at least this many replicas are connected and within `minReplicasMaxLag`. Unset by default, which leaves the Redis default (disabled). With `replicas: 2` and a value of 1 the master rejects writes while its only replica is down, trading availability for a bound on the writes lost if an isolated master is failed over. Replication stays asynchronous, so this bounds the loss, it does not remove it. Must be 0 or more and below `replicas` (a master with `replicas` pods has `replicas - 1` replicas), otherwise every write is refused; the chart refuses such a value. | `*int` | `null` | | `minReplicasMaxLag` | Redis `min-replicas-max-lag`, in seconds: a replica whose last acknowledgement is older than this does not count towards `minReplicasToWrite`. Unset by default, which leaves the Redis default (10). Has no effect unless `minReplicasToWrite` is set. Must be at least 1 when `minReplicasToWrite` is set: Redis treats 0 as disabling the check, so the chart refuses it. | `*int` | `null` | | `maxmemory` | Redis `maxmemory`: the dataset size at which Redis applies `maxmemoryPolicy`. Unset by default, which renders `maxmemory 0` (no limit, the Redis default), so a value set by hand with `CONFIG SET` is reset on the next reconcile. Must be at most 90% of the memory request of each Redis pod (from `resources` or `resourcesPreset`): the operator silently drops a larger value, so the chart refuses it. Leave headroom below that for replication and snapshot buffers. | `quantity` | `""` | diff --git a/packages/apps/redis/templates/credentials.yaml b/packages/apps/redis/templates/credentials.yaml new file mode 100644 index 000000000..4bb33d42d --- /dev/null +++ b/packages/apps/redis/templates/credentials.yaml @@ -0,0 +1,21 @@ +{{- /* + The one account of this kind: the default user, whose password the + Cozystack credentials API mints and revokes. cozystack-controller keeps its + account Secret, .default.account, which auth.secretPath names, and + the operator applies a changed password with CONFIG SET, restarting + nothing. The chart renders no password, and nobody can log in until a mint. + + Replication, the Sentinels, the probes and the metrics exporter do not use + it: the operator gives them an internal account of their own. The backup + Job does, reading it when the Job starts. +*/ -}} +{{- if .Values.authEnabled }} +apiVersion: cozystack.io/v1alpha1 +kind: CredentialTemplate +metadata: + name: {{ printf "%s.default" .Release.Name | quote }} +spec: + username: default + format: + name: plaintext +{{- end }} diff --git a/packages/apps/redis/templates/redisfailover.yaml b/packages/apps/redis/templates/redisfailover.yaml index 143f29d6b..fa409dd8f 100644 --- a/packages/apps/redis/templates/redisfailover.yaml +++ b/packages/apps/redis/templates/redisfailover.yaml @@ -30,20 +30,6 @@ {{- if or $sentinel.resources $sentinel.resourcesPreset -}} {{- $sentinelResources = $sentinel.resources | default dict -}} {{- end -}} -{{- if .Values.authEnabled }} - {{- $existingPassword := lookup "v1" "Secret" .Release.Namespace (printf "%s-auth" .Release.Name) }} - {{- $password := randAlphaNum 32 | b64enc }} - {{- if $existingPassword }} - {{- $password = index $existingPassword.data "password" }} - {{- end }} ---- -apiVersion: v1 -kind: Secret -metadata: - name: {{ .Release.Name }}-auth -data: - password: {{ $password }} -{{- end }} --- @@ -214,8 +200,13 @@ spec: - min-replicas-max-lag {{ .Values.minReplicasMaxLag | int }} {{- end }} {{- if .Values.authEnabled }} + {{- /* The account Secret of the default CredentialTemplate (credentials.yaml), + which cozystack-controller keeps and the credentials API rewrites on a + mint. The operator reads its password key on every reconcile and + applies a changed one to the running servers with CONFIG SET; nothing + else it runs authenticates with it. */}} auth: - secretPath: {{ .Release.Name }}-auth + secretPath: {{ printf "%s.default.account" .Release.Name }} {{- end }} --- diff --git a/packages/apps/redis/tests/credential_templates_test.yaml b/packages/apps/redis/tests/credential_templates_test.yaml new file mode 100644 index 000000000..6a3db93e8 --- /dev/null +++ b/packages/apps/redis/tests/credential_templates_test.yaml @@ -0,0 +1,80 @@ +suite: the default account is a CredentialTemplate whose account Secret the operator reads + +# The template is the account the credentials API mints through; its name plus +# ".account" must be the auth.secretPath of the RedisFailover, or the operator +# reads a Secret nobody writes. The chart itself renders no password. + +release: + name: my-redis + namespace: tenant-test + +tests: + - it: renders the default account while authentication is on + templates: + - templates/credentials.yaml + asserts: + - hasDocuments: + count: 1 + - isKind: + of: CredentialTemplate + - equal: + path: apiVersion + value: cozystack.io/v1alpha1 + - equal: + path: metadata.name + value: my-redis.default + - equal: + path: spec.username + value: default + # The operator reads the password itself from the account Secret. + - equal: + path: spec.format.name + value: plaintext + # The operator re-reads the Secret on its own resync and watches nothing + # a label would select. + - notExists: + path: spec.secret + - notExists: + path: spec.valuesPath + + - it: renders no account without authentication + templates: + - templates/credentials.yaml + set: + authEnabled: false + asserts: + - hasDocuments: + count: 0 + + - it: points the operator at the account Secret + templates: + - templates/redisfailover.yaml + documentSelector: + path: kind + value: RedisFailover + asserts: + - equal: + path: spec.auth.secretPath + value: my-redis.default.account + + - it: gives the operator no Secret without authentication + templates: + - templates/redisfailover.yaml + set: + authEnabled: false + documentSelector: + path: kind + value: RedisFailover + asserts: + - notExists: + path: spec.auth + + - it: renders no password Secret + templates: + - templates/redisfailover.yaml + asserts: + - containsDocument: + kind: Secret + apiVersion: v1 + name: my-redis-auth + not: true diff --git a/packages/apps/redis/values.schema.json b/packages/apps/redis/values.schema.json index bfeae6c9f..a3696cc07 100644 --- a/packages/apps/redis/values.schema.json +++ b/packages/apps/redis/values.schema.json @@ -176,7 +176,7 @@ } }, "authEnabled": { - "description": "Enable password generation.", + "description": "Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password.", "type": "boolean", "default": true }, diff --git a/packages/apps/redis/values.yaml b/packages/apps/redis/values.yaml index 5422c8dd5..21622a10a 100644 --- a/packages/apps/redis/values.yaml +++ b/packages/apps/redis/values.yaml @@ -119,7 +119,7 @@ tls: {} ## @section Application-specific parameters ## -## @param {bool} authEnabled - Enable password generation. +## @param {bool} authEnabled - Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password. authEnabled: true ## @param {*int} [minReplicasToWrite] - Redis `min-replicas-to-write`: the master refuses writes unless at least this many replicas are connected and within `minReplicasMaxLag`. Unset by default, which leaves the Redis default (disabled). With `replicas: 2` and a value of 1 the master rejects writes while its only replica is down, trading availability for a bound on the writes lost if an isolated master is failed over. Replication stays asynchronous, so this bounds the loss, it does not remove it. Must be 0 or more and below `replicas` (a master with `replicas` pods has `replicas - 1` replicas), otherwise every write is refused; the chart refuses such a value. diff --git a/packages/apps/valkey/README.md b/packages/apps/valkey/README.md index e2ee1c404..7b5c2a6ec 100644 --- a/packages/apps/valkey/README.md +++ b/packages/apps/valkey/README.md @@ -33,7 +33,7 @@ Service runs Valkey on the freshworks-oss redis-operator, which manages Sentinel | Name | Description | Type | Value | | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------ | -| `authEnabled` | Enable password generation. | `bool` | `true` | +| `authEnabled` | Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password. | `bool` | `true` | | `schedulingClass` | Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant. | `string` | `""` | diff --git a/packages/apps/valkey/templates/credentials.yaml b/packages/apps/valkey/templates/credentials.yaml new file mode 100644 index 000000000..4bb33d42d --- /dev/null +++ b/packages/apps/valkey/templates/credentials.yaml @@ -0,0 +1,21 @@ +{{- /* + The one account of this kind: the default user, whose password the + Cozystack credentials API mints and revokes. cozystack-controller keeps its + account Secret, .default.account, which auth.secretPath names, and + the operator applies a changed password with CONFIG SET, restarting + nothing. The chart renders no password, and nobody can log in until a mint. + + Replication, the Sentinels, the probes and the metrics exporter do not use + it: the operator gives them an internal account of their own. The backup + Job does, reading it when the Job starts. +*/ -}} +{{- if .Values.authEnabled }} +apiVersion: cozystack.io/v1alpha1 +kind: CredentialTemplate +metadata: + name: {{ printf "%s.default" .Release.Name | quote }} +spec: + username: default + format: + name: plaintext +{{- end }} diff --git a/packages/apps/valkey/templates/valkeyfailover.yaml b/packages/apps/valkey/templates/valkeyfailover.yaml index e6046162a..972779fcd 100644 --- a/packages/apps/valkey/templates/valkeyfailover.yaml +++ b/packages/apps/valkey/templates/valkeyfailover.yaml @@ -6,23 +6,7 @@ {{- fail (trim (printf "valkey: _cluster.scheduling.globalAppTopologySpreadConstraints must be YAML with a non-empty topologySpreadConstraints list. %s" (get $policy "Error"))) }} {{- end }} {{- end }} -{{- if .Values.authEnabled }} - {{- $existingPassword := lookup "v1" "Secret" .Release.Namespace (printf "%s-auth" .Release.Name) }} - {{- $password := randAlphaNum 32 | b64enc }} - {{- if $existingPassword }} - {{- $password = index $existingPassword.data "password" }} - {{- end }} --- -apiVersion: v1 -kind: Secret -metadata: - name: {{ .Release.Name }}-auth -data: - password: {{ $password }} -{{- end }} - ---- - apiVersion: databases.spotahome.com/v1 kind: RedisFailover metadata: @@ -113,8 +97,13 @@ spec: - save "" {{- end }} {{- if .Values.authEnabled }} + {{- /* The account Secret of the default CredentialTemplate (credentials.yaml), + which cozystack-controller keeps and the credentials API rewrites on a + mint. The operator reads its password key on every reconcile and + applies a changed one to the running servers with CONFIG SET; nothing + else it runs authenticates with it. */}} auth: - secretPath: {{ .Release.Name }}-auth + secretPath: {{ printf "%s.default.account" .Release.Name }} {{- end }} --- diff --git a/packages/apps/valkey/tests/credential_templates_test.yaml b/packages/apps/valkey/tests/credential_templates_test.yaml new file mode 100644 index 000000000..b8ad2958a --- /dev/null +++ b/packages/apps/valkey/tests/credential_templates_test.yaml @@ -0,0 +1,80 @@ +suite: the default account is a CredentialTemplate whose account Secret the operator reads + +# The template is the account the credentials API mints through; its name plus +# ".account" must be the auth.secretPath of the RedisFailover, or the operator +# reads a Secret nobody writes. The chart itself renders no password. + +release: + name: my-valkey + namespace: tenant-test + +tests: + - it: renders the default account while authentication is on + templates: + - templates/credentials.yaml + asserts: + - hasDocuments: + count: 1 + - isKind: + of: CredentialTemplate + - equal: + path: apiVersion + value: cozystack.io/v1alpha1 + - equal: + path: metadata.name + value: my-valkey.default + - equal: + path: spec.username + value: default + # The operator reads the password itself from the account Secret. + - equal: + path: spec.format.name + value: plaintext + # The operator re-reads the Secret on its own resync and watches nothing + # a label would select. + - notExists: + path: spec.secret + - notExists: + path: spec.valuesPath + + - it: renders no account without authentication + templates: + - templates/credentials.yaml + set: + authEnabled: false + asserts: + - hasDocuments: + count: 0 + + - it: points the operator at the account Secret + templates: + - templates/valkeyfailover.yaml + documentSelector: + path: kind + value: RedisFailover + asserts: + - equal: + path: spec.auth.secretPath + value: my-valkey.default.account + + - it: gives the operator no Secret without authentication + templates: + - templates/valkeyfailover.yaml + set: + authEnabled: false + documentSelector: + path: kind + value: RedisFailover + asserts: + - notExists: + path: spec.auth + + - it: renders no password Secret + templates: + - templates/valkeyfailover.yaml + asserts: + - containsDocument: + kind: Secret + apiVersion: v1 + name: my-valkey-auth + not: true diff --git a/packages/apps/valkey/values.schema.json b/packages/apps/valkey/values.schema.json index ce54b1636..22644d4b8 100644 --- a/packages/apps/valkey/values.schema.json +++ b/packages/apps/valkey/values.schema.json @@ -137,7 +137,7 @@ ] }, "authEnabled": { - "description": "Enable password generation.", + "description": "Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password.", "type": "boolean", "default": true }, diff --git a/packages/apps/valkey/values.yaml b/packages/apps/valkey/values.yaml index 581f8998a..c39cf49fe 100644 --- a/packages/apps/valkey/values.yaml +++ b/packages/apps/valkey/values.yaml @@ -86,7 +86,7 @@ version: v8 ## @section Application-specific parameters ## -## @param {bool} authEnabled - Enable password generation. +## @param {bool} authEnabled - Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password. authEnabled: true ## @param {string} schedulingClass - Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant. diff --git a/packages/core/platform/images/migrations/Dockerfile b/packages/core/platform/images/migrations/Dockerfile index f3a745841..232b4f5e9 100644 --- a/packages/core/platform/images/migrations/Dockerfile +++ b/packages/core/platform/images/migrations/Dockerfile @@ -55,9 +55,10 @@ RUN mkdir /strimzi-crds && \ https://github.com/strimzi/strimzi-kafka-operator/releases/download/0.51.0/strimzi-crds-0.51.0.yaml && \ echo "a11257e67985a946a6facfb17d729aac5670b89675d410d13162fe455a5ac7a8 /strimzi-crds/strimzi-crds-0.51.0.yaml" | sha256sum -c - -# The CredentialTemplate CRD, which migration 64 applies before the converted -# charts render templates: it ships with cozystack-controller, whose release -# can upgrade after the tenant releases switch charts. +# The CredentialTemplate CRD, which the credentials conversions apply (see +# migrations/lib/credential-crd.sh) before the converted charts render +# templates: it ships with cozystack-controller, whose release can upgrade +# after the tenant releases switch charts. COPY packages/system/cozystack-controller/definitions/cozystack.io_credentialtemplates.yaml /credential-crds/ COPY packages/core/platform/images/migrations/migrations /migrations # v1alpha2 etcd CRDs, vendored into the build context by `make image-migrations`. diff --git a/packages/core/platform/images/migrations/migrations/64 b/packages/core/platform/images/migrations/migrations/64 index 8b5ecf80e..ea37d1c9d 100755 --- a/packages/core/platform/images/migrations/migrations/64 +++ b/packages/core/platform/images/migrations/migrations/64 @@ -48,21 +48,16 @@ set -euo pipefail # shellcheck source=lib/cozystack-version.sh . "$(dirname "$0")/lib/cozystack-version.sh" +# shellcheck source=lib/credential-crd.sh +. "$(dirname "$0")/lib/credential-crd.sh" NAMESPACE="${NAMESPACE:-cozy-system}" # The converted postgres chart renders CredentialTemplates, whose CRD ships # with cozystack-controller. That release can upgrade minutes after the tenant # releases switch charts, and every render in between fails on the unknown -# kind, so apply the CRD baked into this image first, owned by the -# cozystack-controller release as its later upgrade expects to find it. -CRD_FILE="${CREDENTIAL_CRD_FILE:-/credential-crds/cozystack.io_credentialtemplates.yaml}" -kubectl apply --server-side --force-conflicts --filename "$CRD_FILE" -kubectl label crd credentialtemplates.cozystack.io app.kubernetes.io/managed-by=Helm --overwrite -kubectl annotate crd credentialtemplates.cozystack.io \ - meta.helm.sh/release-name=cozystack-controller \ - meta.helm.sh/release-namespace=cozy-system --overwrite -kubectl wait --for=condition=established crd/credentialtemplates.cozystack.io --timeout=60s +# kind, so apply the CRD baked into this image first. +apply_credential_crd credentials-migrate seed \ --migration 64 \ diff --git a/packages/core/platform/images/migrations/migrations/68 b/packages/core/platform/images/migrations/migrations/68 new file mode 100755 index 000000000..f4b545370 --- /dev/null +++ b/packages/core/platform/images/migrations/migrations/68 @@ -0,0 +1,179 @@ +#!/bin/sh +# Migration 68 --> 69 +# Convert RabbitMQ users to platform-minted credentials, first part. +# +# The converted rabbitmq chart renders a CredentialTemplate per user and +# points each User's importCredentialsSecret at the template's account +# Secret, which cozystack-controller seeds with a random password only on a +# release marked for seeding. This hook runs before any component chart +# changes version and writes those Secrets, unowned, for every existing +# RabbitMQ release from the per-user --credentials Secrets the +# old chart generated, so clients keep logging in at every point of the +# upgrade; the controller adopts them once the templates exist. The old +# chart kept one Secret per user, holding username and password, so they are +# found by label and by the Helm release that rendered them. A release whose +# every user got its Secret is marked for seeding, so users added later are +# seeded too. The account Secret carries the label messaging-topology-operator +# caches Secrets by; without it the operator's admission webhook refuses the +# User. +# +# The second part is the cozystack-credentials-migration-68 Job, which waits +# per release for its chart to switch, then strips any users..password +# left in the values, deletes a per-user Secret Helm did not prune, and labels +# the operator's -default-user Secret not tenant-visible. That Secret +# holds the administrator messaging-topology-operator logs in with. The +# converted ApplicationDefinition excludes it, which keeps it hidden on every +# rewrite by the cluster operator: that rewrite replaces the Secret's labels, +# and the lineage webhook stamps it again from the definition. The label is +# still needed for the Secret as it stands, which the webhook stamped visible +# under the old definition and leaves alone until such a rewrite. It goes on +# only once the definition in the API excludes the Secret: the rabbitmq-rd +# chart upgrades after the new cluster operator is Ready, whose first pass +# rewrites the Secret, and a label written before would be undone by it. Its +# password is not rotated here: the broker takes the default user's password +# only at first boot, so a rotation is a broker operation this Job does not +# have. +# +# The Job is created directly rather than rendered from the platform chart, +# for the reasons migration 64 gives, and runs the image this hook runs as. +# Its ServiceAccount, ClusterRole and binding carry this migration's number, +# so a conversion running in the same upgrade never deletes or re-owns +# another's identity. The ClusterRole is least-privilege: finish needs CRUD +# and list on Secrets (list, for the per-user sources), get/list/patch on +# HelmReleases, create on Events, and its state ConfigMap. The ServiceAccount +# is owned by the Job, so the garbage collector removes it with the Job; the +# ClusterRoleBinding cannot be owned by a namespaced Job and is left, granting +# to no subject once the ServiceAccount is gone. To rerun the Job by hand, +# delete it and re-apply the manifest below. +# +# Fail-closed: migrations never re-run, so an error here stops the upgrade +# rather than stamping the version past a release that was not recorded. + +set -euo pipefail + +# shellcheck source=lib/cozystack-version.sh +. "$(dirname "$0")/lib/cozystack-version.sh" + +NAMESPACE="${NAMESPACE:-cozy-system}" +NAME=cozystack-credentials-migration-68 + +credentials-migrate seed \ + --migration 68 \ + --kind RabbitMQ \ + --format plaintext \ + --accounts-path users \ + --source-selector 'apps.cozystack.io/user-secret=true' \ + --source-key password \ + --label 'rabbitmq.com/topology-operator=true' + +# The finish Job runs the same image as this hook. Read it from this pod's +# own container by name, as migration 64 does. +image=$(kubectl get pod "$(hostname)" \ + --namespace "$NAMESPACE" \ + --output 'jsonpath={.spec.containers[?(@.name=="migration")].image}') +if [ -z "$image" ]; then + echo "cannot read this pod's image to run the finish Job" >&2 + exit 1 +fi + +# Delete any Job and ServiceAccount left by an earlier run of this hook: the +# pod template is immutable, and a ServiceAccount still owned by the deleted +# Job could be collected after the apply below. finish recovers its progress +# from the state ConfigMap, so recreating the Job loses nothing. +kubectl delete job "$NAME" \ + --namespace "$NAMESPACE" \ + --ignore-not-found +kubectl delete serviceaccount "$NAME" \ + --namespace "$NAMESPACE" \ + --ignore-not-found + +kubectl apply --filename - <&2 + exit 1 +fi +kubectl patch serviceaccount "$NAME" \ + --namespace "$NAMESPACE" \ + --type merge \ + --patch "{\"metadata\":{\"ownerReferences\":[{\"apiVersion\":\"batch/v1\",\"kind\":\"Job\",\"name\":\"${NAME}\",\"uid\":\"${job_uid}\"}]}}" + +stamp_cozystack_version 69 diff --git a/packages/core/platform/images/migrations/migrations/69 b/packages/core/platform/images/migrations/migrations/69 new file mode 100755 index 000000000..1d10e9c61 --- /dev/null +++ b/packages/core/platform/images/migrations/migrations/69 @@ -0,0 +1,176 @@ +#!/bin/sh +# Migration 69 --> 70 +# Convert the Redis password to platform-minted credentials, first part. +# +# The converted redis chart renders one CredentialTemplate, for the default +# user, while authEnabled is on, and points the RedisFailover's +# auth.secretPath at its account Secret, which cozystack-controller seeds +# with a random password only on a release marked for seeding. This hook runs +# before any component chart changes version and writes that Secret, unowned, +# for every existing Redis release from the password in -auth, so +# the clients keep the password they have at every point of the upgrade. +# (Replication, the Sentinels, the probes and the exporter move to the +# operator's own internal account when the operator is upgraded, +# independently of this migration.) The controller adopts the Secret once +# the template exists. A release whose Secret was written, or that has +# authentication off, is marked for seeding. +# The Redis backup strategy reads the same account Secret, so the next +# backup authenticates with the migrated password. +# +# The hook also suspends every Redis release until the redis-operator +# Deployment runs its new revision. Every application chart switches the +# moment the platform chart moves the packages source, while the operator +# rolls out later, and the converted chart changes the pod template: the +# old operator rolls such a change by deleting the master, failing writes +# for about a minute, where the new one moves the master off first and +# applies the password with no restart. The finish Job resumes the +# releases once the new operator runs, and may read Deployments for that. +# +# The second part is the cozystack-credentials-migration-69 Job, which waits +# per release for its chart to switch, then deletes whatever is left of +# -auth, which the switched chart no longer renders. The hook creates +# the Job directly, with a least-privilege ServiceAccount the Job owns, for the +# reasons migration 64 gives: a chart-rendered Job would hold up the platform +# release and fault on its immutable pod template at the next upgrade. To +# rerun it by hand, delete the Job and re-apply the manifest below. +# +# Fail-closed: migrations never re-run, so an error here stops the upgrade +# rather than stamping the version past a release that was not recorded. + +set -euo pipefail + +# shellcheck source=lib/cozystack-version.sh +. "$(dirname "$0")/lib/cozystack-version.sh" + +NAMESPACE="${NAMESPACE:-cozy-system}" + +credentials-migrate seed \ + --migration 69 \ + --kind Redis \ + --format plaintext \ + --fixed-account default \ + --source-key password \ + --enabled-flag authEnabled \ + --source-suffix=-auth \ + --hold-until-rollout cozy-redis-operator/redis-operator + +# The finish Job runs the same image as this hook, so a release and its +# conversion share the credentials-migrate build. Read it from this pod's own +# container by name rather than render it from values, which the hook does not +# carry, and rather than by position, which a webhook-injected container shifts. +image=$(kubectl get pod "$(hostname)" \ + --namespace "$NAMESPACE" \ + --output 'jsonpath={.spec.containers[?(@.name=="migration")].image}') +if [ -z "$image" ]; then + echo "cannot read this pod's image to run the finish Job" >&2 + exit 1 +fi + +# Delete any Job left by an earlier run of this hook: its pod template is +# immutable, so a rerun on a newer image would fault on apply. finish recovers +# its progress from the state ConfigMap, so recreating the Job loses nothing. +# Delete the ServiceAccount with it: an earlier run may have left it owned by +# the Job just deleted, and the apply below does not touch ownerReferences, so +# without this the garbage collector could remove the re-applied ServiceAccount +# out from under the ownerReference patch. A fresh, owner-less ServiceAccount is +# never collected before the patch names the new Job. +kubectl delete job cozystack-credentials-migration-69 \ + --namespace "$NAMESPACE" \ + --ignore-not-found +kubectl delete serviceaccount cozystack-credentials-migration-69 \ + --namespace "$NAMESPACE" \ + --ignore-not-found + +kubectl apply --filename - <&2 + exit 1 +fi +kubectl patch serviceaccount cozystack-credentials-migration-69 \ + --namespace "$NAMESPACE" \ + --type merge \ + --patch "{\"metadata\":{\"ownerReferences\":[{\"apiVersion\":\"batch/v1\",\"kind\":\"Job\",\"name\":\"cozystack-credentials-migration-69\",\"uid\":\"${job_uid}\"}]}}" + +stamp_cozystack_version 70 diff --git a/packages/core/platform/images/migrations/migrations/70 b/packages/core/platform/images/migrations/migrations/70 new file mode 100755 index 000000000..9dd2e88b0 --- /dev/null +++ b/packages/core/platform/images/migrations/migrations/70 @@ -0,0 +1,174 @@ +#!/bin/sh +# Migration 70 --> 71 +# Convert the Valkey password to platform-minted credentials, first part. +# +# The converted valkey chart renders one CredentialTemplate, for the default +# user, while authEnabled is on, and points the RedisFailover's +# auth.secretPath at its account Secret, which cozystack-controller seeds +# with a random password only on a release marked for seeding. This hook runs +# before any component chart changes version and writes that Secret, unowned, +# for every existing Valkey release from the password in -auth, so +# the clients keep the password they have at every point of the upgrade. +# (Replication, the Sentinels, the probes and the exporter move to the +# operator's own internal account when the operator is upgraded, +# independently of this migration.) The controller adopts the Secret once +# the template exists. A release whose Secret was written, or that has +# authentication off, is marked for seeding. +# +# The hook also suspends every Valkey release until the redis-operator +# Deployment runs its new revision. Every application chart switches the +# moment the platform chart moves the packages source, while the operator +# rolls out later, and the converted chart changes the pod template: the +# old operator rolls such a change by deleting the master, failing writes +# for about a minute, where the new one moves the master off first and +# applies the password with no restart. The finish Job resumes the +# releases once the new operator runs, and may read Deployments for that. +# +# The second part is the cozystack-credentials-migration-70 Job, which waits +# per release for its chart to switch, then deletes whatever is left of +# -auth, which the switched chart no longer renders. The hook creates +# the Job directly, with a least-privilege ServiceAccount the Job owns, for the +# reasons migration 64 gives: a chart-rendered Job would hold up the platform +# release and fault on its immutable pod template at the next upgrade. To +# rerun it by hand, delete the Job and re-apply the manifest below. +# +# Fail-closed: migrations never re-run, so an error here stops the upgrade +# rather than stamping the version past a release that was not recorded. + +set -euo pipefail + +# shellcheck source=lib/cozystack-version.sh +. "$(dirname "$0")/lib/cozystack-version.sh" + +NAMESPACE="${NAMESPACE:-cozy-system}" + +credentials-migrate seed \ + --migration 70 \ + --kind Valkey \ + --format plaintext \ + --fixed-account default \ + --source-key password \ + --enabled-flag authEnabled \ + --source-suffix=-auth \ + --hold-until-rollout cozy-redis-operator/redis-operator + +# The finish Job runs the same image as this hook, so a release and its +# conversion share the credentials-migrate build. Read it from this pod's own +# container by name rather than render it from values, which the hook does not +# carry, and rather than by position, which a webhook-injected container shifts. +image=$(kubectl get pod "$(hostname)" \ + --namespace "$NAMESPACE" \ + --output 'jsonpath={.spec.containers[?(@.name=="migration")].image}') +if [ -z "$image" ]; then + echo "cannot read this pod's image to run the finish Job" >&2 + exit 1 +fi + +# Delete any Job left by an earlier run of this hook: its pod template is +# immutable, so a rerun on a newer image would fault on apply. finish recovers +# its progress from the state ConfigMap, so recreating the Job loses nothing. +# Delete the ServiceAccount with it: an earlier run may have left it owned by +# the Job just deleted, and the apply below does not touch ownerReferences, so +# without this the garbage collector could remove the re-applied ServiceAccount +# out from under the ownerReference patch. A fresh, owner-less ServiceAccount is +# never collected before the patch names the new Job. +kubectl delete job cozystack-credentials-migration-70 \ + --namespace "$NAMESPACE" \ + --ignore-not-found +kubectl delete serviceaccount cozystack-credentials-migration-70 \ + --namespace "$NAMESPACE" \ + --ignore-not-found + +kubectl apply --filename - <&2 + exit 1 +fi +kubectl patch serviceaccount cozystack-credentials-migration-70 \ + --namespace "$NAMESPACE" \ + --type merge \ + --patch "{\"metadata\":{\"ownerReferences\":[{\"apiVersion\":\"batch/v1\",\"kind\":\"Job\",\"name\":\"cozystack-credentials-migration-70\",\"uid\":\"${job_uid}\"}]}}" + +stamp_cozystack_version 71 diff --git a/packages/core/platform/images/migrations/migrations/71 b/packages/core/platform/images/migrations/migrations/71 new file mode 100755 index 000000000..b7b796d98 --- /dev/null +++ b/packages/core/platform/images/migrations/migrations/71 @@ -0,0 +1,173 @@ +#!/bin/sh +# Migration 71 --> 72 +# Convert Bucket users to platform-minted credentials. +# +# The converted bucket chart stops rendering a tenant user's BucketAccess and +# renders an engine-issued CredentialTemplate in its place; +# cozystack-controller then owns the BucketAccess and re-creates it on a mint. +# A BucketAccess's keys are bound to its UID (the COSI sidecar names the driver +# account after it), so a deleted and re-created BucketAccess is a new key +# pair. This hook runs before any component chart changes version and keeps +# every existing user's keys: +# +# - each tenant BucketAccess the bucket chart rendered gets +# helm.sh/resource-policy=keep, which Helm reads off the live object +# before it deletes a resource the new chart no longer renders, so the +# upgrade leaves it in place; and credentials.cozystack.io/adopt=true, which +# lets the controller take it over and copy the keys it already has into +# the account Secret. Clients keep working until the first mint. +# +# - the CredentialTemplate CRD baked into this image is applied first. +# The converted chart renders spec.bucketAccess, which a cluster that ran +# migration 64 in an earlier release lacks until cozystack-controller +# upgrades, possibly after the bucket releases switch: the API server +# would prune the field, and the controller would skip the template. +# +# - the backup bucket's system user is marked platform in its Bucket +# release, so it keeps its chart-rendered BucketAccess and its readable +# Secret whichever of the bucket chart and backupstrategy-controller is +# upgraded first. Its BucketAccess is not marked. +# +# - each tenant user's --credentials loses its accessKey and +# secretKey, which the tenant can read. The converted bucket-system chart +# renders that Secret without them, but its upgrade cannot remove them: +# the old chart wrote them through stringData, so they are absent from the +# manifest Helm diffs against, and a three-way merge keeps a live field +# that neither manifest names (helm v3.20 pkg/kube/client.go createPatch, +# strategicpatch.CreateThreeWayMergePatch). Done here, before the chart +# switch, the keys are gone however the release is upgraded. A platform +# user's Secret keeps them. +# +# There is no finish Job and so no standing identity: once the keys are +# stripped here, the COSI Secret the sidecar writes is the only other copy, +# and it has to stay for the grant. The keep annotation is +# left on adopted BucketAccesses: Helm no longer tracks them, and the garbage +# collector removes them with their template, which the annotation does not +# affect. +# +# Fail-closed: migrations never re-run, so an error here stops the upgrade +# rather than stamping the version past a BucketAccess that was not marked. + +set -euo pipefail + +# shellcheck source=lib/cozystack-version.sh +. "$(dirname "$0")/lib/cozystack-version.sh" +# shellcheck source=lib/credential-crd.sh +. "$(dirname "$0")/lib/credential-crd.sh" + +apply_credential_crd + +# Where backupstrategy-controller provisions the backup bucket, from its +# release values when they override the chart defaults. +BACKUP_RELEASE_NAMESPACE="${BACKUP_RELEASE_NAMESPACE:-cozy-backup-controller}" +BACKUP_RELEASE_NAME="${BACKUP_RELEASE_NAME:-backupstrategy-controller}" + +backup_value() { + kubectl get helmreleases.helm.toolkit.fluxcd.io "$BACKUP_RELEASE_NAME" \ + --namespace "$BACKUP_RELEASE_NAMESPACE" \ + --ignore-not-found \ + --output "jsonpath={.spec.values.backupStorage.$1}" +} + +platform_namespace=$(backup_value namespace) +platform_bucket=$(backup_value bucketName) +provision=$(backup_value provisionBucket) +platform_namespace="${platform_namespace:-tenant-root}" +platform_bucket="${platform_bucket:-cozy-backups}" +platform_release="bucket-${platform_bucket}" +platform_access="${platform_release}-system" + +# Only a release that has the system user: a merge patch would otherwise add +# one to a bucket that never declared it. +if [ "$provision" != "false" ]; then + system_user=$(kubectl get helmreleases.helm.toolkit.fluxcd.io "$platform_release" \ + --namespace "$platform_namespace" \ + --ignore-not-found \ + --output 'jsonpath={.spec.values.users.system}') + if [ -n "$system_user" ]; then + kubectl patch helmreleases.helm.toolkit.fluxcd.io "$platform_release" \ + --namespace "$platform_namespace" \ + --type merge \ + --patch '{"spec":{"values":{"users":{"system":{"platform":true}}}}}' + fi +fi + +# A cluster without the COSI API has no BucketAccess to keep. +crd=$(kubectl get customresourcedefinitions.apiextensions.k8s.io \ + bucketaccesses.objectstorage.k8s.io \ + --ignore-not-found \ + --output name) +if [ -z "$crd" ]; then + stamp_cozystack_version 72 + exit 0 +fi + +# One line per BucketAccessClass: name and access policy. The anonymous +# public-read access is told by its class, never by its name: with publicRead +# off a tenant user may be called public-read, and its keyed BucketAccess has +# the same name the anonymous one would. +classes=$(kubectl get bucketaccessclasses.objectstorage.k8s.io \ + --output 'jsonpath={range .items[*]}{.metadata.name}{" "}{.parameters.accessPolicy}{"\n"}{end}') + +# Whether a BucketAccess of this class is the keyless public-read access: its +# class grants the public-read policy, or, gone since, carries the -public +# suffix the SeaweedFS chart gives only that class. +public_class() { + _policy=$(printf '%s\n' "$classes" | awk -v class="$1" ' + $1 == class { found = 1; policy = $2 } + END { if (found) print (policy == "" ? "-" : policy) }') + case "$_policy" in + public-read) return 0 ;; + "") case "$1" in *-public) return 0 ;; esac ;; + esac + return 1 +} + +# One line per BucketAccess: namespace, name, the Helm release that rendered +# it, its class, and the kind of its controller, if any. +accesses=$(kubectl get bucketaccesses.objectstorage.k8s.io \ + --all-namespaces \ + --output 'jsonpath={range .items[*]}{.metadata.namespace}{" "}{.metadata.name}{" "}{.metadata.annotations.meta\.helm\.sh/release-name}{" "}{.spec.bucketAccessClassName}{" "}{.metadata.ownerReferences[?(@.controller==true)].kind}{"\n"}{end}') + +printf '%s\n' "$accesses" | while read -r namespace name release class controller; do + [ -n "$name" ] || continue + # Only what a bucket chart rendered for one of its users. + case "$release" in bucket-*) ;; *) continue ;; esac + case "$name" in "${release}"-?*) ;; *) continue ;; esac + # The anonymous public-read access has no keys and stays chart-rendered. + if public_class "$class"; then + continue + fi + # The backup bucket's system user stays a chart-rendered platform account. + if [ "$namespace" = "$platform_namespace" ] && [ "$name" = "$platform_access" ]; then + continue + fi + # Strip the keys from the tenant-readable Secret, checked without reading + # them, and patched only when one is there: a merge patch of null removes a + # key and leaves endpoint and bucketName in place. + secret="${name}-credentials" + held=$(kubectl get secrets "$secret" \ + --namespace "$namespace" \ + --ignore-not-found \ + --output 'go-template={{with .data}}{{if or (index . "accessKey") (index . "secretKey")}}held{{end}}{{end}}') + if [ -n "$held" ]; then + kubectl patch secrets "$secret" \ + --namespace "$namespace" \ + --type merge \ + --patch '{"data":{"accessKey":null,"secretKey":null}}' + echo "removed the keys from Secret $namespace/$secret" + fi + # Already taken over. + [ -z "$controller" ] || continue + kubectl annotate bucketaccesses.objectstorage.k8s.io "$name" \ + --namespace "$namespace" \ + --overwrite \ + helm.sh/resource-policy=keep + kubectl label bucketaccesses.objectstorage.k8s.io "$name" \ + --namespace "$namespace" \ + --overwrite \ + credentials.cozystack.io/adopt=true + echo "marked BucketAccess $namespace/$name for adoption" +done + +stamp_cozystack_version 72 diff --git a/packages/core/platform/images/migrations/migrations/lib/credential-crd.sh b/packages/core/platform/images/migrations/migrations/lib/credential-crd.sh new file mode 100644 index 000000000..7d4a16ef5 --- /dev/null +++ b/packages/core/platform/images/migrations/migrations/lib/credential-crd.sh @@ -0,0 +1,29 @@ +# shellcheck shell=sh +# Shared helper for applying the CredentialTemplate CRD during migrations. +# +# The CRD ships with cozystack-controller, whose release can upgrade minutes +# after the tenant releases switch charts. A converted chart that renders a +# CredentialTemplate, or a field the installed CRD does not have yet, fails +# (or has the field pruned) in between, so a conversion that needs the CRD +# applies the copy baked into the migrations image before any chart +# switches. It is labelled and annotated as owned by the cozystack-controller +# release, as that release's later upgrade expects to find it. +# +# Sourced, not executed. A migration that needs it does: +# . "$(dirname "$0")/lib/credential-crd.sh" +# apply_credential_crd + +# apply_credential_crd +# Server-side apply the baked CRD, hand it to the cozystack-controller Helm +# release, and wait until it is established. $CREDENTIAL_CRD_FILE overrides +# the path, for the tests. Every step fails the migration on error, under the +# caller's set -e. +apply_credential_crd() { + _crd_file="${CREDENTIAL_CRD_FILE:-/credential-crds/cozystack.io_credentialtemplates.yaml}" + kubectl apply --server-side --force-conflicts --filename "$_crd_file" + kubectl label crd credentialtemplates.cozystack.io app.kubernetes.io/managed-by=Helm --overwrite + kubectl annotate crd credentialtemplates.cozystack.io \ + meta.helm.sh/release-name=cozystack-controller \ + meta.helm.sh/release-namespace=cozy-system --overwrite + kubectl wait --for=condition=established crd/credentialtemplates.cozystack.io --timeout=60s +} diff --git a/packages/core/platform/values.yaml b/packages/core/platform/values.yaml index eb764c949..9126f5a5e 100644 --- a/packages/core/platform/values.yaml +++ b/packages/core/platform/values.yaml @@ -89,7 +89,7 @@ migrations: # refuses to advance past a migration file missing from the image (exit 1), so # a stale pin fails loudly rather than silently skipping the etcd adoption. image: ghcr.io/cozystack/cozystack/platform-migrations:v1.6.0@sha256:6777042e3e9c6bad76e7d96fb64baa115061975f39061cb3ede84e21d0e2213f - targetVersion: 68 + targetVersion: 72 # Adopt legacy etcd clusters onto the v1alpha2 operator WITHOUT the mandatory # pre-adoption safety snapshot (migration 50). Leave false unless migration 50 # has actually refused to proceed and you accept the risk: adoption rewires diff --git a/packages/system/backupstrategy-controller/templates/bucket.yaml b/packages/system/backupstrategy-controller/templates/bucket.yaml index 9cca0f9e8..9f8395e15 100644 --- a/packages/system/backupstrategy-controller/templates/bucket.yaml +++ b/packages/system/backupstrategy-controller/templates/bucket.yaml @@ -6,6 +6,11 @@ metadata: namespace: {{ .Values.backupStorage.namespace }} spec: users: + # A platform user: its keys stay in the bucket-system Secret this + # controller reads (backupStorage.systemSecretName), which no tenant + # role selects, and it gets no CredentialTemplate whose mint would + # rotate them under every default backup. system: readonly: false + platform: true {{- end }} diff --git a/packages/system/backupstrategy-controller/templates/strategy-redis-default.yaml b/packages/system/backupstrategy-controller/templates/strategy-redis-default.yaml index dc930f394..c969262ab 100644 --- a/packages/system/backupstrategy-controller/templates/strategy-redis-default.yaml +++ b/packages/system/backupstrategy-controller/templates/strategy-redis-default.yaml @@ -82,14 +82,15 @@ spec: {{- end }} env: {{- /* - Redis password, when the app has authEnabled (the default). The chart - emits the Secret -auth; mount it optionally so a no-auth - app still schedules. + Redis password, when the app has authEnabled (the default): the + account Secret .default.account of its default + CredentialTemplate, which a mint rewrites. Mount it optionally so a + no-auth app still schedules. */}} - name: REDIS_PASSWORD valueFrom: secretKeyRef: - name: {{ printf `{{ .Release.Prefix | default "redis-" }}{{ .Release.Name }}-auth` | quote }} + name: {{ printf `{{ .Release.Prefix | default "redis-" }}{{ .Release.Name }}.default.account` | quote }} key: password optional: true {{- /* diff --git a/packages/system/backupstrategy-controller/tests/rendering_test.yaml b/packages/system/backupstrategy-controller/tests/rendering_test.yaml index d89b4ec0d..11778559e 100644 --- a/packages/system/backupstrategy-controller/tests/rendering_test.yaml +++ b/packages/system/backupstrategy-controller/tests/rendering_test.yaml @@ -42,6 +42,14 @@ tests: path: metadata.namespace value: tenant-root template: templates/bucket.yaml + # The system user is a platform account: its keys stay in the Secret + # this controller reads, and no tenant credential can rotate them. + - equal: + path: spec.users.system + value: + readonly: false + platform: true + template: templates/bucket.yaml - hasDocuments: count: 0 template: templates/strategy-cnpg-default.yaml diff --git a/packages/system/backupstrategy-controller/tests/strategy_redis_test.yaml b/packages/system/backupstrategy-controller/tests/strategy_redis_test.yaml index 24cbe3343..fd76c481e 100644 --- a/packages/system/backupstrategy-controller/tests/strategy_redis_test.yaml +++ b/packages/system/backupstrategy-controller/tests/strategy_redis_test.yaml @@ -92,3 +92,19 @@ tests: content: name: S3_INSECURE_SKIP_VERIFY value: "true" + + - it: "reads the password from the account Secret of the app's default account" + asserts: + # The app's chart no longer renders -auth: the password lives in the + # account Secret of its default CredentialTemplate, which a mint + # rewrites, so the next backup authenticates with the new password. The + # reference stays optional so an app without authentication schedules. + - contains: + path: spec.template.spec.containers[0].env + content: + name: REDIS_PASSWORD + valueFrom: + secretKeyRef: + name: '{{ .Release.Prefix | default "redis-" }}{{ .Release.Name }}.default.account' + key: password + optional: true diff --git a/packages/system/bucket-rd/cozyrds/bucket.yaml b/packages/system/bucket-rd/cozyrds/bucket.yaml index 290141d75..720456ef9 100644 --- a/packages/system/bucket-rd/cozyrds/bucket.yaml +++ b/packages/system/bucket-rd/cozyrds/bucket.yaml @@ -8,7 +8,7 @@ spec: plural: buckets singular: bucket openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"locking":{"description":"Provisions bucket from the `-lock` BucketClass (with object lock enabled).","type":"boolean","default":false},"lockingDefaultRetention":{"description":"With `locking`, keeps the default retention of the `-lock` BucketClass (COMPLIANCE, 365 days). Set to `false` to provision from the `-lock-noretention` BucketClass instead: Object Lock is enabled with no default retention, and retention is then set on the bucket or per object through the S3 API. Read at creation only.","type":"boolean","default":true},"storagePool":{"description":"Selects a specific BucketClass by storage pool name.","type":"string","default":"","x-cozystack-options":{"source":"storagepool"}},"ui":{"description":"Deploys the web UI (s3manager) with its Service and its Ingress or HTTPRoute at `.`. Set to `false` to run the bucket without them.","type":"boolean","default":true},"publicRead":{"description":"Serves the bucket's objects to anyone without credentials at `//`. Anonymous callers can read objects but cannot list the bucket or write to it.","type":"boolean","default":false},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"readonly":{"description":"Whether the user has read-only access.","type":"boolean"}}}},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63}}} + {"title":"Chart Values","type":"object","properties":{"locking":{"description":"Provisions bucket from the `-lock` BucketClass (with object lock enabled).","type":"boolean","default":false},"lockingDefaultRetention":{"description":"With `locking`, keeps the default retention of the `-lock` BucketClass (COMPLIANCE, 365 days). Set to `false` to provision from the `-lock-noretention` BucketClass instead: Object Lock is enabled with no default retention, and retention is then set on the bucket or per object through the S3 API. Read at creation only.","type":"boolean","default":true},"storagePool":{"description":"Selects a specific BucketClass by storage pool name.","type":"string","default":"","x-cozystack-options":{"source":"storagepool"}},"ui":{"description":"Deploys the web UI (s3manager) with its Service and its Ingress or HTTPRoute at `.`. Set to `false` to run the bucket without them.","type":"boolean","default":true},"publicRead":{"description":"Serves the bucket's objects to anyone without credentials at `//`. Anonymous callers can read objects but cannot list the bucket or write to it.","type":"boolean","default":false},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"platform":{"description":"Marks a platform account, such as the `system` user of the backup bucket, which backupstrategy-controller sets. Its keys stay in the `--credentials` Secret, which no tenant can read, and are never minted. Clearing it drops the chart-rendered BucketAccess, which revokes those keys, and the user becomes a normal account whose keys are minted through its Credential. Leave it unset for your own users.","type":"boolean"},"readonly":{"description":"Whether the user has read-only access.","type":"boolean"}}}},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63}}} release: prefix: bucket- labels: diff --git a/packages/system/bucket/templates/user-credentials.yaml b/packages/system/bucket/templates/user-credentials.yaml index a45320254..30acc89db 100644 --- a/packages/system/bucket/templates/user-credentials.yaml +++ b/packages/system/bucket/templates/user-credentials.yaml @@ -36,23 +36,46 @@ to every bucket needs a controller that owns them and is tracked separately. */}} +{{- /* + What the Secret holds depends on who consumes the user. A tenant user's keys + live in the account Secret of its CredentialTemplate and are shown only by a + mint, so its Secret here carries the endpoint and bucket name, which are not + secret. A platform user (users..platform) has no template: its Secret + keeps the keys for the platform component that reads it, and is labelled so + the tenant Secret view and the dashboard leave it out. +*/}} {{- range $name, $user := .Values.users }} {{- $secretName := printf "%s-%s" $.Values.bucketName $name }} {{- $existingSecret := lookup "v1" "Secret" $.Release.Namespace $secretName }} {{- if $existingSecret }} {{- $bucketInfo := fromJson (b64dec (index $existingSecret.data "BucketInfo")) }} +{{- $platform := default false $user.platform }} --- apiVersion: v1 kind: Secret metadata: name: {{ $secretName }}-credentials labels: + {{- if $platform }} + internal.cozystack.io/tenantresource: "false" + {{- else }} apps.cozystack.io/user-secret: "true" + {{- end }} type: Opaque -stringData: - accessKey: {{ index $bucketInfo.spec.secretS3 "accessKeyID" | quote }} - secretKey: {{ index $bucketInfo.spec.secretS3 "accessSecretKey" | quote }} - endpoint: {{ index $bucketInfo.spec.secretS3 "endpoint" | trimPrefix "https://" | trimPrefix "http://" | quote }} - bucketName: {{ index $bucketInfo.spec "bucketName" | quote }} +{{- /* + data rather than stringData: Helm's three-way merge removes a live key only + when the previous manifest named it, and a stringData key never appears in + data, so a key dropped from stringData stays in the Secret. Rendered as + data, a key this chart stops emitting is removed on the upgrade that drops + it. The keys the stringData chart left on tenant users are stripped by + platform migration 71. +*/}} +data: + {{- if $platform }} + accessKey: {{ index $bucketInfo.spec.secretS3 "accessKeyID" | b64enc | quote }} + secretKey: {{ index $bucketInfo.spec.secretS3 "accessSecretKey" | b64enc | quote }} + {{- end }} + endpoint: {{ index $bucketInfo.spec.secretS3 "endpoint" | trimPrefix "https://" | trimPrefix "http://" | b64enc | quote }} + bucketName: {{ index $bucketInfo.spec "bucketName" | b64enc | quote }} {{- end }} {{- end }} diff --git a/packages/system/bucket/tests/user_credentials_test.yaml b/packages/system/bucket/tests/user_credentials_test.yaml index c0c4a1634..a59124275 100644 --- a/packages/system/bucket/tests/user_credentials_test.yaml +++ b/packages/system/bucket/tests/user_credentials_test.yaml @@ -78,3 +78,77 @@ tests: - equal: path: metadata.name value: bucket-cozy-backups-ui + + # With the COSI Secrets present (kubernetesProvider), what the per-user + # Secret holds depends on who consumes the user: a tenant user's keys live + # in its account Secret and are shown only by a mint, a platform user keeps + # them here, hidden from tenants. + - it: "a tenant user's Secret carries the endpoint and bucket name, no keys" + templates: + - templates/user-credentials.yaml + set: + <<: *base + users: + web: {} + kubernetesProvider: &cosiSecrets + scheme: + "v1/Secret": + gvr: + version: "v1" + resource: "secrets" + namespaced: true + objects: + - kind: Secret + apiVersion: v1 + metadata: + name: bucket-cozy-backups-web + namespace: tenant-root + data: + BucketInfo: eyJtZXRhZGF0YSI6eyJuYW1lIjoiYmMtdWlkIn0sInNwZWMiOnsiYnVja2V0TmFtZSI6ImJ1Y2tldC1jbGFpbS11aWQiLCJzZWNyZXRTMyI6eyJlbmRwb2ludCI6Imh0dHBzOi8vczMuZXhhbXBsZS5vcmciLCJhY2Nlc3NLZXlJRCI6IkFLSUFURVNUIiwiYWNjZXNzU2VjcmV0S2V5IjoidGVzdC1zZWNyZXQifX19 + - kind: Secret + apiVersion: v1 + metadata: + name: bucket-cozy-backups-system + namespace: tenant-root + data: + BucketInfo: eyJtZXRhZGF0YSI6eyJuYW1lIjoiYmMtdWlkIn0sInNwZWMiOnsiYnVja2V0TmFtZSI6ImJ1Y2tldC1jbGFpbS11aWQiLCJzZWNyZXRTMyI6eyJlbmRwb2ludCI6Imh0dHBzOi8vczMuZXhhbXBsZS5vcmciLCJhY2Nlc3NLZXlJRCI6IkFLSUFURVNUIiwiYWNjZXNzU2VjcmV0S2V5IjoidGVzdC1zZWNyZXQifX19 + asserts: + - hasDocuments: + count: 1 + - equal: + path: metadata.labels + value: + apps.cozystack.io/user-secret: "true" + - equal: + path: data + value: + endpoint: czMuZXhhbXBsZS5vcmc= + bucketName: YnVja2V0LWNsYWltLXVpZA== + # Rendered as data, so a key the chart stops emitting is removed by + # Helm's three-way merge on the upgrade that drops it. + - notExists: + path: stringData + + - it: "a platform user's Secret keeps the keys and is hidden from tenants" + templates: + - templates/user-credentials.yaml + set: + <<: *base + users: + system: + platform: true + kubernetesProvider: *cosiSecrets + asserts: + - hasDocuments: + count: 1 + - equal: + path: metadata.labels + value: + internal.cozystack.io/tenantresource: "false" + - equal: + path: data + value: + accessKey: QUtJQVRFU1Q= + secretKey: dGVzdC1zZWNyZXQ= + endpoint: czMuZXhhbXBsZS5vcmc= + bucketName: YnVja2V0LWNsYWltLXVpZA== diff --git a/packages/system/cozystack-controller/definitions/cozystack.io_credentialtemplates.yaml b/packages/system/cozystack-controller/definitions/cozystack.io_credentialtemplates.yaml index b56c24c73..e662b8fbf 100644 --- a/packages/system/cozystack-controller/definitions/cozystack.io_credentialtemplates.yaml +++ b/packages/system/cozystack-controller/definitions/cozystack.io_credentialtemplates.yaml @@ -59,6 +59,37 @@ spec: Secret that stores its password. A kind's chart renders one per account; a tenant cannot write it. properties: + bucketAccess: + description: |- + BucketAccess makes the account engine-issued: it names the BucketAccess + whose COSI grant issues the account's keys, which the platform cannot + choose. cozystack-controller creates and owns it, re-creates it on a + mint, and deletes it on a revoke. The keys are stored as they are + issued, so the format is plaintext. + properties: + bucketAccessClassName: + description: BucketAccessClassName is the class that sets the + access policy. + minLength: 1 + type: string + bucketClaimName: + description: BucketClaimName is the BucketClaim the access is + granted on. + minLength: 1 + type: string + name: + description: Name of the BucketAccess and of the Secret the COSI + sidecar writes. + minLength: 1 + type: string + required: + - bucketAccessClassName + - bucketClaimName + - name + type: object + x-kubernetes-validations: + - message: bucketAccess.name is immutable + rule: self.name == oldSelf.name format: description: Format is how a password is stored in the account Secret. properties: @@ -106,6 +137,10 @@ spec: - format - username type: object + x-kubernetes-validations: + - message: a template with bucketAccess stores its keys in the plaintext + format + rule: '!has(self.bucketAccess) || self.format.name == ''plaintext''' status: description: |- CredentialTemplateStatus mirrors the record the account Secret keeps, so the diff --git a/packages/system/cozystack-controller/templates/rbac.yaml b/packages/system/cozystack-controller/templates/rbac.yaml index a9f7b646d..8502b32d8 100644 --- a/packages/system/cozystack-controller/templates/rbac.yaml +++ b/packages/system/cozystack-controller/templates/rbac.yaml @@ -64,6 +64,19 @@ rules: # writes their Ready status. It never creates or deletes a sentinel; that is # the chart's (helm-controller's) job. No tenant role grants any verb on # internal.cozystack.io, which is what keeps sentinels out of tenant reach. +# COSICredentialReconciler creates the BucketAccess an engine-issued +# CredentialTemplate names, adopts one the conversion marked, and deletes it on +# a mint or a revoke, which makes the COSI sidecar revoke the old keys, +# re-creating it for a mint. No tenant role grants any verb on +# objectstorage.k8s.io. +- apiGroups: ["objectstorage.k8s.io"] + resources: ["bucketaccesses"] + verbs: ["get", "list", "watch", "create", "update", "delete"] +# It reads the class and the claim of a BucketAccess the sidecar has not +# finalized, to tell whether a deleted template can release it at once. +- apiGroups: ["objectstorage.k8s.io"] + resources: ["bucketaccessclasses", "bucketclaims"] + verbs: ["get"] - apiGroups: ["internal.cozystack.io"] resources: ["tenantprojections"] verbs: ["get", "list", "watch"] diff --git a/packages/system/cozystack-controller/tests/rbac_test.yaml b/packages/system/cozystack-controller/tests/rbac_test.yaml index 891e28870..7ac9f6277 100644 --- a/packages/system/cozystack-controller/tests/rbac_test.yaml +++ b/packages/system/cozystack-controller/tests/rbac_test.yaml @@ -36,3 +36,20 @@ tests: apiGroups: [""] resources: ["secrets"] verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + - it: lets the COSI credentials reconciler re-create BucketAccesses + documentSelector: + path: kind + value: ClusterRole + asserts: + - contains: + path: rules + content: + apiGroups: ["objectstorage.k8s.io"] + resources: ["bucketaccesses"] + verbs: ["get", "list", "watch", "create", "update", "delete"] + - contains: + path: rules + content: + apiGroups: ["objectstorage.k8s.io"] + resources: ["bucketaccessclasses", "bucketclaims"] + verbs: ["get"] diff --git a/packages/system/rabbitmq-rd/cozyrds/rabbitmq.yaml b/packages/system/rabbitmq-rd/cozyrds/rabbitmq.yaml index ec3a3880c..f731dbc84 100644 --- a/packages/system/rabbitmq-rd/cozyrds/rabbitmq.yaml +++ b/packages/system/rabbitmq-rd/cozyrds/rabbitmq.yaml @@ -8,7 +8,7 @@ spec: plural: rabbitmqs singular: rabbitmq openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of RabbitMQ replicas.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each RabbitMQ replica. Every resource left unset here is taken from `resourcesPreset`.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset. It supplies every resource `resources` does not set, not only a `resources` left empty entirely.","type":"string","default":"s1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"affinity":{"description":"Pod affinity applied to RabbitMQ pods (standard Kubernetes corev1.Affinity). Use podAntiAffinity with topologyKey `kubernetes.io/hostname` to spread RabbitMQ pods across nodes.","type":"object","default":{},"x-kubernetes-preserve-unknown-fields":true},"tls":{"description":"TLS configuration. TLS is off unless `tls.enabled` is set to true.","type":"object","default":{},"properties":{"disableNonTLSListeners":{"description":"Close the plaintext AMQP (5672) and management (15672) listeners. This is a broker-level switch: it drops in-cluster clients as well as external ones, and it cannot be combined with `users` or `vhosts`. Erlang distribution (25672) and epmd (4369) stay plaintext regardless. Defaults to false.","type":"boolean"},"enabled":{"description":"Enable TLS for AMQPS (5671) and Management HTTPS (15671). Applies whether or not `external` is set. Plaintext AMQP (5672) and management (15672) keep serving unless `disableNonTLSListeners` is set as well. Moves the `port` key of the `-default-user` Secret from 5672 to 5671, and the metrics port from 15692 to 15691. Defaults to false.","type":"boolean"}}},"version":{"description":"RabbitMQ major.minor version to deploy","type":"string","default":"v4.2","enum":["v4.2","v4.1","v4.0","v3.13"]},"users":{"description":"Users configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","properties":{"password":{"description":"Password for the user.","type":"string"}}}},"vhosts":{"description":"Virtual hosts configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","required":["roles"],"properties":{"roles":{"description":"Virtual host roles list.","type":"object","properties":{"admin":{"description":"List of admin users.","type":"array","items":{"type":"string"}},"readonly":{"description":"List of readonly users.","type":"array","items":{"type":"string"}}}}}}},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of RabbitMQ replicas.","type":"integer","default":3},"resources":{"description":"Explicit CPU and memory configuration for each RabbitMQ replica. Every resource left unset here is taken from `resourcesPreset`.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset. It supplies every resource `resources` does not set, not only a `resources` left empty entirely.","type":"string","default":"s1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"10Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"affinity":{"description":"Pod affinity applied to RabbitMQ pods (standard Kubernetes corev1.Affinity). Use podAntiAffinity with topologyKey `kubernetes.io/hostname` to spread RabbitMQ pods across nodes.","type":"object","default":{},"x-kubernetes-preserve-unknown-fields":true},"tls":{"description":"TLS configuration. TLS is off unless `tls.enabled` is set to true.","type":"object","default":{},"properties":{"disableNonTLSListeners":{"description":"Close the plaintext AMQP (5672) and management (15672) listeners. This is a broker-level switch: it drops in-cluster clients as well as external ones, and it cannot be combined with `users` or `vhosts`. Erlang distribution (25672) and epmd (4369) stay plaintext regardless. Defaults to false.","type":"boolean"},"enabled":{"description":"Enable TLS for AMQPS (5671) and Management HTTPS (15671). Applies whether or not `external` is set. Plaintext AMQP (5672) and management (15672) keep serving unless `disableNonTLSListeners` is set as well. Moves the `port` key of the `-default-user` Secret from 5672 to 5671, and the metrics port from 15692 to 15691. Defaults to false.","type":"boolean"}}},"version":{"description":"RabbitMQ major.minor version to deploy","type":"string","default":"v4.2","enum":["v4.2","v4.1","v4.0","v3.13"]},"users":{"description":"Users configuration map. Each user is a RabbitMQ user that messaging-topology-operator keeps from an account Secret the platform holds. Passwords are issued through the Cozystack credentials API: a mint on the account's `Credential` (`core.cozystack.io`) returns a new password once, and a revoke retires the password without issuing one. The operator applies either to the broker within seconds. A `password` key here is ignored. The administrator in `-default-user` belongs to the platform and is not shown to tenants.","type":"object","default":{},"additionalProperties":{"type":"object"}},"vhosts":{"description":"Virtual hosts configuration map.","type":"object","default":{},"additionalProperties":{"type":"object","required":["roles"],"properties":{"roles":{"description":"Virtual host roles list.","type":"object","properties":{"admin":{"description":"List of admin users.","type":"array","items":{"type":"string"}},"readonly":{"description":"List of readonly users.","type":"array","items":{"type":"string"}}}}}}},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63}}} release: prefix: rabbitmq- labels: @@ -40,16 +40,19 @@ spec: # Bounded, not absolute: matching is exact-name with no globs, so a Secret a # future operator version introduces stays in scope of the label-only # include. The primary defence is the lineage webhook stamping only what it - # can attribute; this closes the enumerable set. -default-user is excluded - # from the exclusion on purpose — it is included by name below. + # can attribute; this closes the enumerable set. + # + # -default-user holds the administrator messaging-topology-operator logs + # in with, a platform account no tenant reads. The tenant accounts live in + # account Secrets that no definition selects: the credentials API shows a + # password once, in the response of the mint that issued it. exclude: - resourceNames: - rabbitmq-{{ .name }}-ca - rabbitmq-{{ .name }}-tls - rabbitmq-{{ .name }}-erlang-cookie - include: - - resourceNames: - rabbitmq-{{ .name }}-default-user + include: # The key-free trust anchor the CA-extraction controller publishes. The # chart names its own CA Secret in a TenantProjection sentinel, and the # controller stamps this label on the projection it writes from that @@ -58,8 +61,6 @@ spec: # engine shares; it carries no per-release name templating. - matchLabels: internal.cozystack.io/tenant-ca: "true" - - matchLabels: - apps.cozystack.io/user-secret: "true" services: exclude: [] include: diff --git a/packages/system/redis-operator/images/redis-operator/patches/zz-password-rotation.diff b/packages/system/redis-operator/images/redis-operator/patches/zz-password-rotation.diff new file mode 100644 index 000000000..608824e3b --- /dev/null +++ b/packages/system/redis-operator/images/redis-operator/patches/zz-password-rotation.diff @@ -0,0 +1,4592 @@ +# Downstream: keep the client password out of everything the operator runs, +# so a changed auth Secret is applied live with no pod restart and no +# failover. See operator/redisfailover/service/password.go. +# +# Replication, the Sentinels, the probes and the shutdown hook authenticate +# as an internal ACL user that may run only the commands they send, reads no +# key and no configuration parameter, and uses no channel but the Sentinels' +# hello channel. The exporter authenticates as a user of its own, the only +# operator user that may run CONFIG GET. Their passwords are in their own +# Secret (rfr--internal): a pod password, read by the probes at start, +# and an exporter password, both never rotated and never on a server but as +# a hash; and a link password, which masterauth and the Sentinels' +# auth-pass carry. The auth Secret's password is the default user's alone. +# A change to it is one MULTI/EXEC per running server that resets the +# operator's users, deletes any other user, sets requirepass, and kills +# every connection of the default and exporter users, so no connection +# that authenticated with the old password, or with anything its holder +# set, can read the new one; every mint and revoke disconnects the tenant's +# clients. Holders of the old password can read masterauth, so the link +# password is then rotated in stages that keep the old one valid until no +# server, replica or Sentinel uses it, and ends by disconnecting every +# MONITOR and every connection of an operator user from an address that is +# no pod of the RedisFailover and not loopback, so a replication stream or +# MONITOR opened before the change does not outlive it; the ConfigMap +# records the new client password only once all of it is done. A RedisFailover from before this patch +# gets the users live on every server and Sentinel before its ConfigMap and +# pod template switch to them, which rolls the pods once. After that every +# pass re-asserts the users, masteruser/masterauth and the Sentinels' +# auth-user/auth-pass, since the tenant's default user can change them, and +# a guard checks the internal user on every server every 2 s from memory, +# so a tenant's ACL DELUSER is undone before the Sentinels fail the master +# over. Every rotation and every guard run also deletes any ACL user but +# default, rf-internal, rf-exporter and pinger: one the tenant created would +# outlive a revoke, and with no aclfile none survives a restart anyway. +# +# The pod roll also moves the master role off a stale master with SENTINEL +# FAILOVER and relabels the pods before rolling it as a replica, instead of +# deleting the master and waiting for the Sentinels to notice, and ends that +# pass right after, so nothing heals towards the master it read before. Two +# masters are settled on the one a quorum of Sentinels names. +# +# Requires Redis or Valkey 7 or newer (CONFIG SET of several parameters, +# ACL subcommand rules). +# It builds on tls.diff (tlsConfig arguments) and unauthenticated-sentinel.diff +# (SetSentinelAuthPass); the Dockerfile applies /patches/*.diff in glob order, +# which the zz- prefix keeps it last in. +# +diff --git a/mocks/operator/redisfailover/service/RedisFailoverHeal.go b/mocks/operator/redisfailover/service/RedisFailoverHeal.go +index c54b847..28e9c3c 100644 +--- a/mocks/operator/redisfailover/service/RedisFailoverHeal.go ++++ b/mocks/operator/redisfailover/service/RedisFailoverHeal.go +@@ -6,6 +6,8 @@ import ( + mock "github.com/stretchr/testify/mock" + + v1 "github.com/freshworks/redis-operator/api/redisfailover/v1" ++ ++ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ) + + // RedisFailoverHeal is an autogenerated mock type for the RedisFailoverHeal type +@@ -121,6 +123,60 @@ func (_m *RedisFailoverHeal) SetExternalMasterOnAll(masterIP string, masterPort + return r0 + } + ++// ReconcileRedisAuth provides a mock function with given fields: rFailover, labels, ownerRefs ++func (_m *RedisFailoverHeal) ReconcileRedisAuth(rFailover *v1.RedisFailover, labels map[string]string, ownerRefs []metav1.OwnerReference) error { ++ ret := _m.Called(rFailover, labels, ownerRefs) ++ ++ if len(ret) == 0 { ++ panic("no return value specified for ReconcileRedisAuth") ++ } ++ ++ var r0 error ++ if rf, ok := ret.Get(0).(func(*v1.RedisFailover, map[string]string, []metav1.OwnerReference) error); ok { ++ r0 = rf(rFailover, labels, ownerRefs) ++ } else { ++ r0 = ret.Error(0) ++ } ++ ++ return r0 ++} ++ ++// FailoverMaster provides a mock function with given fields: rFailover ++func (_m *RedisFailoverHeal) FailoverMaster(rFailover *v1.RedisFailover) error { ++ ret := _m.Called(rFailover) ++ ++ if len(ret) == 0 { ++ panic("no return value specified for FailoverMaster") ++ } ++ ++ var r0 error ++ if rf, ok := ret.Get(0).(func(*v1.RedisFailover) error); ok { ++ r0 = rf(rFailover) ++ } else { ++ r0 = ret.Error(0) ++ } ++ ++ return r0 ++} ++ ++// ResolveMultipleMasters provides a mock function with given fields: rFailover ++func (_m *RedisFailoverHeal) ResolveMultipleMasters(rFailover *v1.RedisFailover) error { ++ ret := _m.Called(rFailover) ++ ++ if len(ret) == 0 { ++ panic("no return value specified for ResolveMultipleMasters") ++ } ++ ++ var r0 error ++ if rf, ok := ret.Get(0).(func(*v1.RedisFailover) error); ok { ++ r0 = rf(rFailover) ++ } else { ++ r0 = ret.Error(0) ++ } ++ ++ return r0 ++} ++ + // SetMasterOnAll provides a mock function with given fields: masterIP, rFailover + func (_m *RedisFailoverHeal) SetMasterOnAll(masterIP string, rFailover *v1.RedisFailover) error { + ret := _m.Called(masterIP, rFailover) +diff --git a/mocks/service/redis/Client.go b/mocks/service/redis/Client.go +index dfb27c7..9190d87 100644 +--- a/mocks/service/redis/Client.go ++++ b/mocks/service/redis/Client.go +@@ -6,6 +6,8 @@ import ( + mock "github.com/stretchr/testify/mock" + + tls "crypto/tls" ++ ++ redis "github.com/freshworks/redis-operator/service/redis" + ) + + // Client is an autogenerated mock type for the Client type +@@ -322,6 +324,223 @@ func (_m *Client) SetCustomSentinelConfig(ip string, masterName string, configs + return r0 + } + ++// GetUserACL provides a mock function with given fields: ip, port, auth, user, tlsConfig ++func (_m *Client) GetUserACL(ip string, port string, auth string, user string, tlsConfig *tls.Config) (redis.UserACL, error) { ++ ret := _m.Called(ip, port, auth, user, tlsConfig) ++ ++ if len(ret) == 0 { ++ panic("no return value specified for GetUserACL") ++ } ++ ++ if rf, ok := ret.Get(0).(func(string, string, string, string, *tls.Config) (redis.UserACL, error)); ok { ++ return rf(ip, port, auth, user, tlsConfig) ++ } ++ var r0 redis.UserACL ++ if v, ok := ret.Get(0).(redis.UserACL); ok { ++ r0 = v ++ } ++ return r0, ret.Error(1) ++} ++ ++// GetMasterAuth provides a mock function with given fields: ip, port, auth, tlsConfig ++func (_m *Client) GetMasterAuth(ip string, port string, auth string, tlsConfig *tls.Config) (string, string, error) { ++ ret := _m.Called(ip, port, auth, tlsConfig) ++ ++ if len(ret) == 0 { ++ panic("no return value specified for GetMasterAuth") ++ } ++ ++ return ret.String(0), ret.String(1), ret.Error(2) ++} ++ ++// GetClientUsers provides a mock function with given fields: ip, port, auth, tlsConfig ++func (_m *Client) GetClientUsers(ip string, port string, auth string, tlsConfig *tls.Config) (map[string][]string, error) { ++ ret := _m.Called(ip, port, auth, tlsConfig) ++ ++ if len(ret) == 0 { ++ panic("no return value specified for GetClientUsers") ++ } ++ ++ var r0 map[string][]string ++ if v, ok := ret.Get(0).(map[string][]string); ok { ++ r0 = v ++ } ++ return r0, ret.Error(1) ++} ++ ++// GetDefaultUserPasswords provides a mock function with given fields: ip, port, password, tlsConfig ++func (_m *Client) GetDefaultUserPasswords(ip string, port string, password string, tlsConfig *tls.Config) (redis.DefaultUserPasswords, error) { ++ ret := _m.Called(ip, port, password, tlsConfig) ++ ++ if len(ret) == 0 { ++ panic("no return value specified for GetDefaultUserPasswords") ++ } ++ ++ var r0 redis.DefaultUserPasswords ++ var r1 error ++ if rf, ok := ret.Get(0).(func(string, string, string, *tls.Config) (redis.DefaultUserPasswords, error)); ok { ++ return rf(ip, port, password, tlsConfig) ++ } ++ if v, ok := ret.Get(0).(redis.DefaultUserPasswords); ok { ++ r0 = v ++ } ++ r1 = ret.Error(1) ++ ++ return r0, r1 ++} ++ ++// ListUsers provides a mock function with given fields: ip, port, auth, tlsConfig ++func (_m *Client) ListUsers(ip string, port string, auth string, tlsConfig *tls.Config) ([]string, error) { ++ ret := _m.Called(ip, port, auth, tlsConfig) ++ ++ if len(ret) == 0 { ++ panic("no return value specified for ListUsers") ++ } ++ ++ if rf, ok := ret.Get(0).(func(string, string, string, *tls.Config) ([]string, error)); ok { ++ return rf(ip, port, auth, tlsConfig) ++ } ++ var r0 []string ++ if v, ok := ret.Get(0).([]string); ok { ++ r0 = v ++ } ++ return r0, ret.Error(1) ++} ++ ++// ChangeClientPassword provides a mock function with given fields: ip, port, auth, password, reset, deleteUsers, killUsers, tlsConfig ++func (_m *Client) ChangeClientPassword(ip string, port string, auth string, password string, reset []redis.ACLUser, deleteUsers []string, killUsers []string, tlsConfig *tls.Config) error { ++ ret := _m.Called(ip, port, auth, password, reset, deleteUsers, killUsers, tlsConfig) ++ ++ if len(ret) == 0 { ++ panic("no return value specified for ChangeClientPassword") ++ } ++ ++ if rf, ok := ret.Get(0).(func(string, string, string, string, []redis.ACLUser, []string, []string, *tls.Config) error); ok { ++ return rf(ip, port, auth, password, reset, deleteUsers, killUsers, tlsConfig) ++ } ++ return ret.Error(0) ++} ++ ++// ListClients provides a mock function with given fields: ip, port, auth, tlsConfig ++func (_m *Client) ListClients(ip string, port string, auth string, tlsConfig *tls.Config) ([]redis.ClientInfo, error) { ++ ret := _m.Called(ip, port, auth, tlsConfig) ++ ++ if len(ret) == 0 { ++ panic("no return value specified for ListClients") ++ } ++ ++ var r0 []redis.ClientInfo ++ var r1 error ++ if rf, ok := ret.Get(0).(func(string, string, string, *tls.Config) ([]redis.ClientInfo, error)); ok { ++ return rf(ip, port, auth, tlsConfig) ++ } ++ if ret.Get(0) != nil { ++ r0 = ret.Get(0).([]redis.ClientInfo) ++ } ++ r1 = ret.Error(1) ++ return r0, r1 ++} ++ ++// KillClients provides a mock function with given fields: ip, port, auth, ids, tlsConfig ++func (_m *Client) KillClients(ip string, port string, auth string, ids []string, tlsConfig *tls.Config) error { ++ ret := _m.Called(ip, port, auth, ids, tlsConfig) ++ ++ if len(ret) == 0 { ++ panic("no return value specified for KillClients") ++ } ++ ++ if rf, ok := ret.Get(0).(func(string, string, string, []string, *tls.Config) error); ok { ++ return rf(ip, port, auth, ids, tlsConfig) ++ } ++ return ret.Error(0) ++} ++ ++// DeleteUsers provides a mock function with given fields: ip, port, auth, users, tlsConfig ++func (_m *Client) DeleteUsers(ip string, port string, auth string, users []string, tlsConfig *tls.Config) error { ++ ret := _m.Called(ip, port, auth, users, tlsConfig) ++ ++ if len(ret) == 0 { ++ panic("no return value specified for DeleteUsers") ++ } ++ ++ if rf, ok := ret.Get(0).(func(string, string, string, []string, *tls.Config) error); ok { ++ return rf(ip, port, auth, users, tlsConfig) ++ } ++ return ret.Error(0) ++} ++ ++// SetUserACL provides a mock function with given fields: ip, port, auth, user, rules, tlsConfig ++func (_m *Client) SetUserACL(ip string, port string, auth string, user string, rules []string, tlsConfig *tls.Config) error { ++ ret := _m.Called(ip, port, auth, user, rules, tlsConfig) ++ ++ if len(ret) == 0 { ++ panic("no return value specified for SetUserACL") ++ } ++ ++ var r0 error ++ if rf, ok := ret.Get(0).(func(string, string, string, string, []string, *tls.Config) error); ok { ++ r0 = rf(ip, port, auth, user, rules, tlsConfig) ++ } else { ++ r0 = ret.Error(0) ++ } ++ ++ return r0 ++} ++ ++// SetMasterAuth provides a mock function with given fields: ip, port, auth, user, password, tlsConfig ++func (_m *Client) SetMasterAuth(ip string, port string, auth string, user string, password string, tlsConfig *tls.Config) error { ++ ret := _m.Called(ip, port, auth, user, password, tlsConfig) ++ ++ if len(ret) == 0 { ++ panic("no return value specified for SetMasterAuth") ++ } ++ ++ var r0 error ++ if rf, ok := ret.Get(0).(func(string, string, string, string, string, *tls.Config) error); ok { ++ r0 = rf(ip, port, auth, user, password, tlsConfig) ++ } else { ++ r0 = ret.Error(0) ++ } ++ ++ return r0 ++} ++ ++// SetSentinelAuth provides a mock function with given fields: ip, masterName, user, password, tlsConfig ++func (_m *Client) SetSentinelAuth(ip string, masterName string, user string, password string, tlsConfig *tls.Config) error { ++ ret := _m.Called(ip, masterName, user, password, tlsConfig) ++ ++ if len(ret) == 0 { ++ panic("no return value specified for SetSentinelAuth") ++ } ++ ++ var r0 error ++ if rf, ok := ret.Get(0).(func(string, string, string, string, *tls.Config) error); ok { ++ r0 = rf(ip, masterName, user, password, tlsConfig) ++ } else { ++ r0 = ret.Error(0) ++ } ++ ++ return r0 ++} ++ ++// SentinelFailover provides a mock function with given fields: ip, masterName, tlsConfig ++func (_m *Client) SentinelFailover(ip string, masterName string, tlsConfig *tls.Config) error { ++ ret := _m.Called(ip, masterName, tlsConfig) ++ ++ if len(ret) == 0 { ++ panic("no return value specified for SentinelFailover") ++ } ++ ++ var r0 error ++ if rf, ok := ret.Get(0).(func(string, string, *tls.Config) error); ok { ++ r0 = rf(ip, masterName, tlsConfig) ++ } else { ++ r0 = ret.Error(0) ++ } ++ ++ return r0 ++} ++ + // SetSentinelAuthPass provides a mock function with given fields: ip, masterName, password, tlsConfig + func (_m *Client) SetSentinelAuthPass(ip string, masterName string, password string, tlsConfig *tls.Config) error { + ret := _m.Called(ip, masterName, password, tlsConfig) +diff --git a/operator/redisfailover/checker.go b/operator/redisfailover/checker.go +index 261247b..4cdb318 100644 +--- a/operator/redisfailover/checker.go ++++ b/operator/redisfailover/checker.go +@@ -2,11 +2,13 @@ package redisfailover + + import ( + "errors" ++ "fmt" + "strconv" + "time" + + redisfailoverv1 "github.com/freshworks/redis-operator/api/redisfailover/v1" + "github.com/freshworks/redis-operator/metrics" ++ rfservice "github.com/freshworks/redis-operator/operator/redisfailover/service" + ) + + // UpdateRedisesPods deletes Redis pods with a stale StatefulSet revision (OnDelete rollout). +@@ -71,6 +73,16 @@ func (r *RedisFailoverHandler) UpdateRedisesPods(rf *redisfailoverv1.RedisFailov + return err + } + if masterRevision != ssUR { ++ // Deleting the master leaves writes failing until the Sentinels ++ // detect it and the master label follows. With a replica to take ++ // over, move the role first: the old master is then rolled as a ++ // replica on a later pass. ++ if rf.SentinelsAllowed() && rf.Spec.Redis.Replicas > 1 { ++ if err := r.rfHealer.FailoverMaster(rf); err != nil { ++ return err ++ } ++ return rfservice.ErrMasterMoved ++ } + err = r.rfHealer.DeletePod(master, rf) + if err != nil { + return err +@@ -183,6 +195,15 @@ func (r *RedisFailoverHandler) CheckAndHeal(rf *redisfailoverv1.RedisFailover) e + setRedisCheckerMetrics(r.mClient, "redis", rf.Namespace, rf.Name, metrics.NUMBER_OF_MASTERS, metrics.NOT_APPLICABLE, nil) + default: + setRedisCheckerMetrics(r.mClient, "redis", rf.Namespace, rf.Name, metrics.NUMBER_OF_MASTERS, metrics.NOT_APPLICABLE, errors.New("multiple masters detected")) ++ // When a quorum of Sentinels names one of the masters, that one is the ++ // master clients are sent to: make the others its replicas. Without ++ // such a quorum there is no safe choice to make here. ++ if rf.SentinelsAllowed() { ++ if err := r.rfHealer.ResolveMultipleMasters(rf); err != nil { ++ return fmt.Errorf("more than one master, and the Sentinels do not settle it (%v): fix manually", err) ++ } ++ return nil ++ } + return errors.New("more than one master, fix manually") + } + +@@ -207,6 +228,12 @@ func (r *RedisFailoverHandler) CheckAndHeal(rf *redisfailoverv1.RedisFailover) e + } + + err = r.UpdateRedisesPods(rf) ++ if errors.Is(err, rfservice.ErrMasterMoved) { ++ // master, read at the top of this pass, is no longer the master: the ++ // Sentinel checks below would point the Sentinels back at it and ++ // leave two masters. The next pass starts from the new one. ++ return nil ++ } + if err != nil { + return err + } +diff --git a/operator/redisfailover/checker_test.go b/operator/redisfailover/checker_test.go +index 35b2e56..01d613a 100644 +--- a/operator/redisfailover/checker_test.go ++++ b/operator/redisfailover/checker_test.go +@@ -17,6 +17,7 @@ import ( + mRFService "github.com/freshworks/redis-operator/mocks/operator/redisfailover/service" + mK8SService "github.com/freshworks/redis-operator/mocks/service/k8s" + rfOperator "github.com/freshworks/redis-operator/operator/redisfailover" ++ rfservice "github.com/freshworks/redis-operator/operator/redisfailover/service" + ) + + func TestCheckAndHeal(t *testing.T) { +@@ -607,7 +608,9 @@ func TestCheckAndHeal(t *testing.T) { + case 1: + break + default: +- // always expect error ++ // always expect error: with no Sentinel quorum to settle ++ // the masters on, the healer still asks for a manual fix. ++ mrfh.On("ResolveMultipleMasters", rf).Maybe().Return(errors.New("no quorum")) + expErr = true + } + if !expErr && continueTests { +@@ -1132,6 +1135,7 @@ func TestUpdate(t *testing.T) { + mrfc.On("GetRedisesIPs", rf).Once().Return([]string{"0.0.0.0", "0.0.0.1", "1.1.1.1"}, nil) + + next := true ++ moved := false + if !test.bootstrapping { + master := "1.1.1.1" + if test.noMaster { +@@ -1162,6 +1166,13 @@ func TestUpdate(t *testing.T) { + for _, pod := range test.pods { + mrfc.On("GetRedisRevisionHash", pod.pod.ObjectMeta.Name, rf).Once().Return(pod.pod.ObjectMeta.Labels[appsv1.ControllerRevisionHashLabelKey], nil) + if pod.pod.ObjectMeta.Labels[appsv1.ControllerRevisionHashLabelKey] != test.ssVersion { ++ if pod.master && !test.bootstrapping { ++ // A stale master with a replica to take over is ++ // failed over, not deleted. ++ mrfh.On("FailoverMaster", rf).Once().Return(nil) ++ moved = true ++ break ++ } + mrfh.On("DeletePod", pod.pod.ObjectMeta.Name, rf).Once().Return(nil) + if pod.master == false { + next = false +@@ -1184,7 +1195,10 @@ func TestUpdate(t *testing.T) { + handler := rfOperator.NewRedisFailoverHandler(config, mrfs, mrfc, mrfh, mk, metrics.Dummy, log.Dummy) + err := handler.UpdateRedisesPods(rf) + +- if test.errExpected { ++ if moved { ++ // The master was failed over: the caller must end its pass. ++ assert.ErrorIs(err, rfservice.ErrMasterMoved) ++ } else if test.errExpected { + assert.Error(err) + } else { + assert.NoError(err) +diff --git a/operator/redisfailover/ensurer.go b/operator/redisfailover/ensurer.go +index b38d7b8..cd1c812 100644 +--- a/operator/redisfailover/ensurer.go ++++ b/operator/redisfailover/ensurer.go +@@ -1,6 +1,8 @@ + package redisfailover + + import ( ++ "errors" ++ + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + redisfailoverv1 "github.com/freshworks/redis-operator/api/redisfailover/v1" +@@ -76,8 +78,21 @@ func (w *RedisFailoverHandler) Ensure(rf *redisfailoverv1.RedisFailover, labels + if err := w.rfService.EnsureRedisReadinessConfigMap(rf, labels, or); err != nil { + return err + } +- if err := w.rfService.EnsureRedisConfigMap(rf, labels, or); err != nil { +- return err ++ // The redis ConfigMap records the credentials every running server has: ++ // ReconcileRedisAuth brings the servers and Sentinels onto what it is ++ // about to say first, and the pod template follows it. One that could ++ // not finish leaves both as they were, and the rest of the resources are ++ // still ensured, so a broken pod can be fixed through the spec meanwhile. ++ rotation := w.rfHealer.ReconcileRedisAuth(rf, labels, or) ++ if rotation != nil && !errors.Is(rotation, rfservice.ErrPasswordRotationPending) { ++ return rotation ++ } ++ if rotation == nil { ++ if err := w.rfService.EnsureRedisConfigMap(rf, labels, or); err != nil { ++ return err ++ } ++ } else { ++ w.logger.WithField("redisfailover", rf.ObjectMeta.Name).WithField("namespace", rf.ObjectMeta.Namespace).Warningf("Keeping the redis config as it is: %v", rotation) + } + if err := w.rfService.EnsureRedisStatefulset(rf, labels, or, tlsHash); err != nil { + return err +@@ -89,5 +104,7 @@ func (w *RedisFailoverHandler) Ensure(rf *redisfailoverv1.RedisFailover, labels + } + } + +- return nil ++ // Pending, the checks do not run either, so nothing starts relying on ++ // credentials a server may lack. ++ return rotation + } +diff --git a/operator/redisfailover/ensurer_test.go b/operator/redisfailover/ensurer_test.go +index bd3f695..20cae01 100644 +--- a/operator/redisfailover/ensurer_test.go ++++ b/operator/redisfailover/ensurer_test.go +@@ -1,6 +1,8 @@ + package redisfailover_test + + import ( ++ "errors" ++ "fmt" + "testing" + + "github.com/stretchr/testify/assert" +@@ -13,6 +15,7 @@ import ( + mRFService "github.com/freshworks/redis-operator/mocks/operator/redisfailover/service" + mK8SService "github.com/freshworks/redis-operator/mocks/service/k8s" + rfOperator "github.com/freshworks/redis-operator/operator/redisfailover" ++ rfservice "github.com/freshworks/redis-operator/operator/redisfailover/service" + ) + + const ( +@@ -122,6 +125,7 @@ func TestEnsure(t *testing.T) { + mrfs.On("EnsureRedisSlaveService", rf, mock.Anything, mock.Anything).Once().Return(nil) + mrfs.On("EnsureRedisCertificate", rf, mock.Anything, mock.Anything).Once().Return(nil) + mrfs.On("EnsureRedisCACertSecret", rf, mock.Anything, mock.Anything).Once().Return("", nil) ++ mrfh.On("ReconcileRedisAuth", rf, mock.Anything, mock.Anything).Once().Return(nil) + mrfs.On("EnsureRedisConfigMap", rf, mock.Anything, mock.Anything).Once().Return(nil) + mrfs.On("EnsureRedisShutdownConfigMap", rf, mock.Anything, mock.Anything).Once().Return(nil) + mrfs.On("EnsureRedisReadinessConfigMap", rf, mock.Anything, mock.Anything).Once().Return(nil) +@@ -158,6 +162,7 @@ func TestEnsurePropagatesTLSHashToPodTemplates(t *testing.T) { + mrfs.On("EnsureRedisMasterService", rf, mock.Anything, mock.Anything).Once().Return(nil) + mrfs.On("EnsureRedisSlaveService", rf, mock.Anything, mock.Anything).Once().Return(nil) + mrfs.On("EnsureRedisCertificate", rf, mock.Anything, mock.Anything).Once().Return(nil) ++ mrfh.On("ReconcileRedisAuth", rf, mock.Anything, mock.Anything).Once().Return(nil) + mrfs.On("EnsureRedisConfigMap", rf, mock.Anything, mock.Anything).Once().Return(nil) + mrfs.On("EnsureRedisShutdownConfigMap", rf, mock.Anything, mock.Anything).Once().Return(nil) + mrfs.On("EnsureRedisReadinessConfigMap", rf, mock.Anything, mock.Anything).Once().Return(nil) +@@ -215,3 +220,69 @@ func TestEnsureWaitsForTLSMaterialBeforeWritingPodFacingObjects(t *testing.T) { + mrfs.AssertNotCalled(t, "EnsureRedisStatefulset", rf, mock.Anything, mock.Anything, mock.Anything) + mrfs.AssertNotCalled(t, "EnsureSentinelDeployment", rf, mock.Anything, mock.Anything, mock.Anything) + } ++ ++// A rotation that cannot finish keeps the redis ConfigMap, and with it the ++// pod template, on the password every server still accepts, while the rest ++// is ensured as usual; the pending error stops the checks. ++func TestEnsureKeepsRedisConfigWhilePasswordRotationIsPending(t *testing.T) { ++ assert := assert.New(t) ++ ++ rf := generateRF(false, false, false) ++ config := generateConfig() ++ mk := &mK8SService.Services{} ++ mrfc := &mRFService.RedisFailoverCheck{} ++ mrfh := &mRFService.RedisFailoverHeal{} ++ mrfs := &mRFService.RedisFailoverClient{} ++ ++ mrfs.On("EnsureNotPresentRedisService", rf).Once().Return(nil) ++ mrfs.On("EnsureSentinelService", rf, mock.Anything, mock.Anything).Once().Return(nil) ++ mrfs.On("EnsureSentinelConfigMap", rf, mock.Anything, mock.Anything).Once().Return(nil) ++ mrfs.On("EnsureRedisMasterService", rf, mock.Anything, mock.Anything).Once().Return(nil) ++ mrfs.On("EnsureRedisSlaveService", rf, mock.Anything, mock.Anything).Once().Return(nil) ++ mrfs.On("EnsureRedisCertificate", rf, mock.Anything, mock.Anything).Once().Return(nil) ++ mrfs.On("EnsureRedisCACertSecret", rf, mock.Anything, mock.Anything).Once().Return("", nil) ++ mrfs.On("EnsureRedisShutdownConfigMap", rf, mock.Anything, mock.Anything).Once().Return(nil) ++ mrfs.On("EnsureRedisReadinessConfigMap", rf, mock.Anything, mock.Anything).Once().Return(nil) ++ mrfs.On("EnsureRedisStatefulset", rf, mock.Anything, mock.Anything, mock.Anything).Once().Return(nil) ++ mrfs.On("EnsureSentinelDeployment", rf, mock.Anything, mock.Anything, mock.Anything).Once().Return(nil) ++ mrfh.On("ReconcileRedisAuth", rf, mock.Anything, mock.Anything).Once().Return(fmt.Errorf("%w: set masterauth on 10.0.0.1: i/o timeout", rfservice.ErrPasswordRotationPending)) ++ ++ handler := rfOperator.NewRedisFailoverHandler(config, mrfs, mrfc, mrfh, mk, metrics.Dummy, log.Dummy) ++ err := handler.Ensure(rf, map[string]string{}, []metav1.OwnerReference{}, metrics.Dummy) ++ ++ assert.ErrorIs(err, rfservice.ErrPasswordRotationPending) ++ mrfs.AssertExpectations(t) ++ mrfs.AssertNotCalled(t, "EnsureRedisConfigMap", rf, mock.Anything, mock.Anything) ++} ++ ++// Any other failure, such as an auth Secret that does not exist, stops ++// Ensure where writing the ConfigMap used to. ++func TestEnsureStopsOnPasswordReadError(t *testing.T) { ++ assert := assert.New(t) ++ ++ rf := generateRF(false, false, false) ++ config := generateConfig() ++ mk := &mK8SService.Services{} ++ mrfc := &mRFService.RedisFailoverCheck{} ++ mrfh := &mRFService.RedisFailoverHeal{} ++ mrfs := &mRFService.RedisFailoverClient{} ++ ++ mrfs.On("EnsureNotPresentRedisService", rf).Once().Return(nil) ++ mrfs.On("EnsureSentinelService", rf, mock.Anything, mock.Anything).Once().Return(nil) ++ mrfs.On("EnsureSentinelConfigMap", rf, mock.Anything, mock.Anything).Once().Return(nil) ++ mrfs.On("EnsureRedisMasterService", rf, mock.Anything, mock.Anything).Once().Return(nil) ++ mrfs.On("EnsureRedisSlaveService", rf, mock.Anything, mock.Anything).Once().Return(nil) ++ mrfs.On("EnsureRedisCertificate", rf, mock.Anything, mock.Anything).Once().Return(nil) ++ mrfs.On("EnsureRedisCACertSecret", rf, mock.Anything, mock.Anything).Once().Return("", nil) ++ mrfs.On("EnsureRedisShutdownConfigMap", rf, mock.Anything, mock.Anything).Once().Return(nil) ++ mrfs.On("EnsureRedisReadinessConfigMap", rf, mock.Anything, mock.Anything).Once().Return(nil) ++ readErr := errors.New(`secrets "test-auth" not found`) ++ mrfh.On("ReconcileRedisAuth", rf, mock.Anything, mock.Anything).Once().Return(readErr) ++ ++ handler := rfOperator.NewRedisFailoverHandler(config, mrfs, mrfc, mrfh, mk, metrics.Dummy, log.Dummy) ++ err := handler.Ensure(rf, map[string]string{}, []metav1.OwnerReference{}, metrics.Dummy) ++ ++ assert.Equal(readErr, err) ++ mrfs.AssertNotCalled(t, "EnsureRedisConfigMap", rf, mock.Anything, mock.Anything) ++ mrfs.AssertNotCalled(t, "EnsureRedisStatefulset", rf, mock.Anything, mock.Anything, mock.Anything) ++} +diff --git a/operator/redisfailover/factory.go b/operator/redisfailover/factory.go +index d5e3a6c..fb52f70 100644 +--- a/operator/redisfailover/factory.go ++++ b/operator/redisfailover/factory.go +@@ -41,6 +41,9 @@ func New(cfg Config, k8sService k8s.Services, k8sClient kubernetes.Interface, lo + rfService := rfservice.NewRedisFailoverKubeClient(k8sService, logger, kooperMetricsRecorder, clusterDomain) + rfChecker := rfservice.NewRedisFailoverChecker(k8sService, redisClient, logger, kooperMetricsRecorder) + rfHealer := rfservice.NewRedisFailoverHealer(k8sService, redisClient, logger) ++ // Lives as long as the operator process; only the leader runs passes, ++ // so only the leader has anything for it to guard. ++ go rfHealer.RunInternalUserGuard(make(chan struct{})) + + // Create the handlers. + rfHandler := NewRedisFailoverHandler(cfg, rfService, rfChecker, rfHealer, k8sService, kooperMetricsRecorder, logger) +diff --git a/operator/redisfailover/service/client.go b/operator/redisfailover/service/client.go +index b83ba64..c8b5800 100644 +--- a/operator/redisfailover/service/client.go ++++ b/operator/redisfailover/service/client.go +@@ -144,6 +144,21 @@ func (r *RedisFailoverKubeClient) EnsureRedisStatefulset(rf *redisfailoverv1.Red + + // Generate and create/update StatefulSet + ss := generateRedisStatefulSet(rf, labels, ownerRefs, tlsHash) ++ // The probes, the shutdown hook and the exporter authenticate as the ++ // internal user once the redis ConfigMap says every server has it, and as ++ // the default user before that, and the exporter as its own user once ++ // the ConfigMap says every server has that one, so the pods roll onto ++ // them once and never again: the client password is in no pod's ++ // environment. ++ if internalAuthEnabled(rf) { ++ applied, _, err := appliedRedisConfig(r.K8SService, rf) ++ if err != nil { ++ return err ++ } ++ if applied.internal { ++ useInternalAuth(&ss.Spec.Template.Spec, rf, applied.exporter) ++ } ++ } + err := r.K8SService.CreateOrUpdateStatefulSet(rf.Namespace, ss) + + r.setEnsureOperationMetrics(ss.Namespace, ss.Name, "StatefulSet", rf.Name, err) +@@ -264,7 +279,21 @@ func (r *RedisFailoverKubeClient) EnsureRedisConfigMap(rf *redisfailoverv1.Redis + return err + } + +- cm := generateRedisConfigMap(rf, labels, ownerRefs, password) ++ var creds internalCreds ++ if internalAuthEnabled(rf) && password != "" { ++ // ReconcileRedisAuth creates the Secret before this runs, and lets ++ // this run only with no rotation in flight. ++ sec, c, err := readInternalCreds(r.K8SService, rf) ++ if err != nil { ++ return err ++ } ++ if sec == nil || c.link == "" || c.exporter == "" { ++ return fmt.Errorf("secret %q does not exist yet", GetRedisInternalAuthName(rf)) ++ } ++ creds = c ++ } ++ ++ cm := generateRedisConfigMap(rf, labels, ownerRefs, password, creds.pod, creds.link, creds.exporter) + err = r.K8SService.CreateOrUpdateConfigMap(rf.Namespace, cm) + + r.setEnsureOperationMetrics(cm.Namespace, cm.Name, "ConfigMap", rf.Name, err) +diff --git a/operator/redisfailover/service/export_test.go b/operator/redisfailover/service/export_test.go +new file mode 100644 +index 0000000..80ec75c +--- /dev/null ++++ b/operator/redisfailover/service/export_test.go +@@ -0,0 +1,21 @@ ++package service ++ ++import "time" ++ ++// SetFailoverTiming shortens FailoverMaster's wait for the tests and returns ++// a function restoring it. ++func SetFailoverTiming(timeout, poll time.Duration) func() { ++ oldTimeout, oldPoll := failoverTimeout, failoverPoll ++ failoverTimeout, failoverPoll = timeout, poll ++ return func() { failoverTimeout, failoverPoll = oldTimeout, oldPoll } ++} ++ ++// GenerateRedisConfigMapForTest exposes generateRedisConfigMap. ++var GenerateRedisConfigMapForTest = generateRedisConfigMap ++ ++// SetGuardNow replaces the guard's clock and returns a function restoring it. ++func SetGuardNow(now func() time.Time) func() { ++ old := guardNow ++ guardNow = now ++ return func() { guardNow = old } ++} +diff --git a/operator/redisfailover/service/generator.go b/operator/redisfailover/service/generator.go +index a6635fa..bfbc43e 100644 +--- a/operator/redisfailover/service/generator.go ++++ b/operator/redisfailover/service/generator.go +@@ -448,7 +448,13 @@ func generateSentinelConfigMap(rf *redisfailoverv1.RedisFailover, labels map[str + } + } + +-func generateRedisConfigMap(rf *redisfailoverv1.RedisFailover, labels map[string]string, ownerRefs []metav1.OwnerReference, password string) *corev1.ConfigMap { ++// generateRedisConfigMap writes the client password as requirepass. With the ++// internal user's passwords the servers replicate as that user with its link ++// password, its ACL line carries the hashes of both its pod and its link ++// password, and the exporter user's line the hash of the exporter password; ++// without them (no internal Secret yet, or a bootstrapping RedisFailover) ++// they replicate with the client password, as upstream does. ++func generateRedisConfigMap(rf *redisfailoverv1.RedisFailover, labels map[string]string, ownerRefs []metav1.OwnerReference, password, pod, link, exporter string) *corev1.ConfigMap { + name := GetRedisName(rf) + labels = util.MergeLabels(labels, generateSelectorLabels(redisRoleName, rf.Name)) + +@@ -464,7 +470,13 @@ func generateRedisConfigMap(rf *redisfailoverv1.RedisFailover, labels map[string + + redisConfigFileContent := tplOutput.String() + +- if password != "" { ++ switch { ++ case password != "" && pod != "" && link != "": ++ redisConfigFileContent = fmt.Sprintf("%s\nmasteruser %s\nmasterauth %s\nrequirepass %s\nuser %s %s", redisConfigFileContent, internalUser, link, password, internalUser, strings.Join(internalUserRules(pod, link), " ")) ++ if exporter != "" { ++ redisConfigFileContent = fmt.Sprintf("%s\nuser %s %s", redisConfigFileContent, exporterUser, strings.Join(exporterUserRules(exporter), " ")) ++ } ++ case password != "": + redisConfigFileContent = fmt.Sprintf("%s\nmasterauth %s\nrequirepass %s", redisConfigFileContent, password, password) + } + +@@ -500,6 +512,9 @@ fi + cmd="%[4]s %[6]s-p %[2]v" + if [ ! -z "${REDIS_PASSWORD}" ]; then + export %[5]s=${REDIS_PASSWORD} ++ if [ ! -z "${REDIS_USER}" ]; then ++ cmd="${cmd} --user ${REDIS_USER}" ++ fi + fi + save_command="${cmd} save" + eval $save_command`, rfName, port, rf.MasterName(), cli, authEnv, tlsFlags) +@@ -536,6 +551,9 @@ NO_MASTER="master_host:127.0.0.1" + cmd="%[2]s %[4]s-p %[1]v" + if [ ! -z "${REDIS_PASSWORD}" ]; then + export %[3]s=${REDIS_PASSWORD} ++ if [ ! -z "${REDIS_USER}" ]; then ++ cmd="${cmd} --user ${REDIS_USER}" ++ fi + fi + + cmd="${cmd} info replication" +diff --git a/operator/redisfailover/service/generator_test.go b/operator/redisfailover/service/generator_test.go +index 39bbcfd..52bed44 100644 +--- a/operator/redisfailover/service/generator_test.go ++++ b/operator/redisfailover/service/generator_test.go +@@ -2259,6 +2259,7 @@ func TestRedisEnv(t *testing.T) { + + ms := &mK8SService.Services{} + ms.On("GetStatefulSet", namespace, mock.Anything).Once().Return(nil, errors.NewNotFound(schema.GroupResource{}, "")) ++ ms.On("GetConfigMap", namespace, mock.Anything).Maybe().Return(nil, errors.NewNotFound(schema.GroupResource{}, "")) + ms.On("CreateOrUpdatePodDisruptionBudget", namespace, mock.Anything).Once().Return(nil, nil) + ms.On("CreateOrUpdateStatefulSet", namespace, mock.Anything).Once().Run(func(args mock.Arguments) { + s := args.Get(1).(*appsv1.StatefulSet) +@@ -2853,7 +2854,7 @@ func TestDisableMyMaster(t *testing.T) { + }, + expectedRedisShutdownSHScriptConfigMap: &corev1.ConfigMap{ + Data: map[string]string{ +- "shutdown.sh": "master=$(redis-cli -h ${RFS_TEST_SERVICE_HOST} -p ${RFS_TEST_SERVICE_PORT_SENTINEL} --csv SENTINEL get-master-addr-by-name mymaster | tr ',' ' ' | tr -d '\\\"' |cut -d' ' -f1)\nif [ \"$master\" = \"$(hostname -i)\" ]; then\nredis-cli -h ${RFS_TEST_SERVICE_HOST} -p ${RFS_TEST_SERVICE_PORT_SENTINEL} SENTINEL failover mymaster\nsleep 31\nfi\ncmd=\"redis-cli -p 0\"\nif [ ! -z \"${REDIS_PASSWORD}\" ]; then\n\texport REDISCLI_AUTH=${REDIS_PASSWORD}\nfi\nsave_command=\"${cmd} save\"\neval $save_command", ++ "shutdown.sh": "master=$(redis-cli -h ${RFS_TEST_SERVICE_HOST} -p ${RFS_TEST_SERVICE_PORT_SENTINEL} --csv SENTINEL get-master-addr-by-name mymaster | tr ',' ' ' | tr -d '\\\"' |cut -d' ' -f1)\nif [ \"$master\" = \"$(hostname -i)\" ]; then\nredis-cli -h ${RFS_TEST_SERVICE_HOST} -p ${RFS_TEST_SERVICE_PORT_SENTINEL} SENTINEL failover mymaster\nsleep 31\nfi\ncmd=\"redis-cli -p 0\"\nif [ ! -z \"${REDIS_PASSWORD}\" ]; then\n\texport REDISCLI_AUTH=${REDIS_PASSWORD}\n\tif [ ! -z \"${REDIS_USER}\" ]; then\n\t\tcmd=\"${cmd} --user ${REDIS_USER}\"\n\tfi\nfi\nsave_command=\"${cmd} save\"\neval $save_command", + }, + }, + }, +@@ -2880,7 +2881,7 @@ func TestDisableMyMaster(t *testing.T) { + }, + expectedRedisShutdownSHScriptConfigMap: &corev1.ConfigMap{ + Data: map[string]string{ +- "shutdown.sh": "master=$(redis-cli -h ${RFS_TEST_SERVICE_HOST} -p ${RFS_TEST_SERVICE_PORT_SENTINEL} --csv SENTINEL get-master-addr-by-name test | tr ',' ' ' | tr -d '\\\"' |cut -d' ' -f1)\nif [ \"$master\" = \"$(hostname -i)\" ]; then\nredis-cli -h ${RFS_TEST_SERVICE_HOST} -p ${RFS_TEST_SERVICE_PORT_SENTINEL} SENTINEL failover test\nsleep 31\nfi\ncmd=\"redis-cli -p 0\"\nif [ ! -z \"${REDIS_PASSWORD}\" ]; then\n\texport REDISCLI_AUTH=${REDIS_PASSWORD}\nfi\nsave_command=\"${cmd} save\"\neval $save_command", ++ "shutdown.sh": "master=$(redis-cli -h ${RFS_TEST_SERVICE_HOST} -p ${RFS_TEST_SERVICE_PORT_SENTINEL} --csv SENTINEL get-master-addr-by-name test | tr ',' ' ' | tr -d '\\\"' |cut -d' ' -f1)\nif [ \"$master\" = \"$(hostname -i)\" ]; then\nredis-cli -h ${RFS_TEST_SERVICE_HOST} -p ${RFS_TEST_SERVICE_PORT_SENTINEL} SENTINEL failover test\nsleep 31\nfi\ncmd=\"redis-cli -p 0\"\nif [ ! -z \"${REDIS_PASSWORD}\" ]; then\n\texport REDISCLI_AUTH=${REDIS_PASSWORD}\n\tif [ ! -z \"${REDIS_USER}\" ]; then\n\t\tcmd=\"${cmd} --user ${REDIS_USER}\"\n\tfi\nfi\nsave_command=\"${cmd} save\"\neval $save_command", + }, + }, + }, +diff --git a/operator/redisfailover/service/heal.go b/operator/redisfailover/service/heal.go +index 36bbc6a..bec4382 100644 +--- a/operator/redisfailover/service/heal.go ++++ b/operator/redisfailover/service/heal.go +@@ -12,6 +12,7 @@ import ( + "github.com/freshworks/redis-operator/service/k8s" + "github.com/freshworks/redis-operator/service/redis" + v1 "k8s.io/api/core/v1" ++ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ) + + // RedisFailoverHeal defines the interface able to fix the problems on the redis failovers +@@ -26,6 +27,9 @@ type RedisFailoverHeal interface { + SetSentinelCustomConfig(ip string, rFailover *redisfailoverv1.RedisFailover) error + SetRedisCustomConfig(ip string, rFailover *redisfailoverv1.RedisFailover) error + DeletePod(podName string, rFailover *redisfailoverv1.RedisFailover) error ++ ReconcileRedisAuth(rFailover *redisfailoverv1.RedisFailover, labels map[string]string, ownerRefs []metav1.OwnerReference) error ++ FailoverMaster(rFailover *redisfailoverv1.RedisFailover) error ++ ResolveMultipleMasters(rFailover *redisfailoverv1.RedisFailover) error + } + + // RedisFailoverHealer is our implementation of RedisFailoverCheck interface +@@ -33,6 +37,7 @@ type RedisFailoverHealer struct { + k8sService k8s.Services + redisClient redis.Client + logger log.Logger ++ guard *internalUserGuard + } + + // NewRedisFailoverHealer creates an object of the RedisFailoverChecker struct +@@ -42,6 +47,7 @@ func NewRedisFailoverHealer(k8sService k8s.Services, redisClient redis.Client, l + k8sService: k8sService, + redisClient: redisClient, + logger: logger, ++ guard: newInternalUserGuard(), + } + } + +@@ -292,27 +298,14 @@ func (r *RedisFailoverHealer) SetExternalMasterOnAll(masterIP, masterPort string + + // NewSentinelMonitor changes the master that Sentinel has to monitor + func (r *RedisFailoverHealer) NewSentinelMonitor(ip string, monitor string, rf *redisfailoverv1.RedisFailover) error { +- quorum := strconv.Itoa(int(getQuorum(rf))) +- +- password, err := k8s.GetRedisPassword(r.k8sService, rf) +- if err != nil { +- return err +- } +- +- tlsConfig, err := tlsConfigFor(r.k8sService, rf) +- if err != nil { +- return err +- } +- +- port := getRedisPort(rf.Spec.Redis.Port) +- return r.redisClient.MonitorRedisWithPort(ip, monitor, port, quorum, password, rf.MasterName(), tlsConfig) ++ return r.NewSentinelMonitorWithPort(ip, monitor, getRedisPort(rf.Spec.Redis.Port), rf) + } + + // NewSentinelMonitorWithPort changes the master that Sentinel has to monitor by the provided IP and Port + func (r *RedisFailoverHealer) NewSentinelMonitorWithPort(ip string, monitor string, monitorPort string, rf *redisfailoverv1.RedisFailover) error { + quorum := strconv.Itoa(int(getQuorum(rf))) + +- password, err := k8s.GetRedisPassword(r.k8sService, rf) ++ user, password, err := sentinelAuth(r.k8sService, rf) + if err != nil { + return err + } +@@ -322,7 +315,15 @@ func (r *RedisFailoverHealer) NewSentinelMonitorWithPort(ip string, monitor stri + return err + } + +- return r.redisClient.MonitorRedisWithPort(ip, monitor, monitorPort, quorum, password, rf.MasterName(), tlsConfig) ++ if user == "" { ++ return r.redisClient.MonitorRedisWithPort(ip, monitor, monitorPort, quorum, password, rf.MasterName(), tlsConfig) ++ } ++ // MONITOR, then the internal user's credentials, which MonitorRedisWithPort ++ // can only give as a default-user password. ++ if err := r.redisClient.MonitorRedisWithPort(ip, monitor, monitorPort, quorum, "", rf.MasterName(), tlsConfig); err != nil { ++ return err ++ } ++ return r.redisClient.SetSentinelAuth(ip, rf.MasterName(), user, password, tlsConfig) + } + + // RestoreSentinel clears the number of sentinels on memory. +@@ -343,14 +344,17 @@ func (r *RedisFailoverHealer) RestoreSentinel(ip string, rf *redisfailoverv1.Red + // message, so it monitors the right address without a password, gets + // NOAUTH from the master and keeps reporting it as down: the reset alone + // would then repeat on every check without converging. +- password, err := k8s.GetRedisPassword(r.k8sService, rf) ++ user, password, err := sentinelAuth(r.k8sService, rf) + if err != nil { + return err + } + if password == "" { + return nil + } +- return r.redisClient.SetSentinelAuthPass(ip, rf.MasterName(), password, tlsConfig) ++ if user == "" { ++ return r.redisClient.SetSentinelAuthPass(ip, rf.MasterName(), password, tlsConfig) ++ } ++ return r.redisClient.SetSentinelAuth(ip, rf.MasterName(), user, password, tlsConfig) + } + + // SetSentinelCustomConfig will call sentinel to set the configuration given in config +diff --git a/operator/redisfailover/service/heal_test.go b/operator/redisfailover/service/heal_test.go +index e8c316e..5393464 100644 +--- a/operator/redisfailover/service/heal_test.go ++++ b/operator/redisfailover/service/heal_test.go +@@ -9,7 +9,9 @@ import ( + + "github.com/stretchr/testify/assert" + corev1 "k8s.io/api/core/v1" ++ apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ++ "k8s.io/apimachinery/pkg/runtime/schema" + + "github.com/freshworks/redis-operator/log" + mK8SService "github.com/freshworks/redis-operator/mocks/service/k8s" +@@ -504,6 +506,9 @@ func TestRestoreSentinel(t *testing.T) { + + mr.On("ResetSentinel", "0.0.0.0", mock.Anything).Once().Return(test.resetErr) + if test.resetErr == nil && test.authSecret != "" { ++ // No redis ConfigMap yet, so no internal user: the Sentinel ++ // gets the client password, as before. ++ ms.On("GetConfigMap", rf.Namespace, rfservice.GetRedisName(rf)).Once().Return(nil, apierrors.NewNotFound(schema.GroupResource{}, "")) + secret := &corev1.Secret{Data: map[string][]byte{"password": []byte("s3cret")}} + if test.secretErr != nil { + secret = nil +diff --git a/operator/redisfailover/service/password.go b/operator/redisfailover/service/password.go +new file mode 100644 +index 0000000..9108e10 +--- /dev/null ++++ b/operator/redisfailover/service/password.go +@@ -0,0 +1,1325 @@ ++package service ++ ++import ( ++ "crypto/rand" ++ "crypto/sha256" ++ "crypto/tls" ++ "encoding/hex" ++ "errors" ++ "fmt" ++ "math/big" ++ "net" ++ "sort" ++ "strings" ++ "sync" ++ "time" ++ ++ corev1 "k8s.io/api/core/v1" ++ apierrors "k8s.io/apimachinery/pkg/api/errors" ++ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ++ ++ redisfailoverv1 "github.com/freshworks/redis-operator/api/redisfailover/v1" ++ "github.com/freshworks/redis-operator/log" ++ "github.com/freshworks/redis-operator/operator/redisfailover/util" ++ "github.com/freshworks/redis-operator/service/k8s" ++ "github.com/freshworks/redis-operator/service/redis" ++) ++ ++// The password of the auth Secret belongs to the clients: whoever holds the ++// Secret may change it at any time, and a change must reach the servers ++// without restarting anything. So nothing the operator runs authenticates ++// with it except the operator's own checks. Replication, the Sentinels, the ++// probes and the shutdown hook authenticate as internalUser, and the ++// exporter as exporterUser. ++// ++// The internal user has two passwords, kept in its own Secret: ++// ++// - the pod password (key "password"), which the probes and the shutdown ++// hook read from their environment at start. It is never rotated, since ++// that would restart them, and no server ever holds it in clear: it is in ++// the ACL as a hash only. ++// - the link password (key "link"), which the servers replicate with ++// (masterauth) and the Sentinels authenticate with (auth-pass). Anyone ++// holding the client password can read it with CONFIG GET masterauth, ++// so it is rotated whenever the client password changes, in stages that ++// keep the old one valid until nothing uses it any more (see ++// rotateLinkPassword). ++// ++// The exporter's password (key "exporter") is fixed like the pod password and ++// held by the servers as a hash only. It is the one password that can run ++// CONFIG GET, which reads requirepass and masterauth, so no client password ++// holder can learn it from a server. ++const ( ++ internalUser = "rf-internal" ++ exporterUser = "rf-exporter" ++ ++ podPasswordKey = "password" ++ exporterPasswordKey = "exporter" ++ linkPasswordKey = "link" ++ // linkPreviousKey holds the link password being retired while a rotation ++ // is in flight; it is absent otherwise. ++ linkPreviousKey = "link-previous" ++ // linkIssuedForKey is the hash of the client password in force when the ++ // current link password was generated: holders of that client password, ++ // and of no older one, may have read it. ++ linkIssuedForKey = "client-sha256" ++ ++ sentinelHelloChannel = "__sentinel__:hello" ++ ++ // pingerUser is the liveness probe's user, from the redis.conf template, ++ // and pingerPassword its password, which the template makes public. ++ pingerUser = "pinger" ++ pingerPassword = "pingpass" ++) ++ ++// operatorUsers are the only ACL users a server keeps. A tenant's default ++// user can create others, and one created before a revoke would keep the ++// tenant in after it. They never survived a restart anyway (no aclfile is ++// configured, so the servers load users from redis.conf alone), so the ++// operator deletes them on every client password change, on every rotation ++// and in the guard. ACL DELUSER also disconnects every client authenticated ++// as the user it deletes. ++var operatorUsers = map[string]bool{"default": true, internalUser: true, exporterUser: true, pingerUser: true} ++ ++// internalCommands is every command the internal user may run, and nothing ++// else: it reads no key, no configuration parameter, and uses no channel but ++// the Sentinels' hello channel. AUTH and HELLO need no rule, ACL does not ++// check them. Checked against Redis 7.2.7 and 8.0.2 and Valkey 8.0.2: ++// ++// - a replica on its master: PING, REPLCONF, PSYNC and SYNC ++// (replication.c, syncWithMaster and the rdb channel of Redis 8 and ++// Valkey 8); ++// - a Sentinel on every server: CLIENT SETNAME, SUBSCRIBE and PUBLISH on ++// the hello channel, PING, INFO, SCRIPT KILL, and the failover ++// transaction MULTI, SLAVEOF, CONFIG REWRITE, CLIENT KILL, EXEC ++// (sentinel.c). A command ACL denies inside MULTI aborts the EXEC, so the ++// transaction needs every one of them. No Sentinel sends CONFIG GET; ++// - the readiness probe INFO and the shutdown hook SAVE (generator.go). ++// ++// The operator itself authenticates as the default user, the liveness probe ++// as pinger and the exporter as exporterUser. ++var internalCommands = []string{ ++ "ping", "info", ++ "psync", "sync", "replconf", ++ "client|setname", "client|kill", "subscribe", "publish", ++ "multi", "exec", "slaveof", "config|rewrite", "script|kill", ++ "save", ++} ++ ++// exporterCommands is every command redis_exporter v1.55.0 sends to a server ++// with the flags the operator starts it with: CLIENT SETNAME ++// (exporter.go:581, set-client-name is on by default), CONFIG GET ++// (exporter.go:587), INFO (exporter.go:597 and 600), LATENCY LATEST and ++// HISTOGRAM (latency.go:27 and 54), SLOWLOG LEN and GET (slowlog.go:9 and ++// 13). PING (ping-on-connect), CLIENT LIST (export-client-list), and the key, ++// stream, count, key-group and Lua checks are off by default and not set, ++// CLUSTER INFO runs on a cluster only and SENTINEL on a Sentinel only. AUTH ++// is not checked, and with no database in REDIS_ADDR there is no SELECT. ++var exporterCommands = []string{ ++ "client|setname", "config|get", "info", ++ "latency|latest", "latency|histogram", "slowlog|len", "slowlog|get", ++} ++ ++// commandRules is commands as ACL GETUSER reports them back: the server keeps ++// the command rules in the order given, lowercased, after the -@all that ++// starts them. ++func commandRules(commands []string) string { ++ rules := []string{"-@all"} ++ for _, c := range commands { ++ rules = append(rules, "+"+c) ++ } ++ return strings.Join(rules, " ") ++} ++ ++func internalCommandRules() string { return commandRules(internalCommands) } ++ ++// ErrPasswordRotationPending reports that the running servers and Sentinels ++// could not all be brought onto the internal user, or onto a changed client ++// password and the link password rotated with it. The redis ConfigMap, and ++// with it the pod template, stays as it was until they are, and the checks ++// do not run, so nothing starts relying on credentials a server lacks. ++var ErrPasswordRotationPending = errors.New("redis auth rotation pending") ++ ++// ErrMasterMoved reports that the pod roll moved the master role this pass. ++// Whatever the pass read as the master before is stale, so it must end ++// instead of healing towards it. ++var ErrMasterMoved = errors.New("the master role moved") ++ ++// GetRedisInternalAuthName is the Secret holding the internal user's ++// passwords. ++func GetRedisInternalAuthName(rf *redisfailoverv1.RedisFailover) string { ++ return GetRedisName(rf) + "-internal" ++} ++ ++// internalAuthEnabled tells whether the RedisFailover uses the internal ++// user. A bootstrapping RedisFailover replicates from a master outside it, ++// which knows nothing of that user, so it keeps the upstream behaviour. ++func internalAuthEnabled(rf *redisfailoverv1.RedisFailover) bool { ++ return rf.Spec.Auth.SecretPath != "" && !rf.Bootstrapping() ++} ++ ++// appliedConfig is what the redis ConfigMap says every running server has: ++// the ConfigMap moves on only once they do. ++type appliedConfig struct { ++ password string ++ internal bool ++ exporter bool ++} ++ ++func appliedRedisConfig(s k8s.Services, rf *redisfailoverv1.RedisFailover) (cfg appliedConfig, found bool, err error) { ++ cm, err := s.GetConfigMap(rf.Namespace, GetRedisName(rf)) ++ if apierrors.IsNotFound(err) { ++ return appliedConfig{}, false, nil ++ } ++ if err != nil { ++ return appliedConfig{}, false, err ++ } ++ return parseRedisConfig(cm.Data[redisConfigFileName]), true, nil ++} ++ ++// parseRedisConfig reads a redis.conf as generateRedisConfigMap writes it. ++func parseRedisConfig(conf string) appliedConfig { ++ var cfg appliedConfig ++ for _, line := range strings.Split(conf, "\n") { ++ if v, ok := strings.CutPrefix(line, "requirepass "); ok { ++ cfg.password = v ++ } ++ if strings.HasPrefix(line, "user "+internalUser+" ") { ++ cfg.internal = true ++ } ++ if strings.HasPrefix(line, "user "+exporterUser+" ") { ++ cfg.exporter = true ++ } ++ } ++ return cfg ++} ++ ++// internalCreds is what the internal Secret holds. ++type internalCreds struct { ++ pod string ++ exporter string ++ link string ++ previous string ++ issuedFor string ++} ++ ++// links is every link password the servers must accept now: the current one ++// and, during a rotation, the one being retired. ++func (c internalCreds) links() []string { ++ if c.previous == "" { ++ return []string{c.link} ++ } ++ return []string{c.previous, c.link} ++} ++ ++// readInternalCreds returns the internal Secret and what it holds, or a nil ++// Secret when it does not exist yet. ++func readInternalCreds(s k8s.Services, rf *redisfailoverv1.RedisFailover) (*corev1.Secret, internalCreds, error) { ++ sec, err := s.GetSecret(rf.Namespace, GetRedisInternalAuthName(rf)) ++ if apierrors.IsNotFound(err) { ++ return nil, internalCreds{}, nil ++ } ++ if err != nil { ++ return nil, internalCreds{}, err ++ } ++ creds := internalCreds{ ++ pod: string(sec.Data[podPasswordKey]), ++ exporter: string(sec.Data[exporterPasswordKey]), ++ link: string(sec.Data[linkPasswordKey]), ++ previous: string(sec.Data[linkPreviousKey]), ++ issuedFor: string(sec.Data[linkIssuedForKey]), ++ } ++ if creds.pod == "" { ++ return nil, internalCreds{}, fmt.Errorf("secret %q has no %s", sec.Name, podPasswordKey) ++ } ++ return sec, creds, nil ++} ++ ++// ensureInternalSecret creates the internal Secret once and returns what it ++// holds. issuedFor is the hash of the client password whose holders can ++// read the link password from the servers once it is in use. The pod and ++// exporter passwords are never rewritten: everything that reads them at ++// start would need a restart. ++func ensureInternalSecret(s k8s.Services, rf *redisfailoverv1.RedisFailover, labels map[string]string, ownerRefs []metav1.OwnerReference, issuedFor string) (internalCreds, error) { ++ sec, creds, err := readInternalCreds(s, rf) ++ if err != nil { ++ return internalCreds{}, err ++ } ++ if sec != nil && creds.link != "" && creds.exporter != "" { ++ return creds, nil ++ } ++ if sec != nil { ++ // A Secret written by an operator version that had no link password, ++ // when the servers replicated with the pod password, or no exporter ++ // user, when the exporter ran as the internal user: add what is ++ // missing. The per-pass checks then move masterauth and the Sentinels ++ // onto the link password, and introduce the exporter user. ++ sec = sec.DeepCopy() ++ if creds.link == "" { ++ if creds.link, err = randomPassword(32); err != nil { ++ return internalCreds{}, err ++ } ++ creds.issuedFor = issuedFor ++ sec.Data[linkPasswordKey] = []byte(creds.link) ++ sec.Data[linkIssuedForKey] = []byte(issuedFor) ++ } ++ if creds.exporter == "" { ++ if creds.exporter, err = randomPassword(32); err != nil { ++ return internalCreds{}, err ++ } ++ sec.Data[exporterPasswordKey] = []byte(creds.exporter) ++ } ++ if err := s.UpdateSecret(rf.Namespace, sec); err != nil { ++ return internalCreds{}, err ++ } ++ return creds, nil ++ } ++ creds = internalCreds{issuedFor: issuedFor} ++ for _, p := range []*string{&creds.pod, &creds.exporter, &creds.link} { ++ if *p, err = randomPassword(32); err != nil { ++ return internalCreds{}, err ++ } ++ } ++ sec = &corev1.Secret{ ++ ObjectMeta: metav1.ObjectMeta{ ++ Name: GetRedisInternalAuthName(rf), ++ Namespace: rf.Namespace, ++ Labels: util.MergeLabels(labels, generateSelectorLabels(redisRoleName, rf.Name)), ++ OwnerReferences: ownerRefs, ++ }, ++ Type: corev1.SecretTypeOpaque, ++ Data: map[string][]byte{ ++ podPasswordKey: []byte(creds.pod), ++ exporterPasswordKey: []byte(creds.exporter), ++ linkPasswordKey: []byte(creds.link), ++ linkIssuedForKey: []byte(issuedFor), ++ }, ++ } ++ if err := s.CreateSecret(rf.Namespace, sec); err != nil { ++ return internalCreds{}, err ++ } ++ return creds, nil ++} ++ ++// updateInternalSecret re-reads the internal Secret, applies change to a ++// copy and writes it back, so a write lost to a conflict changes nothing. ++func updateInternalSecret(s k8s.Services, rf *redisfailoverv1.RedisFailover, change func(map[string][]byte)) error { ++ sec, _, err := readInternalCreds(s, rf) ++ if err != nil { ++ return err ++ } ++ if sec == nil { ++ return fmt.Errorf("secret %q does not exist", GetRedisInternalAuthName(rf)) ++ } ++ sec = sec.DeepCopy() ++ change(sec.Data) ++ return s.UpdateSecret(rf.Namespace, sec) ++} ++ ++func randomPassword(n int) (string, error) { ++ const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" ++ out := make([]byte, n) ++ for i := range out { ++ k, err := rand.Int(rand.Reader, big.NewInt(int64(len(alphabet)))) ++ if err != nil { ++ return "", err ++ } ++ out[i] = alphabet[k.Int64()] ++ } ++ return string(out), nil ++} ++ ++// passwordHash is the form ACL rules and ACL GETUSER use for a password. ++func passwordHash(password string) string { ++ sum := sha256.Sum256([]byte(password)) ++ return hex.EncodeToString(sum[:]) ++} ++ ++// internalUserRules is the ACL rule list of the internal user, for ACL ++// SETUSER after a reset and for the redis.conf user line: on, the pod ++// password and every link password given, no key, the Sentinels' hello ++// channel alone, and internalCommands. ++func internalUserRules(pod string, links ...string) []string { ++ rules := []string{"on", "#" + passwordHash(pod)} ++ for _, l := range links { ++ rules = append(rules, "#"+passwordHash(l)) ++ } ++ rules = append(rules, "resetkeys", "resetchannels", "&"+sentinelHelloChannel) ++ return append(rules, strings.Fields(internalCommandRules())...) ++} ++ ++// exporterUserRules is the ACL rule list of the exporter user: on, its one ++// password, no key, no channel, and exporterCommands. ++func exporterUserRules(password string) []string { ++ rules := []string{"on", "#" + passwordHash(password), "resetkeys", "resetchannels"} ++ return append(rules, strings.Fields(commandRules(exporterCommands))...) ++} ++ ++// pingerUserRules is the pinger line of the redis.conf template as a rule ++// list: on, its public password, PING alone. ++func pingerUserRules() []string { ++ return []string{"on", "#" + passwordHash(pingerPassword), "resetkeys", "resetchannels", "-@all", "+ping"} ++} ++ ++// userMatches tells whether acl is exactly a user that is on, with exactly ++// the given passwords, no key, the given channels and commands, and no extra ++// selector. ++func userMatches(acl redis.UserACL, channels, commands string, passwords ...string) bool { ++ if !acl.Exists || !acl.On || acl.NoPass || acl.Selectors != 0 || ++ acl.Keys != "" || acl.Channels != channels || acl.Commands != commands { ++ return false ++ } ++ want := make([]string, 0, len(passwords)) ++ for _, p := range passwords { ++ want = append(want, passwordHash(p)) ++ } ++ got := append([]string(nil), acl.Hashes...) ++ sort.Strings(want) ++ sort.Strings(got) ++ return strings.Join(want, ",") == strings.Join(got, ",") ++} ++ ++// internalUserMatches tells whether the internal user is exactly what ++// internalUserRules(pod, links...) sets. ++func internalUserMatches(acl redis.UserACL, pod string, links ...string) bool { ++ return userMatches(acl, "&"+sentinelHelloChannel, internalCommandRules(), append([]string{pod}, links...)...) ++} ++ ++// exporterUserMatches tells whether the exporter user is exactly what ++// exporterUserRules(password) sets. ++func exporterUserMatches(acl redis.UserACL, password string) bool { ++ return userMatches(acl, "", commandRules(exporterCommands), password) ++} ++ ++// ReconcileRedisAuth brings the running servers and Sentinels onto what the ++// redis ConfigMap is about to say, before it says it. It runs in Ensure ++// before the ConfigMap is written. ++// ++// While the ConfigMap has no internal user (a RedisFailover created before ++// this operator version), every running server gets the user and uses it as ++// masteruser/masterauth, and every running Sentinel uses it as ++// auth-user/auth-pass; any failure returns ErrPasswordRotationPending, so ++// the ConfigMap and the pod template, whose probes and exporter switch to ++// the user, wait until every server has it. The exporter user is introduced ++// the same way while the ConfigMap has none (a RedisFailover whose exporter ++// ran as the internal user), so the exporter switches to it only once every ++// server has it. ++// ++// A client password that differs from the ConfigMap's is applied on every ++// running server, authenticating with the new password or, until it is ++// applied, the old one, by changeClientPassword: CONFIG SET requirepass ++// leaves every connection that authenticated with the old password open, ++// and the default user may run CONFIG GET requirepass, so the change ++// disconnects every client but the operator's own links in the same ++// transaction. Holders of the old one may have read the link password, so ++// once every server is on the new one the link password is rotated ++// (rotateLinkPassword). Until both are ++// done the pass returns ErrPasswordRotationPending, so the ConfigMap keeps ++// the old client password and a server restarted meanwhile comes back on ++// credentials the next pass knows. A server that accepts neither client ++// password is deleted (one per pass) to start again from the ConfigMap. ++// ++// Otherwise every pass re-asserts the internal and exporter users ++// (reassertInternalUser): ++// the tenant's default user can run ACL, CONFIG and SENTINEL SET. Nothing a ++// tenant changes outlives a restart either: the servers read redis.conf ++// straight from the ConfigMap volume, which is read-only, so CONFIG REWRITE ++// fails, and no aclfile is configured (ACL SAVE fails, and aclfile cannot be ++// set at runtime). ++// ++// Every step is idempotent and the internal Secret and the ConfigMap record ++// progress, so a pass interrupted at any point is resumed by the next one. ++// The guard does not check a RedisFailover while a pass runs on it. ++func (r *RedisFailoverHealer) ReconcileRedisAuth(rf *redisfailoverv1.RedisFailover, labels map[string]string, ownerRefs []metav1.OwnerReference) error { ++ if !internalAuthEnabled(rf) { ++ r.guard.forget(rf) ++ return nil ++ } ++ defer r.guard.lock(guardKey(rf))() ++ ++ desired, err := k8s.GetRedisPassword(r.k8sService, rf) ++ if err != nil { ++ return err ++ } ++ applied, found, err := appliedRedisConfig(r.k8sService, rf) ++ if err != nil { ++ return err ++ } ++ // A new link password can be read by whoever holds the client password ++ // the servers run on: the ConfigMap's, or for a new RedisFailover the ++ // one its pods start with. ++ holder := desired ++ if found { ++ holder = applied.password ++ } ++ creds, err := ensureInternalSecret(r.k8sService, rf, labels, ownerRefs, passwordHash(holder)) ++ if err != nil { ++ return err ++ } ++ if !found { ++ // A new RedisFailover: its pods start from a ConfigMap that has it all. ++ return nil ++ } ++ tlsConfig, err := tlsConfigFor(r.k8sService, rf) ++ if err != nil { ++ return err ++ } ++ serverList, err := r.k8sService.GetStatefulSetPods(rf.Namespace, GetRedisName(rf)) ++ if err != nil { ++ return err ++ } ++ pods, _ := runningPods(serverList, nil) ++ // known is every address the operator's own links may come from: any ++ // pod of the RedisFailover holding an IP, running or not, so a replica ++ // or Sentinel that is starting or stopping is not taken for a stranger. ++ known := podAddresses(serverList) ++ var sentinels []corev1.Pod ++ if rf.SentinelsAllowed() { ++ sentinelList, err := r.k8sService.GetDeploymentPods(rf.Namespace, GetSentinelName(rf)) ++ if err != nil { ++ return err ++ } ++ sentinels, _ = runningPods(sentinelList, nil) ++ for ip := range podAddresses(sentinelList) { ++ known[ip] = true ++ } ++ } ++ port := getRedisPort(rf.Spec.Redis.Port) ++ logger := r.logger.WithField("redisfailover", rf.ObjectMeta.Name).WithField("namespace", rf.ObjectMeta.Namespace) ++ ++ if !applied.internal { ++ logger.Infof("Introducing the internal redis user on %d running servers", len(pods)) ++ if err := r.introduceInternalUser(pods, sentinels, rf.MasterName(), port, desired, applied.password, creds, tlsConfig); err != nil { ++ return fmt.Errorf("%w: %v", ErrPasswordRotationPending, err) ++ } ++ } ++ if !applied.exporter { ++ logger.Infof("Introducing the exporter's redis user on %d running servers", len(pods)) ++ if err := r.introduceExporterUser(pods, port, desired, applied.password, creds, tlsConfig); err != nil { ++ return fmt.Errorf("%w: %v", ErrPasswordRotationPending, err) ++ } ++ } ++ ++ rotating := creds.previous != "" || creds.issuedFor != passwordHash(desired) ++ // Outside a rotation, every pass checks that the tenant's default user ++ // moved nothing; a rotation sets all of it anyway. ++ steady := applied.internal && !rotating ++ drifted := map[string]bool{} ++ stale := "" ++ onDesired := true ++ for _, pod := range pods { ++ ip := pod.Status.PodIP ++ auth, err := r.authenticate(ip, port, desired, applied.password, tlsConfig) ++ if err != nil { ++ onDesired = false ++ if redis.IsAuthError(err) && stale == "" { ++ stale = pod.Name ++ } else if !redis.IsAuthError(err) { ++ logger.Warningf("Could not reach redis %s to check its password: %v", ip, err) ++ } ++ continue ++ } ++ if steady { ++ r.reassertInternalUser(ip, port, auth, creds, sentinels, drifted, tlsConfig, logger) ++ } ++ if auth == desired { ++ continue ++ } ++ if err := r.changeClientPassword(ip, port, auth, desired, creds, tlsConfig, logger); err != nil { ++ onDesired = false ++ logger.Warningf("Could not apply the client password on %s: %v", ip, err) ++ } ++ } ++ for _, sentinel := range sentinels { ++ sip := sentinel.Status.PodIP ++ if !drifted[sip] { ++ continue ++ } ++ logger.Warningf("Sentinel %s does not authenticate as the internal user, setting its auth-user and auth-pass again", sip) ++ if err := r.redisClient.SetSentinelAuth(sip, rf.MasterName(), internalUser, creds.link, tlsConfig); err != nil { ++ logger.Warningf("Could not set the auth of Sentinel %s: %v", sip, err) ++ } ++ } ++ ++ target := guardTarget{ ++ master: rf.MasterName(), ++ port: port, ++ auth: desired, ++ pod: creds.pod, ++ links: creds.links(), ++ servers: podIPs(pods), ++ sentinels: podIPs(sentinels), ++ tlsConfig: tlsConfig, ++ } ++ if creds.previous == "" { ++ target.sentinelLink = creds.link ++ } ++ var result error ++ switch { ++ case !rotating: ++ case !onDesired: ++ // Until every server refuses the old client password, its holders ++ // could read the new link password: do not put it in masterauth yet. ++ result = fmt.Errorf("%w: not every running server is on the new client password yet", ErrPasswordRotationPending) ++ default: ++ // A rotation resumed after the client password changed again was ++ // issued under the one before: holders of that one may have read it, ++ // so a second rotation follows at once. ++ for i := 0; i < 2 && (creds.previous != "" || creds.issuedFor != passwordHash(desired)); i++ { ++ if err := r.rotateLinkPassword(rf, pods, sentinels, known, port, desired, &creds, &target, tlsConfig, logger); err != nil { ++ result = fmt.Errorf("%w: rotating the link password: %v", ErrPasswordRotationPending, err) ++ break ++ } ++ } ++ } ++ r.guard.track(rf, target) ++ ++ if stale != "" { ++ logger.Warningf("Redis pod %s accepts neither the current nor the previous client password, restarting it to read the current config", stale) ++ if err := r.k8sService.DeletePod(rf.Namespace, stale); err != nil { ++ logger.Warningf("Could not delete redis pod %s: %v", stale, err) ++ } ++ } ++ return result ++} ++ ++// changeClientPassword moves one server from the client password auth onto ++// desired, and leaves no connection open that authenticated with auth or ++// with anything a holder of auth could have set. In one MULTI/EXEC, so no ++// other client runs a command between its steps: ++// ++// - the internal, exporter and pinger users are reset to what the operator ++// sets, which drops any password or command a holder of auth added to ++// them; ++// - every ACL user but operatorUsers is deleted, which disconnects whoever ++// is authenticated as it; ++// - requirepass becomes desired; ++// - every connection authenticated as the default user is killed, the ++// transaction's own aside (CLIENT KILL skips the caller unless told ++// otherwise), and so is every connection of the exporter user, the one ++// operator user that may read requirepass. ++// ++// The internal user's replication and Sentinel links and the liveness ++// probe's pinger stay up: neither user may read a configuration parameter, ++// so a connection a holder of auth opened as them learns nothing of ++// desired. Done only for a server still on auth, the step cannot happen ++// twice; one that fails changes nothing and is retried by the next pass. ++func (r *RedisFailoverHealer) changeClientPassword(ip, port, auth, desired string, creds internalCreds, tlsConfig *tls.Config, logger log.Logger) error { ++ users, err := r.redisClient.ListUsers(ip, port, auth, tlsConfig) ++ if err != nil { ++ return fmt.Errorf("list the ACL users on %s: %w", ip, err) ++ } ++ var foreign []string ++ for _, u := range users { ++ if !operatorUsers[u] { ++ foreign = append(foreign, u) ++ } ++ } ++ reset := []redis.ACLUser{ ++ {Name: internalUser, Rules: internalUserRules(creds.pod, creds.links()...)}, ++ {Name: exporterUser, Rules: exporterUserRules(creds.exporter)}, ++ {Name: pingerUser, Rules: pingerUserRules()}, ++ } ++ if err := r.redisClient.ChangeClientPassword(ip, port, auth, desired, reset, foreign, []string{"default", exporterUser}, tlsConfig); err != nil { ++ return fmt.Errorf("change the client password: %w", err) ++ } ++ logger.Infof("Applied the client password on %s and disconnected its clients", ip) ++ // A user created between ACL USERS and EXEC: its creator was disconnected ++ // by the transaction, the user goes now. ++ return r.purgeForeignUsers(ip, port, desired, tlsConfig, logger) ++} ++ ++// rotateLinkPassword replaces the link password, with no restart and no ++// moment where a server, replica or Sentinel holds a password another server ++// refuses. Each step runs on every running server or Sentinel and must ++// succeed on all of them before the next one starts; a failure ends the pass ++// and the next pass starts again from the first step not recorded in the ++// internal Secret: ++// ++// 1. Generate the new password into the Secret, keeping the old one as ++// link-previous, and record which client password it is issued under. ++// 2. Every server accepts both: ACL SETUSER with the pod password and both ++// link passwords. ++// 3. Every server replicates with the new one (masteruser/masterauth). ++// 4. Every Sentinel authenticates with the new one (SENTINEL SET). ++// 5. Every server drops the old one from the ACL, and every ACL user but ++// operatorUsers (purgeForeignUsers). ++// 6. Every server disconnects the strangers among the operator users' ++// connections and every MONITOR (killStrayClients). ++// 7. The Secret drops link-previous. ++// ++// Steps 2 to 6 read before they write, so a step done in an earlier pass is ++// only checked again. The caller runs it only once every running server ++// refuses the old client password, so whoever can read the new link ++// password from masterauth holds the current client password. ++func (r *RedisFailoverHealer) rotateLinkPassword(rf *redisfailoverv1.RedisFailover, pods, sentinels []corev1.Pod, known map[string]bool, port, desired string, creds *internalCreds, target *guardTarget, tlsConfig *tls.Config, logger log.Logger) error { ++ if creds.previous == "" { ++ next, err := randomPassword(32) ++ if err != nil { ++ return err ++ } ++ issuedFor := passwordHash(desired) ++ if err := updateInternalSecret(r.k8sService, rf, func(d map[string][]byte) { ++ d[linkPreviousKey] = []byte(creds.link) ++ d[linkPasswordKey] = []byte(next) ++ d[linkIssuedForKey] = []byte(issuedFor) ++ }); err != nil { ++ return fmt.Errorf("record the new link password: %w", err) ++ } ++ creds.previous, creds.link, creds.issuedFor = creds.link, next, issuedFor ++ logger.Infof("Rotating the link password of the internal user on %d servers and %d Sentinels", len(pods), len(sentinels)) ++ } ++ // The guard keeps both until the old one is dropped below. ++ target.links = creds.links() ++ target.sentinelLink = "" ++ ++ for _, pod := range pods { ++ if err := r.ensureInternalUser(pod.Status.PodIP, port, desired, creds.pod, creds.links(), tlsConfig); err != nil { ++ return err ++ } ++ } ++ // The new password is valid everywhere from here to the end. ++ target.sentinelLink = creds.link ++ ++ for _, pod := range pods { ++ ip := pod.Status.PodIP ++ user, password, err := r.redisClient.GetMasterAuth(ip, port, desired, tlsConfig) ++ if err != nil { ++ return fmt.Errorf("read masteruser on %s: %w", ip, err) ++ } ++ if user == internalUser && password == creds.link { ++ continue ++ } ++ if err := r.redisClient.SetMasterAuth(ip, port, desired, internalUser, creds.link, tlsConfig); err != nil { ++ return fmt.Errorf("replicate with the new link password on %s: %w", ip, err) ++ } ++ } ++ ++ // SENTINEL SET offers no way to read auth-pass back, so this is redone ++ // until the rotation is recorded as finished. ++ for _, sentinel := range sentinels { ++ sip := sentinel.Status.PodIP ++ if err := r.redisClient.SetSentinelAuth(sip, rf.MasterName(), internalUser, creds.link, tlsConfig); err != nil { ++ return fmt.Errorf("point the Sentinel %s at the new link password: %w", sip, err) ++ } ++ } ++ ++ target.links = []string{creds.link} ++ for _, pod := range pods { ++ if err := r.ensureInternalUser(pod.Status.PodIP, port, desired, creds.pod, []string{creds.link}, tlsConfig); err != nil { ++ return err ++ } ++ } ++ ++ for _, pod := range pods { ++ if err := r.purgeForeignUsers(pod.Status.PodIP, port, desired, tlsConfig, logger); err != nil { ++ return err ++ } ++ } ++ ++ for _, pod := range pods { ++ if err := r.killStrayClients(pod.Status.PodIP, port, desired, known, tlsConfig, logger); err != nil { ++ return err ++ } ++ } ++ ++ if err := updateInternalSecret(r.k8sService, rf, func(d map[string][]byte) { ++ delete(d, linkPreviousKey) ++ }); err != nil { ++ return fmt.Errorf("record the end of the rotation: %w", err) ++ } ++ creds.previous = "" ++ logger.Infof("Rotated the link password of the internal user") ++ return nil ++} ++ ++// killStrayClients disconnects, on one server, every connection a holder of ++// an old password could have kept through the change: one authenticated as ++// an operator user from an address that is no pod of the RedisFailover and ++// not the pod itself (a SYNC or PSYNC started with a link password read from ++// masterauth streams every write after a revoke, and the link rotation does ++// not close it), and every connection in MONITOR mode, flag O in CLIENT LIST ++// (catClientInfoString in networking.c of Redis 7.2.7 and 8.0.2 and Valkey ++// 8.0.2), whatever its user: MONITOR is checked by ACL once, when it starts, ++// so one opened as a user that was widened then outlives the reset. Run ++// after the old link password is gone, nobody can open such a connection ++// again without the current client password; run again, it finds nothing. ++func (r *RedisFailoverHealer) killStrayClients(ip, port, auth string, known map[string]bool, tlsConfig *tls.Config, logger log.Logger) error { ++ clients, err := r.redisClient.ListClients(ip, port, auth, tlsConfig) ++ if err != nil { ++ return fmt.Errorf("list the clients of %s: %w", ip, err) ++ } ++ var stray []string ++ for _, c := range clients { ++ monitor := strings.Contains(c.Flags, "O") ++ stranger := operatorUsers[c.User] && c.User != "default" && !known[c.Host] && !isLocalAddress(c.Host) ++ if monitor || stranger { ++ stray = append(stray, c.ID) ++ logger.Warningf("Disconnecting client %s of %s: user %s from %s, flags %s", c.ID, ip, c.User, c.Host, c.Flags) ++ } ++ } ++ if len(stray) == 0 { ++ return nil ++ } ++ if err := r.redisClient.KillClients(ip, port, auth, stray, tlsConfig); err != nil { ++ return fmt.Errorf("disconnect clients %v of %s: %w", stray, ip, err) ++ } ++ return nil ++} ++ ++// isLocalAddress tells a connection from inside the pod, as the probes, the ++// shutdown hook and the exporter make, over loopback or a unix socket. ++func isLocalAddress(host string) bool { ++ if strings.HasPrefix(host, "/") { ++ return true ++ } ++ parsed := net.ParseIP(host) ++ return parsed != nil && parsed.IsLoopback() ++} ++ ++// podAddresses is the IP of every pod in list that has one. ++func podAddresses(list *corev1.PodList) map[string]bool { ++ out := map[string]bool{} ++ for _, pod := range list.Items { ++ for _, ip := range pod.Status.PodIPs { ++ out[ip.IP] = true ++ } ++ if pod.Status.PodIP != "" { ++ out[pod.Status.PodIP] = true ++ } ++ } ++ return out ++} ++ ++// purgeForeignUsers deletes every ACL user on one server but operatorUsers. ++func (r *RedisFailoverHealer) purgeForeignUsers(ip, port, auth string, tlsConfig *tls.Config, logger log.Logger) error { ++ users, err := r.redisClient.ListUsers(ip, port, auth, tlsConfig) ++ if err != nil { ++ return fmt.Errorf("list the ACL users on %s: %w", ip, err) ++ } ++ var foreign []string ++ for _, u := range users { ++ if !operatorUsers[u] { ++ foreign = append(foreign, u) ++ } ++ } ++ if len(foreign) == 0 { ++ return nil ++ } ++ logger.Warningf("Deleting ACL users the operator did not create on %s: %v", ip, foreign) ++ if err := r.redisClient.DeleteUsers(ip, port, auth, foreign, tlsConfig); err != nil { ++ return fmt.Errorf("delete the ACL users %v on %s: %w", foreign, ip, err) ++ } ++ return nil ++} ++ ++// ensureInternalUser sets the internal user on one server unless it already ++// is exactly internalUserRules(pod, links...). ++func (r *RedisFailoverHealer) ensureInternalUser(ip, port, auth, pod string, links []string, tlsConfig *tls.Config) error { ++ acl, err := r.redisClient.GetUserACL(ip, port, auth, internalUser, tlsConfig) ++ if err != nil { ++ return fmt.Errorf("read the internal user on %s: %w", ip, err) ++ } ++ if internalUserMatches(acl, pod, links...) { ++ return nil ++ } ++ if err := r.redisClient.SetUserACL(ip, port, auth, internalUser, internalUserRules(pod, links...), tlsConfig); err != nil { ++ return fmt.Errorf("set the internal user on %s: %w", ip, err) ++ } ++ return nil ++} ++ ++// reassertInternalUser checks one server against what the operator set and ++// repairs what differs: the exporter user, the internal user (missing, disabled, with another ++// password or a password added next to it, with other rules), and the user ++// and password the server replicates as. It also marks, in drifted, every ++// running Sentinel with a connection to the server authenticated as any ++// other user: the Sentinel's auth-user or auth-pass was changed, and SENTINEL ++// SET offers no way to read them back. Failures are logged and left to the ++// next pass. ++func (r *RedisFailoverHealer) reassertInternalUser(ip, port, auth string, creds internalCreds, sentinels []corev1.Pod, drifted map[string]bool, tlsConfig *tls.Config, logger log.Logger) { ++ if acl, err := r.redisClient.GetUserACL(ip, port, auth, exporterUser, tlsConfig); err != nil { ++ logger.Warningf("Could not read the exporter user on %s: %v", ip, err) ++ } else if !exporterUserMatches(acl, creds.exporter) { ++ logger.Warningf("The exporter user on %s was changed, setting it again", ip) ++ if err := r.redisClient.SetUserACL(ip, port, auth, exporterUser, exporterUserRules(creds.exporter), tlsConfig); err != nil { ++ logger.Warningf("Could not set the exporter user on %s: %v", ip, err) ++ } ++ } ++ ++ acl, err := r.redisClient.GetUserACL(ip, port, auth, internalUser, tlsConfig) ++ if err != nil { ++ logger.Warningf("Could not read the internal user on %s: %v", ip, err) ++ } else if !internalUserMatches(acl, creds.pod, creds.link) { ++ logger.Warningf("The internal user on %s was changed, setting it again", ip) ++ // SetUserACL resets the user first, so a password added next to the ++ // operator's does not stay valid. ++ if err := r.redisClient.SetUserACL(ip, port, auth, internalUser, internalUserRules(creds.pod, creds.link), tlsConfig); err != nil { ++ logger.Warningf("Could not set the internal user on %s: %v", ip, err) ++ } ++ } ++ ++ user, password, err := r.redisClient.GetMasterAuth(ip, port, auth, tlsConfig) ++ if err != nil { ++ logger.Warningf("Could not read masteruser on %s: %v", ip, err) ++ } else if user != internalUser || password != creds.link { ++ logger.Warningf("Redis %s does not replicate as the internal user, setting masteruser and masterauth again", ip) ++ if err := r.redisClient.SetMasterAuth(ip, port, auth, internalUser, creds.link, tlsConfig); err != nil { ++ logger.Warningf("Could not set masteruser on %s: %v", ip, err) ++ } ++ } ++ ++ if len(sentinels) == 0 { ++ return ++ } ++ clients, err := r.redisClient.GetClientUsers(ip, port, auth, tlsConfig) ++ if err != nil { ++ logger.Warningf("Could not list the clients of %s: %v", ip, err) ++ return ++ } ++ for _, sentinel := range sentinels { ++ for _, u := range clients[sentinel.Status.PodIP] { ++ if u != internalUser { ++ drifted[sentinel.Status.PodIP] = true ++ } ++ } ++ } ++} ++ ++// introduceInternalUser creates the internal user on every running server ++// before any of them replicates as it, and points the Sentinels at it only ++// once every server has it. Mid-rotation (a pass that introduced the user ++// and then failed to rotate), the servers and Sentinels take the link ++// password being retired, which the rotation then moves them off. ++func (r *RedisFailoverHealer) introduceInternalUser(pods, sentinels []corev1.Pod, master, port, desired, applied string, creds internalCreds, tlsConfig *tls.Config) error { ++ link := creds.link ++ if creds.previous != "" { ++ link = creds.previous ++ } ++ auths := make([]string, len(pods)) ++ for i, pod := range pods { ++ ip := pod.Status.PodIP ++ auth, err := r.authenticate(ip, port, desired, applied, tlsConfig) ++ if err != nil { ++ return fmt.Errorf("authenticate to %s: %w", ip, err) ++ } ++ auths[i] = auth ++ if err := r.redisClient.SetUserACL(ip, port, auth, internalUser, internalUserRules(creds.pod, creds.links()...), tlsConfig); err != nil { ++ return fmt.Errorf("create the internal user on %s: %w", ip, err) ++ } ++ } ++ for i, pod := range pods { ++ ip := pod.Status.PodIP ++ if err := r.redisClient.SetMasterAuth(ip, port, auths[i], internalUser, link, tlsConfig); err != nil { ++ return fmt.Errorf("replicate as the internal user on %s: %w", ip, err) ++ } ++ } ++ for _, pod := range sentinels { ++ ip := pod.Status.PodIP ++ if err := r.redisClient.SetSentinelAuth(ip, master, internalUser, link, tlsConfig); err != nil { ++ return fmt.Errorf("point the Sentinel %s at the internal user: %w", ip, err) ++ } ++ } ++ return nil ++} ++ ++// introduceExporterUser creates the exporter user on every running server, ++// so the exporter, which runs as the internal user until the ConfigMap has ++// the exporter user, finds it on whichever server it starts next to. ++func (r *RedisFailoverHealer) introduceExporterUser(pods []corev1.Pod, port, desired, applied string, creds internalCreds, tlsConfig *tls.Config) error { ++ for _, pod := range pods { ++ ip := pod.Status.PodIP ++ auth, err := r.authenticate(ip, port, desired, applied, tlsConfig) ++ if err != nil { ++ return fmt.Errorf("authenticate to %s: %w", ip, err) ++ } ++ if err := r.redisClient.SetUserACL(ip, port, auth, exporterUser, exporterUserRules(creds.exporter), tlsConfig); err != nil { ++ return fmt.Errorf("create the exporter user on %s: %w", ip, err) ++ } ++ } ++ return nil ++} ++ ++// authenticate returns which of the client passwords the server accepts, ++// the new one first. An error for which redis.IsAuthError holds means it ++// accepts neither. ++func (r *RedisFailoverHealer) authenticate(ip, port, desired, applied string, tlsConfig *tls.Config) (string, error) { ++ _, err := r.redisClient.GetDefaultUserPasswords(ip, port, desired, tlsConfig) ++ if err == nil || !redis.IsAuthError(err) || applied == "" || applied == desired { ++ return desired, err ++ } ++ if _, err := r.redisClient.GetDefaultUserPasswords(ip, port, applied, tlsConfig); err != nil { ++ return "", err ++ } ++ return applied, nil ++} ++ ++// sentinelAuth is what the Sentinels authenticate to the servers with: the ++// internal user and its link password once the ConfigMap says every server ++// has it, the client password before that and on a bootstrapping ++// RedisFailover. ++func sentinelAuth(s k8s.Services, rf *redisfailoverv1.RedisFailover) (user, password string, err error) { ++ if internalAuthEnabled(rf) { ++ applied, _, err := appliedRedisConfig(s, rf) ++ if err != nil { ++ return "", "", err ++ } ++ if applied.internal { ++ _, creds, err := readInternalCreds(s, rf) ++ if err != nil { ++ return "", "", err ++ } ++ if creds.link != "" { ++ return internalUser, creds.link, nil ++ } ++ } ++ } ++ password, err = k8s.GetRedisPassword(s, rf) ++ return "", password, err ++} ++ ++// useInternalAuth points the REDIS_USER and REDIS_PASSWORD of every ++// container at the internal user, and those of the exporter at the exporter ++// user once exporter says every server has it, so the probes, the shutdown ++// hook and the exporter keep working whatever the client password becomes. ++func useInternalAuth(spec *corev1.PodSpec, rf *redisfailoverv1.RedisFailover, exporter bool) { ++ fix := func(cs []corev1.Container) { ++ for i := range cs { ++ user, key := internalUser, podPasswordKey ++ if exporter && cs[i].Name == exporterContainerName { ++ user, key = exporterUser, exporterPasswordKey ++ } ++ for j := range cs[i].Env { ++ env := &cs[i].Env[j] ++ switch env.Name { ++ case "REDIS_USER": ++ env.Value = user ++ case "REDIS_PASSWORD": ++ env.ValueFrom = &corev1.EnvVarSource{SecretKeyRef: &corev1.SecretKeySelector{ ++ LocalObjectReference: corev1.LocalObjectReference{Name: GetRedisInternalAuthName(rf)}, ++ Key: key, ++ }} ++ } ++ } ++ } ++ } ++ fix(spec.Containers) ++ fix(spec.InitContainers) ++} ++ ++// FailoverMaster moves the master role off the current master with SENTINEL ++// FAILOVER, waits for the Sentinels to name another one, and relabels the ++// pods, so the master Service follows at once rather than at the next check. ++// The pod roll calls it instead of deleting a stale master: the old master ++// is then a replica, and is rolled as one on a later pass, so writes pause ++// only for the switch instead of for failure detection. ++func (r *RedisFailoverHealer) FailoverMaster(rf *redisfailoverv1.RedisFailover) error { ++ tlsConfig, err := tlsConfigFor(r.k8sService, rf) ++ if err != nil { ++ return err ++ } ++ sentinels, err := runningPods(r.k8sService.GetDeploymentPods(rf.Namespace, GetSentinelName(rf))) ++ if err != nil { ++ return err ++ } ++ if len(sentinels) == 0 { ++ return errors.New("no running Sentinel to fail the master over") ++ } ++ sip := sentinels[0].Status.PodIP ++ old, _, err := r.redisClient.GetSentinelMonitor(sip, rf.MasterName(), tlsConfig) ++ if err != nil { ++ return err ++ } ++ r.logger.WithField("redisfailover", rf.ObjectMeta.Name).WithField("namespace", rf.ObjectMeta.Namespace).Infof("Moving the master role off %s before rolling it", old) ++ if err := r.redisClient.SentinelFailover(sip, rf.MasterName(), tlsConfig); err != nil && !strings.Contains(err.Error(), "INPROG") { ++ return err ++ } ++ current := old ++ for deadline := time.Now().Add(failoverTimeout); current == old; { ++ if time.Now().After(deadline) { ++ return fmt.Errorf("the Sentinels still name %s as master %s after the failover", old, failoverTimeout) ++ } ++ time.Sleep(failoverPoll) ++ if current, _, err = r.redisClient.GetSentinelMonitor(sip, rf.MasterName(), tlsConfig); err != nil { ++ return err ++ } ++ } ++ pods, err := runningPods(r.k8sService.GetStatefulSetPods(rf.Namespace, GetRedisName(rf))) ++ if err != nil { ++ return err ++ } ++ // The master label first, so the master Service never selects nothing. ++ for _, pod := range pods { ++ if pod.Status.PodIP == current { ++ if err := r.setMasterLabelIfNecessary(rf.Namespace, pod); err != nil { ++ return err ++ } ++ } ++ } ++ for _, pod := range pods { ++ if pod.Status.PodIP != current { ++ if err := r.setSlaveLabelIfNecessary(rf.Namespace, pod); err != nil { ++ return err ++ } ++ } ++ } ++ return nil ++} ++ ++// Variables so the tests need not wait. ++var ( ++ failoverTimeout = 30 * time.Second ++ failoverPoll = 500 * time.Millisecond ++) ++ ++// runningPods keeps the pods that are running, not being deleted, and have ++// an IP, the ones a server or Sentinel can be reached on. ++func runningPods(list *corev1.PodList, err error) ([]corev1.Pod, error) { ++ if err != nil { ++ return nil, err ++ } ++ var pods []corev1.Pod ++ for _, pod := range list.Items { ++ if pod.Status.Phase == corev1.PodRunning && pod.DeletionTimestamp == nil && pod.Status.PodIP != "" { ++ pods = append(pods, pod) ++ } ++ } ++ return pods, nil ++} ++ ++func podIPs(pods []corev1.Pod) []string { ++ ips := make([]string, 0, len(pods)) ++ for _, pod := range pods { ++ ips = append(ips, pod.Status.PodIP) ++ } ++ return ips ++} ++ ++// ResolveMultipleMasters settles two or more masters on the one a quorum of ++// the running Sentinels names, by making every other server its replica. ++// That master is where the Sentinels send clients, so the writes the others ++// took since the split are the ones lost, as they would be by hand. With no ++// quorum, or a quorum on a server that is not a master, it changes nothing ++// and returns an error. ++func (r *RedisFailoverHealer) ResolveMultipleMasters(rf *redisfailoverv1.RedisFailover) error { ++ tlsConfig, err := tlsConfigFor(r.k8sService, rf) ++ if err != nil { ++ return err ++ } ++ sentinels, err := runningPods(r.k8sService.GetDeploymentPods(rf.Namespace, GetSentinelName(rf))) ++ if err != nil { ++ return err ++ } ++ votes := map[string]int{} ++ for _, sentinel := range sentinels { ++ ip, _, err := r.redisClient.GetSentinelMonitor(sentinel.Status.PodIP, rf.MasterName(), tlsConfig) ++ if err != nil { ++ continue ++ } ++ votes[ip]++ ++ } ++ quorum := int(getQuorum(rf)) ++ chosen := "" ++ for ip, n := range votes { ++ if n >= quorum { ++ chosen = ip ++ } ++ } ++ if chosen == "" { ++ return fmt.Errorf("no master is named by a quorum of %d Sentinels (votes %v)", quorum, votes) ++ } ++ pods, err := runningPods(r.k8sService.GetStatefulSetPods(rf.Namespace, GetRedisName(rf))) ++ if err != nil { ++ return err ++ } ++ password, err := k8s.GetRedisPassword(r.k8sService, rf) ++ if err != nil { ++ return err ++ } ++ port := getRedisPort(rf.Spec.Redis.Port) ++ known := false ++ for _, pod := range pods { ++ if pod.Status.PodIP == chosen { ++ known = true ++ } ++ } ++ if !known { ++ return fmt.Errorf("the Sentinels name %s, which is no running redis pod", chosen) ++ } ++ if isMaster, err := r.redisClient.IsMaster(chosen, port, password, tlsConfig); err != nil || !isMaster { ++ return fmt.Errorf("the Sentinels name %s, which is not a master (%v)", chosen, err) ++ } ++ r.logger.WithField("redisfailover", rf.ObjectMeta.Name).WithField("namespace", rf.ObjectMeta.Namespace).Warningf("More than one master; a quorum of Sentinels names %s, making the others its replicas", chosen) ++ for _, pod := range pods { ++ ip := pod.Status.PodIP ++ if ip == chosen { ++ continue ++ } ++ isMaster, err := r.redisClient.IsMaster(ip, port, password, tlsConfig) ++ if err != nil { ++ return err ++ } ++ if !isMaster { ++ continue ++ } ++ if err := r.redisClient.MakeSlaveOfWithPort(ip, port, chosen, port, password, tlsConfig); err != nil { ++ return err ++ } ++ } ++ return nil ++} ++ ++// internalUserGuard re-asserts the internal user between reconcile passes. ++// A tenant's ACL DELUSER rf-internal on the master makes the Sentinels fail ++// it over once their links have gone without a valid reply for ++// down-after-milliseconds (5 s by default); the reconcile pass comes every ++// 30 s. The guard checks every server every guardInterval with only what ++// the last pass left in memory, so it costs no API call, and puts the user ++// back early enough for the Sentinels' reconnect to authenticate. ++type internalUserGuard struct { ++ mu sync.Mutex ++ targets map[string]guardTarget ++ // locks holds, per RedisFailover, the lock a reconcile pass and the ++ // guard both take, so the guard never acts on what a rotation is ++ // changing under it. ++ locks map[string]*sync.Mutex ++} ++ ++func guardKey(rf *redisfailoverv1.RedisFailover) string { ++ return rf.Namespace + "/" + rf.Name ++} ++ ++// lock takes the lock of one RedisFailover and returns its unlock. ++func (g *internalUserGuard) lock(key string) func() { ++ g.mu.Lock() ++ m, ok := g.locks[key] ++ if !ok { ++ m = &sync.Mutex{} ++ g.locks[key] = m ++ } ++ g.mu.Unlock() ++ m.Lock() ++ return m.Unlock ++} ++ ++// guardTarget is what the last pass left: the internal user must have the ++// pod password and exactly the link passwords in links (two during a ++// rotation). sentinelLink is the link password valid on every server, to ++// re-send to the Sentinels after a repair, or empty when a rotation stopped ++// before that is known. ++type guardTarget struct { ++ master string ++ port string ++ auth string ++ pod string ++ links []string ++ sentinelLink string ++ servers []string ++ sentinels []string ++ tlsConfig *tls.Config ++ seen time.Time ++} ++ ++var ( ++ guardInterval = 2 * time.Second ++ // guardTTL drops a RedisFailover no pass has refreshed for this long, as ++ // after it was deleted or this operator lost the leadership. ++ guardTTL = 5 * time.Minute ++ guardNow = time.Now ++) ++ ++func newInternalUserGuard() *internalUserGuard { ++ return &internalUserGuard{targets: map[string]guardTarget{}, locks: map[string]*sync.Mutex{}} ++} ++ ++func (g *internalUserGuard) track(rf *redisfailoverv1.RedisFailover, t guardTarget) { ++ t.seen = guardNow() ++ g.mu.Lock() ++ defer g.mu.Unlock() ++ g.targets[guardKey(rf)] = t ++} ++ ++func (g *internalUserGuard) forget(rf *redisfailoverv1.RedisFailover) { ++ g.mu.Lock() ++ defer g.mu.Unlock() ++ delete(g.targets, guardKey(rf)) ++} ++ ++func (g *internalUserGuard) snapshot() map[string]guardTarget { ++ g.mu.Lock() ++ defer g.mu.Unlock() ++ out := make(map[string]guardTarget, len(g.targets)) ++ for k, t := range g.targets { ++ if guardNow().Sub(t.seen) > guardTTL { ++ delete(g.targets, k) ++ continue ++ } ++ out[k] = t ++ } ++ return out ++} ++ ++// RunInternalUserGuard calls GuardInternalUsersOnce every guardInterval ++// until stop is closed. ++func (r *RedisFailoverHealer) RunInternalUserGuard(stop <-chan struct{}) { ++ ticker := time.NewTicker(guardInterval) ++ defer ticker.Stop() ++ for { ++ select { ++ case <-stop: ++ return ++ case <-ticker.C: ++ r.GuardInternalUsersOnce() ++ } ++ } ++} ++ ++// GuardInternalUsersOnce deletes every ACL user but operatorUsers and checks ++// the internal user on every server of every tracked RedisFailover, and ++// resets it where it differs. When it reset one, ++// it also sets the auth of every Sentinel again: that drops the Sentinel's ++// links, which may sit unauthenticated since the user went away, so they ++// reconnect and authenticate now instead of after down-after-milliseconds/2. ++// During a rotation the user it restores carries both link passwords, and ++// the Sentinels get only a link password every server accepts. A server it ++// cannot reach, or that no longer takes the password the last pass saw (a ++// mint in between), is left to the next pass. ++func (r *RedisFailoverHealer) GuardInternalUsersOnce() { ++ for key := range r.guard.snapshot() { ++ r.guardOne(key) ++ } ++} ++ ++// guardOne checks one RedisFailover under its lock, with what the last pass ++// left once that pass is over. ++func (r *RedisFailoverHealer) guardOne(key string) { ++ defer r.guard.lock(key)() ++ t, ok := r.guard.snapshot()[key] ++ if !ok { ++ return ++ } ++ repaired := false ++ for _, ip := range t.servers { ++ if err := r.purgeForeignUsers(ip, t.port, t.auth, t.tlsConfig, r.logger); err != nil { ++ r.logger.Warningf("Could not delete foreign ACL users of %s: %v", key, err) ++ } ++ acl, err := r.redisClient.GetUserACL(ip, t.port, t.auth, internalUser, t.tlsConfig) ++ if err != nil || internalUserMatches(acl, t.pod, t.links...) { ++ continue ++ } ++ r.logger.Warningf("The internal user on %s of %s was changed, setting it again", ip, key) ++ if err := r.redisClient.SetUserACL(ip, t.port, t.auth, internalUser, internalUserRules(t.pod, t.links...), t.tlsConfig); err != nil { ++ r.logger.Warningf("Could not set the internal user on %s of %s: %v", ip, key, err) ++ continue ++ } ++ repaired = true ++ } ++ if !repaired || t.sentinelLink == "" { ++ return ++ } ++ for _, sip := range t.sentinels { ++ if err := r.redisClient.SetSentinelAuth(sip, t.master, internalUser, t.sentinelLink, t.tlsConfig); err != nil { ++ r.logger.Warningf("Could not set the auth of Sentinel %s of %s: %v", sip, key, err) ++ } ++ } ++} +diff --git a/operator/redisfailover/service/password_test.go b/operator/redisfailover/service/password_test.go +new file mode 100644 +index 0000000..a5e2f50 +--- /dev/null ++++ b/operator/redisfailover/service/password_test.go +@@ -0,0 +1,696 @@ ++package service_test ++ ++import ( ++ "crypto/sha256" ++ "encoding/hex" ++ "errors" ++ "fmt" ++ "strings" ++ "testing" ++ "time" ++ ++ "github.com/stretchr/testify/assert" ++ "github.com/stretchr/testify/mock" ++ appsv1 "k8s.io/api/apps/v1" ++ corev1 "k8s.io/api/core/v1" ++ apierrors "k8s.io/apimachinery/pkg/api/errors" ++ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ++ "k8s.io/apimachinery/pkg/runtime/schema" ++ ++ redisfailoverv1 "github.com/freshworks/redis-operator/api/redisfailover/v1" ++ "github.com/freshworks/redis-operator/log" ++ "github.com/freshworks/redis-operator/metrics" ++ mK8SService "github.com/freshworks/redis-operator/mocks/service/k8s" ++ mRedisService "github.com/freshworks/redis-operator/mocks/service/redis" ++ rfservice "github.com/freshworks/redis-operator/operator/redisfailover/service" ++ "github.com/freshworks/redis-operator/service/redis" ++) ++ ++const ( ++ oldPassword = "old-password" ++ newPassword = "new-password" ++ internalPassword = "internal-password" ++ linkPassword = "link-password" ++ exporterPassword = "exporter-password" ++ authSecret = "redis-auth" ++ internalSecret = "rfr-test-internal" ++) ++ ++var wrongPass = errors.New("WRONGPASS invalid username-password pair or user is disabled.") ++ ++func sha(p string) string { ++ sum := sha256.Sum256([]byte(p)) ++ return hex.EncodeToString(sum[:]) ++} ++ ++func authRF() *redisfailoverv1.RedisFailover { ++ rf := generateRF() ++ rf.Spec.Auth.SecretPath = authSecret ++ return rf ++} ++ ++func runningPod(name, ip string) corev1.Pod { ++ return corev1.Pod{ ++ ObjectMeta: metav1.ObjectMeta{Name: name}, ++ Status: corev1.PodStatus{Phase: corev1.PodRunning, PodIP: ip}, ++ } ++} ++ ++// redisConf is the redis.conf the ConfigMap holds: the client password and, ++// with internal set, the internal user with internal as its pod password and ++// linkPassword as its link password, and the exporter user with ++// exporterPassword. ++func redisConf(rf *redisfailoverv1.RedisFailover, client, internal string) string { ++ link, exporter := "", "" ++ if internal != "" { ++ link, exporter = linkPassword, exporterPassword ++ } ++ return rfservice.GenerateRedisConfigMapForTest(rf, nil, nil, client, internal, link, exporter).Data["redis.conf"] ++} ++ ++// redisConfWithoutExporter is the redis.conf of an operator version whose ++// exporter ran as the internal user. ++func redisConfWithoutExporter(rf *redisfailoverv1.RedisFailover, client string) string { ++ return rfservice.GenerateRedisConfigMapForTest(rf, nil, nil, client, internalPassword, linkPassword, "").Data["redis.conf"] ++} ++ ++// authServices serves the client Secret, the internal Secret (unless ++// internal is empty) with linkPassword issued under the client password, the ++// redis ConfigMap (unless conf is empty), two running redis pods next to a ++// pending one, and two running Sentinels. ++func authServices(rf *redisfailoverv1.RedisFailover, client, internal, conf string) *mK8SService.Services { ++ ms := &mK8SService.Services{} ++ ms.On("GetSecret", namespace, authSecret).Return(&corev1.Secret{Data: map[string][]byte{"password": []byte(client)}}, nil) ++ if internal != "" { ++ ms.On("GetSecret", namespace, internalSecret).Return(&corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: internalSecret}, Data: map[string][]byte{ ++ "password": []byte(internal), ++ "exporter": []byte(exporterPassword), ++ "link": []byte(linkPassword), ++ "client-sha256": []byte(sha(client)), ++ }}, nil) ++ } else { ++ ms.On("GetSecret", namespace, internalSecret).Return(nil, apierrors.NewNotFound(schema.GroupResource{}, "")) ++ } ++ if conf != "" { ++ ms.On("GetConfigMap", namespace, rfservice.GetRedisName(rf)).Return(&corev1.ConfigMap{Data: map[string]string{"redis.conf": conf}}, nil) ++ } else { ++ ms.On("GetConfigMap", namespace, rfservice.GetRedisName(rf)).Return(nil, apierrors.NewNotFound(schema.GroupResource{}, "")) ++ } ++ ms.On("GetStatefulSetPods", namespace, rfservice.GetRedisName(rf)).Return(&corev1.PodList{Items: []corev1.Pod{ ++ runningPod("rfr-0", "10.0.0.1"), ++ runningPod("rfr-1", "10.0.0.2"), ++ {ObjectMeta: metav1.ObjectMeta{Name: "rfr-2"}, Status: corev1.PodStatus{Phase: corev1.PodPending}}, ++ }}, nil) ++ ms.On("GetDeploymentPods", namespace, rfservice.GetSentinelName(rf)).Return(&corev1.PodList{Items: []corev1.Pod{ ++ runningPod("rfs-0", "10.0.1.1"), ++ runningPod("rfs-1", "10.0.1.2"), ++ }}, nil) ++ return ms ++} ++ ++// recorder keeps the order of the calls that change a server or Sentinel. ++type recorder []string ++ ++func (r *recorder) add(format string, args ...interface{}) func(mock.Arguments) { ++ return func(mock.Arguments) { *r = append(*r, fmt.Sprintf(format, args...)) } ++} ++ ++// internalCommandRules is spelled out rather than derived, so a change to ++// what the internal user may run shows up here. ++// It reads no configuration parameter: CONFIG GET is the exporter's alone. ++const internalCommandRules = "-@all +ping +info +psync +sync +replconf +client|setname +client|kill +subscribe +publish +multi +exec +slaveof +config|rewrite +script|kill +save" ++ ++// exporterCommandRules is spelled out for the same reason. ++const exporterCommandRules = "-@all +client|setname +config|get +info +latency|latest +latency|histogram +slowlog|len +slowlog|get" ++ ++var exporterRules = strings.Fields("on #" + sha(exporterPassword) + " resetkeys resetchannels " + exporterCommandRules) ++ ++var pingerRules = strings.Fields("on #" + sha("pingpass") + " resetkeys resetchannels -@all +ping") ++ ++// intactExporterACL is what ACL GETUSER reports for an untouched exporter ++// user. ++var intactExporterACL = redis.UserACL{Exists: true, On: true, Hashes: []string{sha(exporterPassword)}, Commands: exporterCommandRules} ++ ++var internalRules = strings.Fields("on #" + sha(internalPassword) + " #" + sha(linkPassword) + " resetkeys resetchannels &__sentinel__:hello " + internalCommandRules) ++ ++// intactACL is what ACL GETUSER reports for an untouched internal user. ++var intactACL = redis.UserACL{Exists: true, On: true, Hashes: []string{sha(internalPassword), sha(linkPassword)}, Keys: "", Channels: "&__sentinel__:hello", Commands: internalCommandRules} ++ ++// sentinelClients is a server's CLIENT LIST as both running Sentinels leave ++// it when they authenticate as the internal user. ++var sentinelClients = map[string][]string{"10.0.1.1": {"rf-internal", "rf-internal"}, "10.0.1.2": {"rf-internal", "rf-internal"}} ++ ++// intactServer answers the per-pass checks of a server nothing tampered with. ++func intactServer(mr *mRedisService.Client, ip, auth string) { ++ mr.On("GetUserACL", ip, "0", auth, "rf-exporter", mock.Anything).Return(intactExporterACL, nil) ++ mr.On("GetUserACL", ip, "0", auth, "rf-internal", mock.Anything).Return(intactACL, nil) ++ mr.On("GetMasterAuth", ip, "0", auth, mock.Anything).Return("rf-internal", linkPassword, nil) ++ mr.On("GetClientUsers", ip, "0", auth, mock.Anything).Return(sentinelClients, nil) ++} ++ ++func TestReconcileRedisAuthOnANewRedisFailoverCreatesTheInternalSecretOnly(t *testing.T) { ++ assert := assert.New(t) ++ rf := authRF() ++ ms := authServices(rf, newPassword, "", "") ++ owner := []metav1.OwnerReference{{Name: "test"}} ++ var created *corev1.Secret ++ ms.On("CreateSecret", namespace, mock.Anything).Once().Run(func(args mock.Arguments) { ++ created = args.Get(1).(*corev1.Secret) ++ }).Return(nil) ++ ++ mr := &mRedisService.Client{} ++ healer := rfservice.NewRedisFailoverHealer(ms, mr, log.Dummy) ++ assert.NoError(healer.ReconcileRedisAuth(rf, map[string]string{"app": "x"}, owner)) ++ if assert.NotNil(created) { ++ assert.Equal(internalSecret, created.Name) ++ assert.Len(string(created.Data["password"]), 32) ++ assert.Len(string(created.Data["link"]), 32) ++ assert.Len(string(created.Data["exporter"]), 32) ++ assert.NotEqual(string(created.Data["password"]), string(created.Data["link"])) ++ assert.NotEqual(string(created.Data["password"]), string(created.Data["exporter"])) ++ assert.Equal(sha(newPassword), string(created.Data["client-sha256"])) ++ assert.NotContains(created.Data, "link-previous") ++ assert.Equal(owner, created.OwnerReferences) ++ } ++ assert.Empty(mr.Calls, "a new RedisFailover has no server to touch") ++} ++ ++// An existing RedisFailover: every server gets the internal user before any ++// replicates as it, and the Sentinels move to it last. ++func TestReconcileRedisAuthIntroducesTheInternalUser(t *testing.T) { ++ assert := assert.New(t) ++ rf := authRF() ++ ms := authServices(rf, newPassword, internalPassword, redisConf(rf, newPassword, "")) ++ var calls recorder ++ ++ mr := &mRedisService.Client{} ++ mr.On("GetDefaultUserPasswords", mock.Anything, "0", newPassword, mock.Anything).Return(redis.DefaultUserPasswords{Hashes: []string{sha(newPassword)}}, nil) ++ for _, ip := range []string{"10.0.0.1", "10.0.0.2"} { ++ mr.On("SetUserACL", ip, "0", newPassword, "rf-internal", internalRules, mock.Anything).Run(calls.add("acl %s", ip)).Return(nil) ++ mr.On("SetMasterAuth", ip, "0", newPassword, "rf-internal", linkPassword, mock.Anything).Run(calls.add("masterauth %s", ip)).Return(nil) ++ mr.On("SetUserACL", ip, "0", newPassword, "rf-exporter", exporterRules, mock.Anything).Run(calls.add("exporter %s", ip)).Return(nil) ++ } ++ for _, ip := range []string{"10.0.1.1", "10.0.1.2"} { ++ mr.On("SetSentinelAuth", ip, rf.MasterName(), "rf-internal", linkPassword, mock.Anything).Run(calls.add("sentinel %s", ip)).Return(nil) ++ } ++ ++ healer := rfservice.NewRedisFailoverHealer(ms, mr, log.Dummy) ++ assert.NoError(healer.ReconcileRedisAuth(rf, nil, nil)) ++ assert.Equal([]string{ ++ "acl 10.0.0.1", "acl 10.0.0.2", ++ "masterauth 10.0.0.1", "masterauth 10.0.0.2", ++ "sentinel 10.0.1.1", "sentinel 10.0.1.2", ++ "exporter 10.0.0.1", "exporter 10.0.0.2", ++ }, []string(calls)) ++ mr.AssertNotCalled(t, "SetCustomRedisConfig", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) ++} ++ ++func TestReconcileRedisAuthPendsWhenAServerCannotTakeTheInternalUser(t *testing.T) { ++ assert := assert.New(t) ++ rf := authRF() ++ ms := authServices(rf, newPassword, internalPassword, redisConf(rf, newPassword, "")) ++ ++ mr := &mRedisService.Client{} ++ mr.On("GetDefaultUserPasswords", "10.0.0.1", "0", newPassword, mock.Anything).Return(redis.DefaultUserPasswords{}, nil) ++ mr.On("SetUserACL", "10.0.0.1", "0", newPassword, "rf-internal", internalRules, mock.Anything).Return(nil) ++ mr.On("GetDefaultUserPasswords", "10.0.0.2", "0", newPassword, mock.Anything).Return(redis.DefaultUserPasswords{}, errors.New("i/o timeout")) ++ ++ healer := rfservice.NewRedisFailoverHealer(ms, mr, log.Dummy) ++ assert.ErrorIs(healer.ReconcileRedisAuth(rf, nil, nil), rfservice.ErrPasswordRotationPending) ++ mr.AssertNotCalled(t, "SetMasterAuth", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) ++ mr.AssertNotCalled(t, "SetSentinelAuth", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) ++} ++ ++// A server that accepts neither password restarts from the current ++// ConfigMap; one that cannot be reached is left to start from it. ++func TestReconcileRedisAuthRestartsAServerOnAnUnknownPassword(t *testing.T) { ++ assert := assert.New(t) ++ rf := authRF() ++ ms := authServices(rf, newPassword, internalPassword, redisConf(rf, newPassword, internalPassword)) ++ ms.On("DeletePod", namespace, "rfr-0").Once().Return(nil) ++ ++ mr := &mRedisService.Client{} ++ mr.On("GetDefaultUserPasswords", "10.0.0.1", "0", newPassword, mock.Anything).Return(redis.DefaultUserPasswords{}, wrongPass) ++ mr.On("GetDefaultUserPasswords", "10.0.0.2", "0", newPassword, mock.Anything).Return(redis.DefaultUserPasswords{}, errors.New("connection refused")) ++ ++ healer := rfservice.NewRedisFailoverHealer(ms, mr, log.Dummy) ++ assert.NoError(healer.ReconcileRedisAuth(rf, nil, nil)) ++ ms.AssertCalled(t, "DeletePod", namespace, "rfr-0") ++ ms.AssertNumberOfCalls(t, "DeletePod", 1) ++} ++ ++func TestReconcileRedisAuthLeavesOtherRedisFailoversAlone(t *testing.T) { ++ for name, rf := range map[string]*redisfailoverv1.RedisFailover{ ++ "authentication off": generateRF(), ++ "bootstrapping": func() *redisfailoverv1.RedisFailover { ++ rf := authRF() ++ rf.Spec.BootstrapNode = &redisfailoverv1.BootstrapSettings{Host: "10.1.1.1"} ++ return rf ++ }(), ++ } { ++ t.Run(name, func(t *testing.T) { ++ ms := &mK8SService.Services{} ++ mr := &mRedisService.Client{} ++ healer := rfservice.NewRedisFailoverHealer(ms, mr, log.Dummy) ++ assert.NoError(t, healer.ReconcileRedisAuth(rf, nil, nil)) ++ assert.Empty(t, ms.Calls) ++ assert.Empty(t, mr.Calls) ++ }) ++ } ++} ++ ++func TestRedisConfigReplicatesAsTheInternalUser(t *testing.T) { ++ assert := assert.New(t) ++ rf := authRF() ++ conf := redisConf(rf, newPassword, internalPassword) ++ assert.Contains(conf, "\nmasteruser rf-internal\nmasterauth "+linkPassword+"\nrequirepass "+newPassword+"\n") ++ assert.Contains(conf, "\nuser rf-internal on #"+sha(internalPassword)+" #"+sha(linkPassword)+" resetkeys resetchannels &__sentinel__:hello "+internalCommandRules+"\n") ++ assert.True(strings.HasSuffix(conf, "\nuser rf-exporter on #"+sha(exporterPassword)+" resetkeys resetchannels "+exporterCommandRules), conf) ++ assert.NotContains(conf, "masterauth "+newPassword, "replication must not depend on the client password") ++ assert.NotContains(conf, internalPassword, "the pod password is on the servers as a hash only") ++ assert.NotContains(conf, exporterPassword, "the exporter password is on the servers as a hash only") ++ ++ // Without the internal password (bootstrapping), the upstream layout. ++ conf = redisConf(rf, newPassword, "") ++ assert.Contains(conf, "\nmasterauth "+newPassword+"\nrequirepass "+newPassword) ++ assert.NotContains(conf, "rf-internal") ++} ++ ++func TestEnsureRedisStatefulsetMovesThePodsToTheInternalUserOnceTheConfigHasIt(t *testing.T) { ++ type auth struct{ user, secret, key string } ++ tests := map[string]struct { ++ conf func(*redisfailoverv1.RedisFailover) string ++ redis auth ++ exporter auth ++ }{ ++ "config without the internal user": { ++ conf: func(rf *redisfailoverv1.RedisFailover) string { return redisConf(rf, newPassword, "") }, ++ redis: auth{"default", authSecret, "password"}, ++ exporter: auth{"default", authSecret, "password"}, ++ }, ++ // The exporter user is not on every server yet: the exporter stays ++ // on the internal user. ++ "config without the exporter user": { ++ conf: func(rf *redisfailoverv1.RedisFailover) string { return redisConfWithoutExporter(rf, newPassword) }, ++ redis: auth{"rf-internal", internalSecret, "password"}, ++ exporter: auth{"rf-internal", internalSecret, "password"}, ++ }, ++ "config with both users": { ++ conf: func(rf *redisfailoverv1.RedisFailover) string { return redisConf(rf, newPassword, internalPassword) }, ++ redis: auth{"rf-internal", internalSecret, "password"}, ++ exporter: auth{"rf-exporter", internalSecret, "exporter"}, ++ }, ++ } ++ for name, test := range tests { ++ t.Run(name, func(t *testing.T) { ++ rf := authRF() ++ rf.Spec.Redis.Exporter.Enabled = true ++ ms := authServices(rf, newPassword, internalPassword, test.conf(rf)) ++ ms.On("GetStatefulSet", namespace, mock.Anything).Return(nil, apierrors.NewNotFound(schema.GroupResource{}, "")) ++ ms.On("CreateOrUpdatePodDisruptionBudget", namespace, mock.Anything).Return(nil) ++ var ss *appsv1.StatefulSet ++ ms.On("CreateOrUpdateStatefulSet", namespace, mock.Anything).Run(func(args mock.Arguments) { ++ ss = args.Get(1).(*appsv1.StatefulSet) ++ }).Return(nil) ++ ++ client := rfservice.NewRedisFailoverKubeClient(ms, log.Dummy, metrics.Dummy, "cluster.local") ++ assert.NoError(t, client.EnsureRedisStatefulset(rf, nil, []metav1.OwnerReference{}, "")) ++ if !assert.NotNil(t, ss) { ++ return ++ } ++ assert.Len(t, ss.Spec.Template.Spec.Containers, 2) ++ for _, c := range ss.Spec.Template.Spec.Containers { ++ var got auth ++ for _, env := range c.Env { ++ switch env.Name { ++ case "REDIS_USER": ++ got.user = env.Value ++ case "REDIS_PASSWORD": ++ got.secret, got.key = env.ValueFrom.SecretKeyRef.Name, env.ValueFrom.SecretKeyRef.Key ++ } ++ } ++ want := test.redis ++ if c.Name == "redis-exporter" { ++ want = test.exporter ++ } ++ assert.Equal(t, want, got, c.Name) ++ } ++ // No annotation follows any password, so nothing rolls on a change. ++ for k := range ss.Spec.Template.Annotations { ++ assert.NotContains(t, k, "password") ++ } ++ }) ++ } ++} ++ ++func TestSentinelsAuthenticateAsTheInternalUser(t *testing.T) { ++ assert := assert.New(t) ++ rf := authRF() ++ ms := authServices(rf, newPassword, internalPassword, redisConf(rf, newPassword, internalPassword)) ++ ++ mr := &mRedisService.Client{} ++ mr.On("ResetSentinel", "10.0.1.1", mock.Anything).Once().Return(nil) ++ mr.On("SetSentinelAuth", "10.0.1.1", rf.MasterName(), "rf-internal", linkPassword, mock.Anything).Twice().Return(nil) ++ mr.On("MonitorRedisWithPort", "10.0.1.1", "10.0.0.1", "0", mock.Anything, "", rf.MasterName(), mock.Anything).Once().Return(nil) ++ ++ healer := rfservice.NewRedisFailoverHealer(ms, mr, log.Dummy) ++ assert.NoError(healer.RestoreSentinel("10.0.1.1", rf)) ++ assert.NoError(healer.NewSentinelMonitor("10.0.1.1", "10.0.0.1", rf)) ++ mr.AssertExpectations(t) ++ mr.AssertNotCalled(t, "SetSentinelAuthPass", mock.Anything, mock.Anything, mock.Anything, mock.Anything) ++} ++ ++func TestFailoverMasterMovesTheRoleThenTheLabels(t *testing.T) { ++ assert := assert.New(t) ++ defer rfservice.SetFailoverTiming(time.Second, time.Millisecond)() ++ rf := authRF() ++ ms := authServices(rf, newPassword, internalPassword, redisConf(rf, newPassword, internalPassword)) ++ var calls recorder ++ ms.On("UpdatePodLabels", namespace, "rfr-1", mock.MatchedBy(func(l map[string]string) bool { return l["redisfailovers-role"] == "master" })).Run(calls.add("master rfr-1")).Return(nil) ++ ms.On("UpdatePodLabels", namespace, "rfr-0", mock.MatchedBy(func(l map[string]string) bool { return l["redisfailovers-role"] == "slave" })).Run(calls.add("slave rfr-0")).Return(nil) ++ ++ mr := &mRedisService.Client{} ++ mr.On("GetSentinelMonitor", "10.0.1.1", rf.MasterName(), mock.Anything).Once().Return("10.0.0.1", "6379", nil) ++ mr.On("SentinelFailover", "10.0.1.1", rf.MasterName(), mock.Anything).Run(calls.add("failover")).Once().Return(nil) ++ mr.On("GetSentinelMonitor", "10.0.1.1", rf.MasterName(), mock.Anything).Once().Return("10.0.0.1", "6379", nil) ++ mr.On("GetSentinelMonitor", "10.0.1.1", rf.MasterName(), mock.Anything).Once().Return("10.0.0.2", "6379", nil) ++ ++ healer := rfservice.NewRedisFailoverHealer(ms, mr, log.Dummy) ++ assert.NoError(healer.FailoverMaster(rf)) ++ assert.Equal([]string{"failover", "master rfr-1", "slave rfr-0"}, []string(calls)) ++ ms.AssertNotCalled(t, "DeletePod", mock.Anything, mock.Anything) ++} ++ ++func TestFailoverMasterGivesUpWhenTheRoleDoesNotMove(t *testing.T) { ++ defer rfservice.SetFailoverTiming(20*time.Millisecond, time.Millisecond)() ++ rf := authRF() ++ ms := authServices(rf, newPassword, internalPassword, redisConf(rf, newPassword, internalPassword)) ++ mr := &mRedisService.Client{} ++ mr.On("GetSentinelMonitor", "10.0.1.1", rf.MasterName(), mock.Anything).Return("10.0.0.1", "6379", nil) ++ // A failover already running is waited for, not an error. ++ mr.On("SentinelFailover", "10.0.1.1", rf.MasterName(), mock.Anything).Return(errors.New("INPROG Failover already in progress")) ++ ++ healer := rfservice.NewRedisFailoverHealer(ms, mr, log.Dummy) ++ err := healer.FailoverMaster(rf) ++ if assert.Error(t, err) { ++ assert.True(t, strings.Contains(err.Error(), "still name"), err.Error()) ++ } ++ ms.AssertNotCalled(t, "UpdatePodLabels", mock.Anything, mock.Anything, mock.Anything) ++} ++ ++// The tenant's default user can run ACL, CONFIG and SENTINEL SET. Every pass ++// puts back what it changed: here the internal user got a second password ++// the tenant knows, one server replicates with the tenant's password, and ++// one Sentinel authenticates as default. ++func TestReconcileRedisAuthRepairsTamperedInternalAuth(t *testing.T) { ++ assert := assert.New(t) ++ rf := authRF() ++ ms := authServices(rf, newPassword, internalPassword, redisConf(rf, newPassword, internalPassword)) ++ ++ mr := &mRedisService.Client{} ++ mr.On("GetDefaultUserPasswords", mock.Anything, "0", newPassword, mock.Anything).Return(redis.DefaultUserPasswords{}, nil) ++ ++ tampered := intactACL ++ tampered.Hashes = []string{sha(internalPassword), sha(linkPassword), sha("tenant-added")} ++ mr.On("GetUserACL", mock.Anything, "0", newPassword, "rf-exporter", mock.Anything).Return(intactExporterACL, nil) ++ mr.On("GetUserACL", "10.0.0.1", "0", newPassword, "rf-internal", mock.Anything).Return(tampered, nil) ++ mr.On("SetUserACL", "10.0.0.1", "0", newPassword, "rf-internal", internalRules, mock.Anything).Once().Return(nil) ++ mr.On("GetMasterAuth", "10.0.0.1", "0", newPassword, mock.Anything).Return("rf-internal", linkPassword, nil) ++ mr.On("GetClientUsers", "10.0.0.1", "0", newPassword, mock.Anything).Return(map[string][]string{ ++ "10.0.1.1": {"rf-internal", "rf-internal"}, ++ "10.0.1.2": {"default", "default"}, ++ "10.0.9.9": {"default"}, // a tenant client, not a Sentinel ++ }, nil) ++ ++ mr.On("GetUserACL", "10.0.0.2", "0", newPassword, "rf-internal", mock.Anything).Return(intactACL, nil) ++ mr.On("GetMasterAuth", "10.0.0.2", "0", newPassword, mock.Anything).Return("", newPassword, nil) ++ mr.On("SetMasterAuth", "10.0.0.2", "0", newPassword, "rf-internal", linkPassword, mock.Anything).Once().Return(nil) ++ mr.On("GetClientUsers", "10.0.0.2", "0", newPassword, mock.Anything).Return(sentinelClients, nil) ++ ++ mr.On("SetSentinelAuth", "10.0.1.2", rf.MasterName(), "rf-internal", linkPassword, mock.Anything).Once().Return(nil) ++ ++ healer := rfservice.NewRedisFailoverHealer(ms, mr, log.Dummy) ++ assert.NoError(healer.ReconcileRedisAuth(rf, nil, nil)) ++ mr.AssertExpectations(t) ++ mr.AssertNotCalled(t, "SetUserACL", "10.0.0.2", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) ++ mr.AssertNotCalled(t, "SetMasterAuth", "10.0.0.1", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) ++ mr.AssertNotCalled(t, "SetSentinelAuth", "10.0.1.1", mock.Anything, mock.Anything, mock.Anything, mock.Anything) ++ ms.AssertNotCalled(t, "DeletePod", mock.Anything, mock.Anything) ++} ++ ++// Every way the internal user can differ from what the operator set is a ++// repair, and an untouched one is left alone. ++func TestReconcileRedisAuthRepairsEachKindOfInternalUserDrift(t *testing.T) { ++ cases := map[string]func(*redis.UserACL){ ++ "intact": nil, ++ "deleted": func(a *redis.UserACL) { *a = redis.UserACL{} }, ++ "disabled": func(a *redis.UserACL) { a.On = false }, ++ "nopass": func(a *redis.UserACL) { a.NoPass = true; a.Hashes = nil }, ++ "another password": func(a *redis.UserACL) { a.Hashes = []string{sha("tenant")} }, ++ "link password gone": func(a *redis.UserACL) { a.Hashes = []string{sha(internalPassword)} }, ++ "pod password gone": func(a *redis.UserACL) { a.Hashes = []string{sha(linkPassword)} }, ++ "commands widened": func(a *redis.UserACL) { a.Commands = "+@all" }, ++ "commands narrowed": func(a *redis.UserACL) { a.Commands = "-@all +ping" }, ++ "keys added": func(a *redis.UserACL) { a.Keys = "~*" }, ++ "channels widened": func(a *redis.UserACL) { a.Channels = "&*" }, ++ "channels removed": func(a *redis.UserACL) { a.Channels = "" }, ++ "selector added": func(a *redis.UserACL) { a.Selectors = 1 }, ++ } ++ for name, change := range cases { ++ t.Run(name, func(t *testing.T) { ++ rf := authRF() ++ ms := authServices(rf, newPassword, internalPassword, redisConf(rf, newPassword, internalPassword)) ++ mr := &mRedisService.Client{} ++ mr.On("GetDefaultUserPasswords", mock.Anything, "0", newPassword, mock.Anything).Return(redis.DefaultUserPasswords{}, nil) ++ acl := intactACL ++ acl.Hashes = append([]string(nil), intactACL.Hashes...) ++ if change != nil { ++ change(&acl) ++ } ++ mr.On("GetUserACL", mock.Anything, "0", newPassword, "rf-internal", mock.Anything).Return(acl, nil) ++ mr.On("GetUserACL", mock.Anything, "0", newPassword, "rf-exporter", mock.Anything).Return(intactExporterACL, nil) ++ mr.On("GetMasterAuth", mock.Anything, "0", newPassword, mock.Anything).Return("rf-internal", linkPassword, nil) ++ mr.On("GetClientUsers", mock.Anything, "0", newPassword, mock.Anything).Return(sentinelClients, nil) ++ mr.On("SetUserACL", mock.Anything, "0", newPassword, "rf-internal", internalRules, mock.Anything).Return(nil) ++ ++ healer := rfservice.NewRedisFailoverHealer(ms, mr, log.Dummy) ++ assert.NoError(t, healer.ReconcileRedisAuth(rf, nil, nil)) ++ want := 2 ++ if change == nil { ++ want = 0 ++ } ++ mr.AssertNumberOfCalls(t, "SetUserACL", want) ++ }) ++ } ++} ++ ++// threeSentinels adds a third running Sentinel, so a quorum of two can ++// outvote one. ++func threeSentinels(ms *mK8SService.Services, rf *redisfailoverv1.RedisFailover) { ++ ms.ExpectedCalls = removeCall(ms.ExpectedCalls, "GetDeploymentPods") ++ ms.On("GetDeploymentPods", namespace, rfservice.GetSentinelName(rf)).Return(&corev1.PodList{Items: []corev1.Pod{ ++ runningPod("rfs-0", "10.0.1.1"), ++ runningPod("rfs-1", "10.0.1.2"), ++ runningPod("rfs-2", "10.0.1.3"), ++ }}, nil) ++} ++ ++func removeCall(calls []*mock.Call, method string) []*mock.Call { ++ out := calls[:0] ++ for _, c := range calls { ++ if c.Method != method { ++ out = append(out, c) ++ } ++ } ++ return out ++} ++ ++// The state the stand was left in: both pods masters, two of three ++// Sentinels on 10.0.0.2. The other master becomes its replica. ++func TestResolveMultipleMastersFollowsTheSentinelQuorum(t *testing.T) { ++ assert := assert.New(t) ++ rf := authRF() ++ ms := authServices(rf, newPassword, internalPassword, redisConf(rf, newPassword, internalPassword)) ++ threeSentinels(ms, rf) ++ ++ mr := &mRedisService.Client{} ++ mr.On("GetSentinelMonitor", "10.0.1.1", rf.MasterName(), mock.Anything).Return("10.0.0.2", "0", nil) ++ mr.On("GetSentinelMonitor", "10.0.1.2", rf.MasterName(), mock.Anything).Return("10.0.0.2", "0", nil) ++ mr.On("GetSentinelMonitor", "10.0.1.3", rf.MasterName(), mock.Anything).Return("10.0.0.1", "0", nil) ++ mr.On("IsMaster", "10.0.0.1", "0", newPassword, mock.Anything).Return(true, nil) ++ mr.On("IsMaster", "10.0.0.2", "0", newPassword, mock.Anything).Return(true, nil) ++ mr.On("MakeSlaveOfWithPort", "10.0.0.1", "0", "10.0.0.2", "0", newPassword, mock.Anything).Once().Return(nil) ++ ++ healer := rfservice.NewRedisFailoverHealer(ms, mr, log.Dummy) ++ assert.NoError(healer.ResolveMultipleMasters(rf)) ++ mr.AssertExpectations(t) ++ mr.AssertNotCalled(t, "MakeSlaveOfWithPort", "10.0.0.2", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) ++} ++ ++func TestResolveMultipleMastersChangesNothingWithoutAQuorum(t *testing.T) { ++ assert := assert.New(t) ++ rf := authRF() ++ ms := authServices(rf, newPassword, internalPassword, redisConf(rf, newPassword, internalPassword)) ++ threeSentinels(ms, rf) ++ ++ mr := &mRedisService.Client{} ++ mr.On("GetSentinelMonitor", "10.0.1.1", rf.MasterName(), mock.Anything).Return("10.0.0.2", "0", nil) ++ mr.On("GetSentinelMonitor", "10.0.1.2", rf.MasterName(), mock.Anything).Return("10.0.0.1", "0", nil) ++ mr.On("GetSentinelMonitor", "10.0.1.3", rf.MasterName(), mock.Anything).Return("", "", errors.New("connection refused")) ++ ++ healer := rfservice.NewRedisFailoverHealer(ms, mr, log.Dummy) ++ assert.ErrorContains(healer.ResolveMultipleMasters(rf), "quorum") ++ mr.AssertNotCalled(t, "MakeSlaveOfWithPort", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) ++} ++ ++// trackedHealer runs one untampered reconcile pass, which leaves the ++// RedisFailover with the guard, and returns a fresh redis mock for the ++// guard's own calls. ++func trackedHealer(t *testing.T) (*rfservice.RedisFailoverHealer, *redisfailoverv1.RedisFailover, *mRedisService.Client) { ++ t.Helper() ++ rf := authRF() ++ ms := authServices(rf, newPassword, internalPassword, redisConf(rf, newPassword, internalPassword)) ++ mr := &mRedisService.Client{} ++ mr.On("GetDefaultUserPasswords", mock.Anything, "0", newPassword, mock.Anything).Return(redis.DefaultUserPasswords{}, nil) ++ intactServer(mr, "10.0.0.1", newPassword) ++ intactServer(mr, "10.0.0.2", newPassword) ++ healer := rfservice.NewRedisFailoverHealer(ms, mr, log.Dummy) ++ if err := healer.ReconcileRedisAuth(rf, nil, nil); err != nil { ++ t.Fatal(err) ++ } ++ mr.ExpectedCalls, mr.Calls = nil, nil ++ return healer, rf, mr ++} ++ ++// A tenant's ACL DELUSER rf-internal between passes: the guard puts the user ++// back and makes the Sentinels reconnect, within seconds instead of at the ++// next pass. ++// operatorUserList is what ACL USERS reports on a server nobody added a user ++// to. ++var operatorUserList = []string{"default", "pinger", "rf-exporter", "rf-internal"} ++ ++func TestGuardRestoresADeletedInternalUserBetweenPasses(t *testing.T) { ++ healer, rf, mr := trackedHealer(t) ++ mr.On("ListUsers", mock.Anything, "0", newPassword, mock.Anything).Return(operatorUserList, nil) ++ mr.On("GetUserACL", "10.0.0.1", "0", newPassword, "rf-internal", mock.Anything).Return(redis.UserACL{}, nil) ++ mr.On("GetUserACL", "10.0.0.2", "0", newPassword, "rf-internal", mock.Anything).Return(intactACL, nil) ++ mr.On("SetUserACL", "10.0.0.1", "0", newPassword, "rf-internal", internalRules, mock.Anything).Once().Return(nil) ++ mr.On("SetSentinelAuth", "10.0.1.1", rf.MasterName(), "rf-internal", linkPassword, mock.Anything).Once().Return(nil) ++ mr.On("SetSentinelAuth", "10.0.1.2", rf.MasterName(), "rf-internal", linkPassword, mock.Anything).Once().Return(nil) ++ ++ healer.GuardInternalUsersOnce() ++ mr.AssertExpectations(t) ++} ++ ++func TestGuardLeavesAnIntactUserAndForgetsStaleTargets(t *testing.T) { ++ healer, _, mr := trackedHealer(t) ++ mr.On("ListUsers", mock.Anything, "0", newPassword, mock.Anything).Return(operatorUserList, nil) ++ mr.On("GetUserACL", mock.Anything, "0", newPassword, "rf-internal", mock.Anything).Return(intactACL, nil) ++ healer.GuardInternalUsersOnce() ++ mr.AssertNumberOfCalls(t, "GetUserACL", 2) ++ mr.AssertNotCalled(t, "SetUserACL", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) ++ mr.AssertNotCalled(t, "SetSentinelAuth", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) ++ mr.AssertNotCalled(t, "DeleteUsers", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) ++ ++ // No pass has refreshed it for longer than the TTL, as after the ++ // RedisFailover was deleted: the guard stops touching its servers. ++ defer rfservice.SetGuardNow(func() time.Time { return time.Now().Add(time.Hour) })() ++ mr.Calls = nil ++ healer.GuardInternalUsersOnce() ++ assert.Empty(t, mr.Calls) ++} ++ ++// A tenant's ACL SETUSER backdoor on >x +@all between passes: the guard ++// deletes it, which also disconnects whoever is authenticated as it, and ++// keeps the operator's own users, the liveness probe's pinger among them. ++func TestGuardDeletesACLUsersTheOperatorDidNotCreate(t *testing.T) { ++ healer, _, mr := trackedHealer(t) ++ mr.On("ListUsers", "10.0.0.1", "0", newPassword, mock.Anything).Return([]string{"backdoor", "default", "pinger", "rf-exporter", "rf-internal", "spare"}, nil) ++ mr.On("ListUsers", "10.0.0.2", "0", newPassword, mock.Anything).Return(operatorUserList, nil) ++ mr.On("DeleteUsers", "10.0.0.1", "0", newPassword, []string{"backdoor", "spare"}, mock.Anything).Once().Return(nil) ++ mr.On("GetUserACL", mock.Anything, "0", newPassword, "rf-internal", mock.Anything).Return(intactACL, nil) ++ ++ healer.GuardInternalUsersOnce() ++ mr.AssertExpectations(t) ++ mr.AssertNumberOfCalls(t, "DeleteUsers", 1) ++ mr.AssertNotCalled(t, "SetUserACL", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) ++} ++ ++// A RedisFailover whose exporter ran as the internal user: every running ++// server gets the exporter user before the ConfigMap, and with it the ++// exporter's environment, names it. One server that cannot take it holds the ++// ConfigMap back. ++func TestReconcileRedisAuthIntroducesTheExporterUser(t *testing.T) { ++ t.Run("every server takes it", func(t *testing.T) { ++ rf := authRF() ++ ms := authServices(rf, newPassword, internalPassword, redisConfWithoutExporter(rf, newPassword)) ++ mr := &mRedisService.Client{} ++ mr.On("GetDefaultUserPasswords", mock.Anything, "0", newPassword, mock.Anything).Return(redis.DefaultUserPasswords{}, nil) ++ var calls recorder ++ for _, ip := range []string{"10.0.0.1", "10.0.0.2"} { ++ mr.On("SetUserACL", ip, "0", newPassword, "rf-exporter", exporterRules, mock.Anything).Run(calls.add("exporter %s", ip)).Once().Return(nil) ++ intactServer(mr, ip, newPassword) ++ } ++ healer := rfservice.NewRedisFailoverHealer(ms, mr, log.Dummy) ++ assert.NoError(t, healer.ReconcileRedisAuth(rf, nil, nil)) ++ assert.Equal(t, []string{"exporter 10.0.0.1", "exporter 10.0.0.2"}, []string(calls)) ++ mr.AssertNotCalled(t, "SetUserACL", mock.Anything, mock.Anything, mock.Anything, "rf-internal", mock.Anything, mock.Anything) ++ }) ++ t.Run("a server cannot take it", func(t *testing.T) { ++ rf := authRF() ++ ms := authServices(rf, newPassword, internalPassword, redisConfWithoutExporter(rf, newPassword)) ++ mr := &mRedisService.Client{} ++ mr.On("GetDefaultUserPasswords", mock.Anything, "0", newPassword, mock.Anything).Return(redis.DefaultUserPasswords{}, nil) ++ mr.On("SetUserACL", "10.0.0.1", "0", newPassword, "rf-exporter", exporterRules, mock.Anything).Return(nil) ++ mr.On("SetUserACL", "10.0.0.2", "0", newPassword, "rf-exporter", exporterRules, mock.Anything).Return(errors.New("i/o timeout")) ++ healer := rfservice.NewRedisFailoverHealer(ms, mr, log.Dummy) ++ assert.ErrorIs(t, healer.ReconcileRedisAuth(rf, nil, nil), rfservice.ErrPasswordRotationPending) ++ }) ++} ++ ++// An internal Secret from before the exporter user gets an exporter ++// password, and keeps everything it had. ++func TestReconcileRedisAuthAddsTheExporterPasswordToAnOlderSecret(t *testing.T) { ++ rf := authRF() ++ ms := &mK8SService.Services{} ++ ms.On("GetSecret", namespace, authSecret).Return(&corev1.Secret{Data: map[string][]byte{"password": []byte(newPassword)}}, nil) ++ ms.On("GetSecret", namespace, internalSecret).Return(&corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: internalSecret}, Data: map[string][]byte{ ++ "password": []byte(internalPassword), ++ "link": []byte(linkPassword), ++ "client-sha256": []byte(sha(newPassword)), ++ }}, nil) ++ ms.On("GetConfigMap", namespace, rfservice.GetRedisName(rf)).Return(nil, apierrors.NewNotFound(schema.GroupResource{}, "")) ++ var updated *corev1.Secret ++ ms.On("UpdateSecret", namespace, mock.Anything).Once().Run(func(args mock.Arguments) { ++ updated = args.Get(1).(*corev1.Secret) ++ }).Return(nil) ++ ++ healer := rfservice.NewRedisFailoverHealer(ms, &mRedisService.Client{}, log.Dummy) ++ assert.NoError(t, healer.ReconcileRedisAuth(rf, nil, nil)) ++ if assert.NotNil(t, updated) { ++ assert.Len(t, string(updated.Data["exporter"]), 32) ++ assert.Equal(t, internalPassword, string(updated.Data["password"])) ++ assert.Equal(t, linkPassword, string(updated.Data["link"])) ++ assert.Equal(t, sha(newPassword), string(updated.Data["client-sha256"])) ++ } ++} ++ ++// The exporter user may read requirepass, so a password the tenant adds to ++// it, or a command, is taken away on the next pass. ++func TestReconcileRedisAuthRepairsATamperedExporterUser(t *testing.T) { ++ rf := authRF() ++ ms := authServices(rf, newPassword, internalPassword, redisConf(rf, newPassword, internalPassword)) ++ mr := &mRedisService.Client{} ++ mr.On("GetDefaultUserPasswords", mock.Anything, "0", newPassword, mock.Anything).Return(redis.DefaultUserPasswords{}, nil) ++ tampered := intactExporterACL ++ tampered.Hashes = []string{sha(exporterPassword), sha("tenant-added")} ++ mr.On("GetUserACL", "10.0.0.1", "0", newPassword, "rf-exporter", mock.Anything).Return(tampered, nil) ++ mr.On("SetUserACL", "10.0.0.1", "0", newPassword, "rf-exporter", exporterRules, mock.Anything).Once().Return(nil) ++ for _, ip := range []string{"10.0.0.1", "10.0.0.2"} { ++ intactServer(mr, ip, newPassword) ++ } ++ healer := rfservice.NewRedisFailoverHealer(ms, mr, log.Dummy) ++ assert.NoError(t, healer.ReconcileRedisAuth(rf, nil, nil)) ++ mr.AssertExpectations(t) ++ mr.AssertNumberOfCalls(t, "SetUserACL", 1) ++} +diff --git a/operator/redisfailover/service/rotation_test.go b/operator/redisfailover/service/rotation_test.go +new file mode 100644 +index 0000000..74022a9 +--- /dev/null ++++ b/operator/redisfailover/service/rotation_test.go +@@ -0,0 +1,866 @@ ++package service_test ++ ++import ( ++ "crypto/tls" ++ "fmt" ++ "sort" ++ "strconv" ++ "strings" ++ "testing" ++ ++ "github.com/stretchr/testify/assert" ++ "github.com/stretchr/testify/require" ++ corev1 "k8s.io/api/core/v1" ++ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ++ ++ redisfailoverv1 "github.com/freshworks/redis-operator/api/redisfailover/v1" ++ "github.com/freshworks/redis-operator/log" ++ mK8SService "github.com/freshworks/redis-operator/mocks/service/k8s" ++ mRedisService "github.com/freshworks/redis-operator/mocks/service/redis" ++ rfservice "github.com/freshworks/redis-operator/operator/redisfailover/service" ++ "github.com/freshworks/redis-operator/service/redis" ++) ++ ++// The tests below run passes against a small model of two servers, two ++// Sentinels, the internal Secret and the redis ConfigMap, and check after ++// every write that nothing the operator set can lock replication or a ++// Sentinel out: ++// ++// - every server accepts the pod password; ++// - every server accepts the masterauth of every server, since any of them ++// may be the master; ++// - every server accepts the auth-pass of every Sentinel; ++// - no masterauth carries a new link password while a server still takes ++// the old client password, whose holders could read it; ++// - no connection of the default or the exporter user is authenticated ++// with a password its user no longer takes: either could read the new ++// client password with CONFIG GET; ++// - the rotation is not recorded as done while a server keeps a MONITOR, ++// or a connection of an operator user from an address that is no pod ++// of the RedisFailover and not loopback. ++ ++var ( ++ serverIPs = []string{"10.0.0.1", "10.0.0.2"} ++ sentinelIPs = []string{"10.0.1.1", "10.0.1.2"} ++) ++ ++type fakeServer struct { ++ users []string ++ requirepass string ++ acls map[string]redis.UserACL ++ masteruser string ++ masterauth string ++ sessions []session ++} ++ ++// session is an open connection, the password it authenticated with, the ++// address it comes from, and whether it is in MONITOR mode. ++type session struct { ++ user, password, host string ++ monitor bool ++} ++ ++const tenantHost = "10.0.9.9" ++ ++func conn(user, password, host string) session { ++ return session{user: user, password: password, host: host} ++} ++ ++// operatorSessions are the connections the operator's own links keep open ++// on every server: a Sentinel and a replica as the internal user, and the ++// liveness probe. The exporter's connection is not among them: a client ++// password change kills it, and the exporter reconnects on its next scrape. ++func operatorSessions() []session { ++ return []session{ ++ conn("rf-internal", linkPassword, sentinelIPs[0]), ++ conn("rf-internal", linkPassword, serverIPs[1]), ++ conn("pinger", "pingpass", "127.0.0.1"), ++ } ++} ++ ++// stray tells a connection the rotation must not leave behind. ++func stray(c session) bool { ++ if c.monitor { ++ return true ++ } ++ if c.user != "rf-internal" && c.user != "rf-exporter" && c.user != "pinger" { ++ return false ++ } ++ for _, ip := range append(append([]string{"127.0.0.1", "::1"}, serverIPs...), sentinelIPs...) { ++ if c.host == ip { ++ return false ++ } ++ } ++ return true ++} ++ ++func (s *fakeServer) kill(user string) { ++ var kept []session ++ for _, c := range s.sessions { ++ if c.user != user { ++ kept = append(kept, c) ++ } ++ } ++ s.sessions = kept ++} ++ ++func (s *fakeServer) sessionsOf(user string) []string { ++ var out []string ++ for _, c := range s.sessions { ++ if c.user == user { ++ out = append(out, c.password) ++ } ++ } ++ return out ++} ++ ++type world struct { ++ rf *redisfailoverv1.RedisFailover ++ client string // the auth Secret's password ++ confClient string // the ConfigMap's requirepass ++ confLink string // the ConfigMap's masterauth ++ oldLink string // the link password before the rotation under test ++ secret map[string][]byte ++ servers map[string]*fakeServer ++ sentinels map[string]string ++ ++ failAt int // the write that fails, -1 for none ++ writes int ++ violations []string ++ changes []change // every ChangeClientPassword, as called ++} ++ ++type change struct { ++ ip, password string ++ reset []redis.ACLUser ++ deleted []string ++ killed []string ++} ++ ++// newWorld is a RedisFailover at rest on oldPassword and linkPassword whose ++// auth Secret now says newPassword. ++func newWorld(rf *redisfailoverv1.RedisFailover) *world { ++ w := &world{ ++ rf: rf, ++ client: newPassword, ++ confClient: oldPassword, ++ confLink: linkPassword, ++ oldLink: linkPassword, ++ secret: map[string][]byte{ ++ "password": []byte(internalPassword), ++ "exporter": []byte(exporterPassword), ++ "link": []byte(linkPassword), ++ "client-sha256": []byte(sha(oldPassword)), ++ }, ++ servers: map[string]*fakeServer{}, ++ sentinels: map[string]string{}, ++ failAt: -1, ++ } ++ for _, ip := range serverIPs { ++ w.servers[ip] = &fakeServer{ ++ users: []string{"default", "pinger", "rf-exporter", "rf-internal"}, ++ requirepass: oldPassword, ++ acls: map[string]redis.UserACL{ ++ "rf-internal": aclFrom(internalRules), ++ "rf-exporter": aclFrom(exporterRules), ++ "pinger": aclFrom(pingerRules), ++ }, ++ masteruser: "rf-internal", ++ masterauth: linkPassword, ++ // A tenant's client on the old password, the exporter, and the ++ // operator's links. ++ sessions: append([]session{conn("default", oldPassword, tenantHost), conn("rf-exporter", exporterPassword, "127.0.0.1")}, operatorSessions()...), ++ } ++ } ++ for _, ip := range sentinelIPs { ++ w.sentinels[ip] = linkPassword ++ } ++ return w ++} ++ ++// aclFrom is what ACL GETUSER reports after ACL SETUSER reset rules... ++func aclFrom(rules []string) redis.UserACL { ++ acl := redis.UserACL{Exists: true} ++ var channels, commands []string ++ for _, r := range rules { ++ switch { ++ case r == "on": ++ acl.On = true ++ case strings.HasPrefix(r, "#"): ++ acl.Hashes = append(acl.Hashes, r[1:]) ++ case strings.HasPrefix(r, "&"): ++ channels = append(channels, r) ++ case strings.HasPrefix(r, "~"): ++ acl.Keys = r ++ case r == "-@all" || strings.HasPrefix(r, "+"): ++ commands = append(commands, r) ++ } ++ } ++ acl.Channels = strings.Join(channels, " ") ++ acl.Commands = strings.Join(commands, " ") ++ return acl ++} ++ ++func (w *world) write(what string) error { ++ n := w.writes ++ w.writes++ ++ if n == w.failAt { ++ return fmt.Errorf("injected failure at write %d (%s)", n, what) ++ } ++ return nil ++} ++ ++func (w *world) accepts(ip, password string) bool { ++ return w.userAccepts(ip, "rf-internal", password) ++} ++ ++func (w *world) userAccepts(ip, user, password string) bool { ++ if user == "default" { ++ return w.servers[ip].requirepass == password ++ } ++ for _, h := range w.servers[ip].acls[user].Hashes { ++ if h == sha(password) { ++ return true ++ } ++ } ++ return false ++} ++ ++func (w *world) check(after string) { ++ for _, ip := range serverIPs { ++ if !w.accepts(ip, internalPassword) { ++ w.violations = append(w.violations, fmt.Sprintf("after %s: %s refuses the pod password", after, ip)) ++ } ++ for _, other := range serverIPs { ++ if !w.accepts(ip, w.servers[other].masterauth) { ++ w.violations = append(w.violations, fmt.Sprintf("after %s: %s refuses the masterauth of %s", after, ip, other)) ++ } ++ } ++ for sip, pass := range w.sentinels { ++ if !w.accepts(ip, pass) { ++ w.violations = append(w.violations, fmt.Sprintf("after %s: %s refuses the auth-pass of Sentinel %s", after, ip, sip)) ++ } ++ } ++ for _, c := range w.servers[ip].sessions { ++ if (c.user == "default" || c.user == "rf-exporter") && !w.userAccepts(ip, c.user, c.password) { ++ w.violations = append(w.violations, fmt.Sprintf("after %s: %s keeps a %s connection on the password %q it no longer takes", after, ip, c.user, c.password)) ++ } ++ } ++ } ++} ++ ++func (w *world) auth(ip, password string) error { ++ if w.servers[ip].requirepass != password { ++ return wrongPass ++ } ++ return nil ++} ++ ++// fakeRedis serves the model; any other method panics through the mock. ++type fakeRedis struct { ++ *mRedisService.Client ++ w *world ++} ++ ++func (f fakeRedis) GetDefaultUserPasswords(ip, _, password string, _ *tls.Config) (redis.DefaultUserPasswords, error) { ++ return redis.DefaultUserPasswords{}, f.w.auth(ip, password) ++} ++ ++func (f fakeRedis) SetCustomRedisConfig(ip, _ string, configs []string, password string, _ *tls.Config) error { ++ if err := f.w.auth(ip, password); err != nil { ++ return err ++ } ++ if err := f.w.write("requirepass " + ip); err != nil { ++ return err ++ } ++ for _, c := range configs { ++ if v, ok := strings.CutPrefix(c, "requirepass "); ok { ++ f.w.servers[ip].requirepass = v ++ } ++ } ++ f.w.check("requirepass " + ip) ++ return nil ++} ++ ++func (f fakeRedis) GetUserACL(ip, _, auth, user string, _ *tls.Config) (redis.UserACL, error) { ++ if err := f.w.auth(ip, auth); err != nil { ++ return redis.UserACL{}, err ++ } ++ acl := f.w.servers[ip].acls[user] ++ acl.Hashes = append([]string(nil), acl.Hashes...) ++ return acl, nil ++} ++ ++func (s *fakeServer) setUser(user string, rules []string) { ++ s.acls[user] = aclFrom(rules) ++ for _, u := range s.users { ++ if u == user { ++ return ++ } ++ } ++ s.users = append(s.users, user) ++ sort.Strings(s.users) ++} ++ ++func (s *fakeServer) deleteUsers(users []string) { ++ gone := map[string]bool{} ++ for _, u := range users { ++ gone[u] = true ++ delete(s.acls, u) ++ s.kill(u) ++ } ++ var kept []string ++ for _, u := range s.users { ++ if !gone[u] { ++ kept = append(kept, u) ++ } ++ } ++ s.users = kept ++} ++ ++func (f fakeRedis) SetUserACL(ip, _, auth, user string, rules []string, _ *tls.Config) error { ++ if err := f.w.auth(ip, auth); err != nil { ++ return err ++ } ++ if err := f.w.write("acl " + ip); err != nil { ++ return err ++ } ++ f.w.servers[ip].setUser(user, rules) ++ f.w.check("acl " + ip) ++ return nil ++} ++ ++// ChangeClientPassword applies the whole transaction as one write, as EXEC ++// does. ++func (f fakeRedis) ChangeClientPassword(ip, _, auth, password string, reset []redis.ACLUser, deleteUsers, killUsers []string, _ *tls.Config) error { ++ if err := f.w.auth(ip, auth); err != nil { ++ return err ++ } ++ f.w.changes = append(f.w.changes, change{ip: ip, password: password, reset: reset, deleted: deleteUsers, killed: killUsers}) ++ if err := f.w.write("change " + ip); err != nil { ++ return err ++ } ++ s := f.w.servers[ip] ++ for _, u := range reset { ++ s.setUser(u.Name, u.Rules) ++ } ++ s.deleteUsers(deleteUsers) ++ s.requirepass = password ++ for _, u := range killUsers { ++ s.kill(u) ++ } ++ f.w.check("change " + ip) ++ return nil ++} ++ ++func (f fakeRedis) ListUsers(ip, _, auth string, _ *tls.Config) ([]string, error) { ++ if err := f.w.auth(ip, auth); err != nil { ++ return nil, err ++ } ++ return append([]string(nil), f.w.servers[ip].users...), nil ++} ++ ++func (f fakeRedis) DeleteUsers(ip, _, auth string, users []string, _ *tls.Config) error { ++ if err := f.w.auth(ip, auth); err != nil { ++ return err ++ } ++ if err := f.w.write("deluser " + ip); err != nil { ++ return err ++ } ++ f.w.servers[ip].deleteUsers(users) ++ return nil ++} ++ ++func (f fakeRedis) GetMasterAuth(ip, _, auth string, _ *tls.Config) (string, string, error) { ++ if err := f.w.auth(ip, auth); err != nil { ++ return "", "", err ++ } ++ return f.w.servers[ip].masteruser, f.w.servers[ip].masterauth, nil ++} ++ ++func (f fakeRedis) SetMasterAuth(ip, _, auth, user, password string, _ *tls.Config) error { ++ if err := f.w.auth(ip, auth); err != nil { ++ return err ++ } ++ if err := f.w.write("masterauth " + ip); err != nil { ++ return err ++ } ++ if password != f.w.oldLink { ++ for other, s := range f.w.servers { ++ if s.requirepass != f.w.client { ++ f.w.violations = append(f.w.violations, fmt.Sprintf("the new link password went into masterauth on %s while %s still takes the old client password", ip, other)) ++ } ++ } ++ } ++ f.w.servers[ip].masteruser, f.w.servers[ip].masterauth = user, password ++ f.w.check("masterauth " + ip) ++ return nil ++} ++ ++func (f fakeRedis) GetClientUsers(ip, _, auth string, _ *tls.Config) (map[string][]string, error) { ++ if err := f.w.auth(ip, auth); err != nil { ++ return nil, err ++ } ++ out := map[string][]string{} ++ for _, sip := range sentinelIPs { ++ out[sip] = []string{"rf-internal"} ++ } ++ return out, nil ++} ++ ++func (f fakeRedis) SetSentinelAuth(ip, _, _, password string, _ *tls.Config) error { ++ if err := f.w.write("sentinel " + ip); err != nil { ++ return err ++ } ++ f.w.sentinels[ip] = password ++ f.w.check("sentinel " + ip) ++ return nil ++} ++ ++func (f fakeRedis) ListClients(ip, _, auth string, _ *tls.Config) ([]redis.ClientInfo, error) { ++ if err := f.w.auth(ip, auth); err != nil { ++ return nil, err ++ } ++ var out []redis.ClientInfo ++ for i, c := range f.w.servers[ip].sessions { ++ flags := "N" ++ if c.monitor { ++ flags = "O" ++ } ++ out = append(out, redis.ClientInfo{ID: strconv.Itoa(i), Host: c.host, User: c.user, Flags: flags}) ++ } ++ return out, nil ++} ++ ++// KillClients takes the ids ListClients gave; nothing in the model connects ++// in between. ++func (f fakeRedis) KillClients(ip, _, auth string, ids []string, _ *tls.Config) error { ++ if err := f.w.auth(ip, auth); err != nil { ++ return err ++ } ++ if err := f.w.write("killclients " + ip); err != nil { ++ return err ++ } ++ gone := map[string]bool{} ++ for _, id := range ids { ++ gone[id] = true ++ } ++ s := f.w.servers[ip] ++ var kept []session ++ for i, c := range s.sessions { ++ if !gone[strconv.Itoa(i)] { ++ kept = append(kept, c) ++ } ++ } ++ s.sessions = kept ++ f.w.check("killclients " + ip) ++ return nil ++} ++ ++// fakeK8s serves the Secrets and the ConfigMap from the model. ++type fakeK8s struct { ++ *mK8SService.Services ++ w *world ++} ++ ++func (f fakeK8s) GetSecret(_, name string) (*corev1.Secret, error) { ++ if name == internalSecret { ++ data := map[string][]byte{} ++ for k, v := range f.w.secret { ++ data[k] = append([]byte(nil), v...) ++ } ++ return &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: name}, Data: data}, nil ++ } ++ return &corev1.Secret{Data: map[string][]byte{"password": []byte(f.w.client)}}, nil ++} ++ ++func (f fakeK8s) UpdateSecret(_ string, s *corev1.Secret) error { ++ if err := f.w.write("secret"); err != nil { ++ return err ++ } ++ _, was := f.w.secret["link-previous"] ++ _, is := s.Data["link-previous"] ++ if was && !is { ++ for ip, srv := range f.w.servers { ++ for _, c := range srv.sessions { ++ if stray(c) { ++ f.w.violations = append(f.w.violations, fmt.Sprintf("the rotation was recorded as done while %s keeps %+v", ip, c)) ++ } ++ } ++ } ++ } ++ f.w.secret = s.Data ++ return nil ++} ++ ++func (f fakeK8s) GetConfigMap(_, _ string) (*corev1.ConfigMap, error) { ++ return rfservice.GenerateRedisConfigMapForTest(f.w.rf, nil, nil, f.w.confClient, internalPassword, f.w.confLink, exporterPassword), nil ++} ++ ++func (w *world) services() fakeK8s { ++ ms := &mK8SService.Services{} ++ pods := &corev1.PodList{} ++ for i, ip := range serverIPs { ++ pods.Items = append(pods.Items, runningPod(fmt.Sprintf("rfr-%d", i), ip)) ++ } ++ sentinels := &corev1.PodList{} ++ for i, ip := range sentinelIPs { ++ sentinels.Items = append(sentinels.Items, runningPod(fmt.Sprintf("rfs-%d", i), ip)) ++ } ++ ms.On("GetStatefulSetPods", namespace, rfservice.GetRedisName(w.rf)).Return(pods, nil) ++ ms.On("GetDeploymentPods", namespace, rfservice.GetSentinelName(w.rf)).Return(sentinels, nil) ++ return fakeK8s{Services: ms, w: w} ++} ++ ++// pass runs one reconcile pass on a fresh healer, as after a restart of the ++// operator, and on success writes the ConfigMap as Ensure would. ++func (w *world) pass() (*rfservice.RedisFailoverHealer, error) { ++ healer := rfservice.NewRedisFailoverHealer(w.services(), fakeRedis{Client: &mRedisService.Client{}, w: w}, log.Dummy) ++ err := healer.ReconcileRedisAuth(w.rf, nil, nil) ++ if err == nil { ++ w.confClient, w.confLink = w.client, string(w.secret["link"]) ++ } ++ return healer, err ++} ++ ++func sorted(s []string) []string { ++ s = append([]string(nil), s...) ++ sort.Strings(s) ++ return s ++} ++ ++// assertRotated checks the end state: everything on newLink, the old link ++// password refused by every server, and the Secret recording the rotation ++// as done for the current client password. ++func (w *world) assertRotated(t *testing.T, newLink string) { ++ t.Helper() ++ assert.NotEqual(t, w.oldLink, newLink) ++ assert.Equal(t, newLink, string(w.secret["link"])) ++ assert.NotContains(t, w.secret, "link-previous") ++ assert.Equal(t, sha(w.client), string(w.secret["client-sha256"])) ++ assert.Equal(t, internalPassword, string(w.secret["password"]), "the pod password never changes") ++ want := sorted([]string{sha(internalPassword), sha(newLink)}) ++ for ip, s := range w.servers { ++ assert.Equal(t, w.client, s.requirepass, ip) ++ assert.Equal(t, want, sorted(s.acls["rf-internal"].Hashes), ip) ++ assert.False(t, w.accepts(ip, w.oldLink), "%s still takes the old link password", ip) ++ assert.Equal(t, "rf-internal", s.masteruser, ip) ++ assert.Equal(t, newLink, s.masterauth, ip) ++ assert.Equal(t, internalCommandRules, s.acls["rf-internal"].Commands, ip) ++ assert.Equal(t, aclFrom(exporterRules), s.acls["rf-exporter"], ip) ++ assert.Equal(t, aclFrom(pingerRules), s.acls["pinger"], ip) ++ // No tenant connection outlives the change, and the operator's own ++ // links are untouched. ++ for _, p := range s.sessionsOf("default") { ++ assert.Equal(t, w.client, p, "%s keeps a default connection on an old client password", ip) ++ } ++ assert.Subset(t, s.sessions, operatorSessions(), ip) ++ } ++ for ip, pass := range w.sentinels { ++ assert.Equal(t, newLink, pass, ip) ++ } ++ assert.Empty(t, w.violations) ++} ++ ++func TestReconcileRedisAuthRotatesTheLinkPasswordWithTheClientPassword(t *testing.T) { ++ w := newWorld(authRF()) ++ _, err := w.pass() ++ require.NoError(t, err) ++ w.assertRotated(t, string(w.secret["link"])) ++ // The client password change on each server, the Secret, both ACLs, ++ // both masterauths, both Sentinels, both ACLs again, the Secret again. ++ assert.Equal(t, 12, w.writes) ++ assert.Equal(t, newPassword, w.confClient, "the ConfigMap moves on only once the rotation is done") ++ ++ // The next pass finds nothing to do. ++ w.writes = 0 ++ _, err = w.pass() ++ require.NoError(t, err) ++ assert.Zero(t, w.writes) ++} ++ ++// A failed write stands for a crash right before it: the next pass, on a ++// fresh operator, must finish the same rotation, never start a second one, ++// and keep every invariant on the way. ++func TestReconcileRedisAuthResumesARotationInterruptedAtAnyStep(t *testing.T) { ++ const writes = 12 ++ for failAt := 0; failAt < writes; failAt++ { ++ t.Run(fmt.Sprintf("write %d", failAt), func(t *testing.T) { ++ w := newWorld(authRF()) ++ w.failAt = failAt ++ _, err := w.pass() ++ require.ErrorIs(t, err, rfservice.ErrPasswordRotationPending) ++ assert.Equal(t, oldPassword, w.confClient, "an unfinished rotation keeps the ConfigMap") ++ generated := "" ++ if _, ok := w.secret["link-previous"]; ok { ++ generated = string(w.secret["link"]) ++ } ++ ++ w.failAt = -1 ++ _, err = w.pass() ++ require.NoError(t, err) ++ if generated != "" { ++ assert.Equal(t, generated, string(w.secret["link"]), "the interrupted rotation is finished, not restarted") ++ } ++ w.assertRotated(t, string(w.secret["link"])) ++ }) ++ } ++} ++ ++// A server that cannot be reached holds the old client password, so its ++// holders could still read masterauth there: the rotation does not start. ++func TestReconcileRedisAuthDoesNotRotateBeforeEveryServerRefusesTheOldClientPassword(t *testing.T) { ++ w := newWorld(authRF()) ++ w.failAt = 1 // the second client password change ++ _, err := w.pass() ++ require.ErrorIs(t, err, rfservice.ErrPasswordRotationPending) ++ assert.Equal(t, linkPassword, string(w.secret["link"])) ++ assert.NotContains(t, w.secret, "link-previous") ++ assert.Equal(t, 2, w.writes, "nothing past the failed client password change") ++ assert.Empty(t, w.violations) ++} ++ ++// A client password changed again after the new link password reached ++// masterauth: holders of the one in between may have read it, so the same ++// pass finishes that rotation and runs a second one. ++func TestReconcileRedisAuthRotatesAgainForAClientPasswordChangedMidway(t *testing.T) { ++ w := newWorld(authRF()) ++ w.failAt = 9 // the first ACL of step 5, after the Sentinels moved ++ _, err := w.pass() ++ require.ErrorIs(t, err, rfservice.ErrPasswordRotationPending) ++ first := string(w.secret["link"]) ++ ++ // The tenant mints once more. The model skips how the servers reach the ++ // third password: a server on neither the ConfigMap's nor the current ++ // one is restarted, which TestReconcileRedisAuthRestartsAServerOnAnUnknownPassword covers. ++ w.client = "third-password" ++ for _, s := range w.servers { ++ s.requirepass = w.client ++ } ++ w.failAt = -1 ++ _, err = w.pass() ++ require.NoError(t, err) ++ second := string(w.secret["link"]) ++ assert.NotEqual(t, first, second) ++ w.assertRotated(t, second) ++ for ip := range w.servers { ++ assert.False(t, w.accepts(ip, first), ip) ++ } ++} ++ ++// The guard between passes, with a rotation stopped halfway: it treats both ++// link passwords as the operator's, repairs a tampered server to both, and ++// re-sends the Sentinels only a password every server accepts. ++func TestGuardKeepsTheTransitionState(t *testing.T) { ++ cases := map[string]struct { ++ failAt int ++ wantSentinel bool ++ }{ ++ // Step 2 done, masterauth not started: the new password is valid ++ // everywhere, so the Sentinels can be re-sent it. ++ "after step 2": {failAt: 5, wantSentinel: true}, ++ // Step 2 half done: whether the new one is valid on every server is ++ // not known, so the Sentinels are left alone. ++ "inside step 2": {failAt: 4, wantSentinel: false}, ++ } ++ for name, c := range cases { ++ t.Run(name, func(t *testing.T) { ++ w := newWorld(authRF()) ++ w.failAt = c.failAt ++ healer, err := w.pass() ++ require.ErrorIs(t, err, rfservice.ErrPasswordRotationPending) ++ w.failAt = -1 ++ next := string(w.secret["link"]) ++ require.NotEqual(t, w.oldLink, next) ++ ++ // The guard runs on the healer whose pass stopped. ++ w.servers["10.0.0.1"].acls["rf-internal"] = redis.UserACL{} // a tenant's ACL DELUSER ++ before := map[string]string{} ++ for ip, p := range w.sentinels { ++ before[ip] = p ++ } ++ healer.GuardInternalUsersOnce() ++ ++ both := sorted([]string{sha(internalPassword), sha(w.oldLink), sha(next)}) ++ for ip, s := range w.servers { ++ assert.Equal(t, both, sorted(s.acls["rf-internal"].Hashes), ip) ++ } ++ for ip, p := range w.sentinels { ++ if c.wantSentinel { ++ assert.Equal(t, next, p, ip) ++ } else { ++ assert.Equal(t, before[ip], p, ip) ++ } ++ } ++ assert.Empty(t, w.violations) ++ ++ // The next pass still finishes the rotation. ++ _, err = w.pass() ++ require.NoError(t, err) ++ w.assertRotated(t, next) ++ }) ++ } ++} ++ ++// A revoke leaves no ACL user a tenant created while it held the old client ++// password, even when deleting it fails once. ++func TestReconcileRedisAuthDeletesForeignACLUsersOnRotation(t *testing.T) { ++ w := newWorld(authRF()) ++ w.servers["10.0.0.2"].users = append(w.servers["10.0.0.2"].users, "backdoor") ++ w.failAt = 11 // the ACL DELUSER on 10.0.0.2, after both ACLs of step 5 ++ _, err := w.pass() ++ require.ErrorIs(t, err, rfservice.ErrPasswordRotationPending) ++ assert.Contains(t, w.secret, "link-previous", "the rotation is not recorded as done") ++ ++ w.failAt = -1 ++ _, err = w.pass() ++ require.NoError(t, err) ++ for ip, s := range w.servers { ++ assert.Equal(t, []string{"default", "pinger", "rf-exporter", "rf-internal"}, s.users, ip) ++ } ++ w.assertRotated(t, string(w.secret["link"])) ++} ++ ++func TestOperatorUserRuleStringsAreExact(t *testing.T) { ++ conf := rfservice.GenerateRedisConfigMapForTest(authRF(), nil, nil, newPassword, "p", "l", "e").Data["redis.conf"] ++ internal := "user rf-internal on #" + sha("p") + " #" + sha("l") + " resetkeys resetchannels &__sentinel__:hello -@all +ping +info +psync +sync +replconf +client|setname +client|kill +subscribe +publish +multi +exec +slaveof +config|rewrite +script|kill +save" ++ exporter := "user rf-exporter on #" + sha("e") + " resetkeys resetchannels -@all +client|setname +config|get +info +latency|latest +latency|histogram +slowlog|len +slowlog|get" ++ lines := strings.Split(conf, "\n") ++ assert.Equal(t, internal, lines[len(lines)-2]) ++ assert.Equal(t, exporter, lines[len(lines)-1]) ++ assert.NotContains(t, conf, "+@all") ++ assert.NotContains(t, conf, "~*") ++ assert.NotContains(t, conf, "&*") ++ // The template's pinger line, which pingerRules restates. ++ assert.Contains(t, conf, "\nuser pinger -@all +ping on >pingpass\n") ++ assert.Equal(t, "on #"+sha("pingpass")+" resetkeys resetchannels -@all +ping", strings.Join(pingerRules, " ")) ++} ++ ++// A mint and then a revoke, each a new client password: each change kills ++// every tenant connection on every server, replicas included, in the same ++// transaction that sets requirepass, and leaves the operator's links up. ++func TestClientPasswordChangeDisconnectsTheTenantOnMintAndRevoke(t *testing.T) { ++ w := newWorld(authRF()) ++ _, err := w.pass() ++ require.NoError(t, err) ++ w.assertRotated(t, string(w.secret["link"])) ++ require.Len(t, w.changes, 2) ++ for i, ip := range serverIPs { ++ c := w.changes[i] ++ assert.Equal(t, ip, c.ip) ++ assert.Equal(t, newPassword, c.password) ++ assert.Equal(t, []string{"default", "rf-exporter"}, c.killed) ++ assert.Empty(t, c.deleted) ++ assert.Equal(t, []redis.ACLUser{ ++ {Name: "rf-internal", Rules: internalRules}, ++ {Name: "rf-exporter", Rules: exporterRules}, ++ {Name: "pinger", Rules: pingerRules}, ++ }, c.reset) ++ } ++ ++ // The tenant connects with the minted password, then revokes it: the ++ // Secret gets a password nobody holds. ++ for _, s := range w.servers { ++ s.sessions = append(s.sessions, conn("default", newPassword, tenantHost)) ++ } ++ w.client, w.oldLink, w.changes = "revoked-unknown", string(w.secret["link"]), nil ++ _, err = w.pass() ++ require.NoError(t, err) ++ w.assertRotated(t, string(w.secret["link"])) ++ require.Len(t, w.changes, 2) ++ for ip, s := range w.servers { ++ assert.Empty(t, s.sessionsOf("default"), "%s keeps a connection made with the revoked password", ip) ++ } ++} ++ ++// What a holder of the old password could set before the change to stay in ++// after it: a password of their own on the exporter user, which may run ++// CONFIG GET, with a connection open on it; the pinger, whose password is ++// public, widened to every command; a user of their own. The change takes all ++// of it away at once. ++func TestClientPasswordChangeUndoesWhatTheOldPasswordSet(t *testing.T) { ++ w := newWorld(authRF()) ++ s := w.servers["10.0.0.2"] ++ tampered := s.acls["rf-exporter"] ++ tampered.Hashes = append(tampered.Hashes, sha("tenant-added")) ++ s.acls["rf-exporter"] = tampered ++ s.sessions = append(s.sessions, conn("rf-exporter", "tenant-added", tenantHost), conn("backdoor", "x", tenantHost)) ++ s.acls["pinger"] = aclFrom(strings.Fields("on #" + sha("pingpass") + " -@all +@all")) ++ s.users = append(s.users, "backdoor") ++ ++ _, err := w.pass() ++ require.NoError(t, err) ++ w.assertRotated(t, string(w.secret["link"])) ++ assert.Empty(t, s.sessionsOf("backdoor")) ++ assert.NotContains(t, s.sessionsOf("rf-exporter"), "tenant-added") ++ assert.Equal(t, []string{"backdoor"}, w.changes[1].deleted) ++} ++ ++// An interrupted change resumes without a second kill on a server it already ++// moved: that server is on the new password, so the next pass leaves it. ++func TestClientPasswordChangeResumesOnTheServersLeft(t *testing.T) { ++ w := newWorld(authRF()) ++ w.failAt = 1 // the change on the second server ++ _, err := w.pass() ++ require.ErrorIs(t, err, rfservice.ErrPasswordRotationPending) ++ assert.Equal(t, newPassword, w.servers["10.0.0.1"].requirepass) ++ assert.Empty(t, w.servers["10.0.0.1"].sessionsOf("default")) ++ assert.Equal(t, oldPassword, w.servers["10.0.0.2"].requirepass) ++ assert.Equal(t, []string{oldPassword}, w.servers["10.0.0.2"].sessionsOf("default"), "a failed change changes nothing") ++ ++ // A tenant client reconnects to the moved server with the new password. ++ w.servers["10.0.0.1"].sessions = append(w.servers["10.0.0.1"].sessions, conn("default", newPassword, tenantHost)) ++ w.failAt, w.changes = -1, nil ++ _, err = w.pass() ++ require.NoError(t, err) ++ w.assertRotated(t, string(w.secret["link"])) ++ require.Len(t, w.changes, 1) ++ assert.Equal(t, "10.0.0.2", w.changes[0].ip) ++ assert.Equal(t, []string{newPassword}, w.servers["10.0.0.1"].sessionsOf("default")) ++} ++ ++// What a holder of the old password could leave open to outlive a revoke ++// without reading the new one: a replication stream as the internal user ++// with the link password it read from masterauth, and a MONITOR opened as ++// the pinger while it was widened. The rotation closes both before it is ++// recorded as done, and keeps every link of the operator's own. ++func TestRotationDisconnectsStrayOperatorConnectionsAndMonitors(t *testing.T) { ++ for name, failAt := range map[string]int{"in one pass": -1, "resumed after the kill failed": 11} { ++ t.Run(name, func(t *testing.T) { ++ w := newWorld(authRF()) ++ s := w.servers["10.0.0.1"] ++ sync := conn("rf-internal", linkPassword, tenantHost) ++ monitor := conn("pinger", "pingpass", tenantHost) ++ monitor.monitor = true ++ // A MONITOR from inside the pod goes too: no operator link uses one. ++ local := conn("pinger", "pingpass", "127.0.0.1") ++ local.monitor = true ++ s.sessions = append(s.sessions, sync, monitor, local) ++ w.failAt = failAt ++ ++ _, err := w.pass() ++ if failAt >= 0 { ++ require.ErrorIs(t, err, rfservice.ErrPasswordRotationPending) ++ assert.Contains(t, w.secret, "link-previous", "not recorded as done before the kill") ++ w.failAt = -1 ++ _, err = w.pass() ++ } ++ require.NoError(t, err) ++ w.assertRotated(t, string(w.secret["link"])) ++ for ip, srv := range w.servers { ++ for _, c := range srv.sessions { ++ assert.False(t, stray(c), "%s keeps %+v", ip, c) ++ } ++ } ++ if failAt < 0 { ++ assert.Equal(t, 13, w.writes, "the 12 writes of a rotation and one kill on the one server with strays") ++ } ++ ++ // Nothing left to kill: the next pass writes nothing. ++ w.writes = 0 ++ _, err = w.pass() ++ require.NoError(t, err) ++ assert.Zero(t, w.writes) ++ }) ++ } ++} +diff --git a/operator/redisfailover/splitbrain_test.go b/operator/redisfailover/splitbrain_test.go +new file mode 100644 +index 0000000..d4ff2af +--- /dev/null ++++ b/operator/redisfailover/splitbrain_test.go +@@ -0,0 +1,80 @@ ++package redisfailover_test ++ ++import ( ++ "errors" ++ "testing" ++ ++ "github.com/stretchr/testify/assert" ++ "github.com/stretchr/testify/mock" ++ ++ "github.com/freshworks/redis-operator/log" ++ "github.com/freshworks/redis-operator/metrics" ++ mRFService "github.com/freshworks/redis-operator/mocks/operator/redisfailover/service" ++ mK8SService "github.com/freshworks/redis-operator/mocks/service/k8s" ++ rfOperator "github.com/freshworks/redis-operator/operator/redisfailover" ++) ++ ++// The sequence from the stand: the roll moved the master off 10.244.0.128, ++// and the same pass then "fixed" the Sentinels back to 10.244.0.128, the ++// master it had read at its start, leaving 10.244.0.122 and 10.244.0.128 ++// both masters. The pass must end at the failover. ++func TestCheckAndHealEndsThePassWhenTheRollMovesTheMaster(t *testing.T) { ++ assert := assert.New(t) ++ const oldMaster, replica = "10.244.0.128", "10.244.0.122" ++ rf := generateRF(false, false, false) ++ rf.Spec.Redis.Replicas = 2 ++ ++ mrfc := &mRFService.RedisFailoverCheck{} ++ mrfh := &mRFService.RedisFailoverHeal{} ++ mrfc.On("IsRedisRunning", rf).Return(true) ++ mrfc.On("IsSentinelRunning", rf).Return(true) ++ mrfc.On("GetNumberMasters", rf).Return(1, nil) ++ mrfc.On("GetMasterIP", rf).Return(oldMaster, nil) ++ mrfc.On("CheckAllSlavesFromMaster", oldMaster, rf).Return(nil) ++ mrfc.On("GetRedisesIPs", rf).Return([]string{oldMaster, replica}, nil) ++ mrfh.On("SetRedisCustomConfig", mock.Anything, rf).Return(nil) ++ // The roll: the replica is already on the new revision, the master is not. ++ mrfc.On("CheckRedisSlavesReady", replica, rf).Return(true, nil) ++ mrfc.On("GetStatefulSetUpdateRevision", rf).Return("new", nil) ++ mrfc.On("GetRedisesSlavesPods", rf).Return([]string{"rfr-1"}, nil) ++ mrfc.On("GetRedisRevisionHash", "rfr-1", rf).Return("new", nil) ++ mrfc.On("GetRedisesMasterPod", rf).Return("rfr-0", nil) ++ mrfc.On("GetRedisRevisionHash", "rfr-0", rf).Return("old", nil) ++ mrfh.On("FailoverMaster", rf).Once().Return(nil) ++ ++ handler := rfOperator.NewRedisFailoverHandler(generateConfig(), &mRFService.RedisFailoverClient{}, mrfc, mrfh, &mK8SService.Services{}, metrics.Dummy, log.Dummy) ++ assert.NoError(handler.CheckAndHeal(rf)) ++ ++ mrfh.AssertCalled(t, "FailoverMaster", rf) ++ mrfh.AssertNotCalled(t, "DeletePod", mock.Anything, mock.Anything) ++ // Nothing after the failover may act on the stale master. ++ mrfc.AssertNotCalled(t, "GetSentinelsIPs", mock.Anything) ++ mrfc.AssertNotCalled(t, "CheckSentinelMonitor", mock.Anything, mock.Anything, mock.Anything, mock.Anything) ++ mrfh.AssertNotCalled(t, "NewSentinelMonitor", mock.Anything, mock.Anything, mock.Anything) ++} ++ ++// Two masters: the healer settles them on the one the Sentinel quorum ++// names, instead of asking for a manual fix; without a quorum it still ++// reports the manual fix. ++func TestCheckAndHealSettlesTwoMastersOnTheSentinelQuorum(t *testing.T) { ++ for name, resolveErr := range map[string]error{"quorum": nil, "no quorum": errors.New("no quorum")} { ++ t.Run(name, func(t *testing.T) { ++ rf := generateRF(false, false, false) ++ mrfc := &mRFService.RedisFailoverCheck{} ++ mrfh := &mRFService.RedisFailoverHeal{} ++ mrfc.On("IsRedisRunning", rf).Return(true) ++ mrfc.On("IsSentinelRunning", rf).Return(true) ++ mrfc.On("GetNumberMasters", rf).Return(2, nil) ++ mrfh.On("ResolveMultipleMasters", rf).Once().Return(resolveErr) ++ ++ handler := rfOperator.NewRedisFailoverHandler(generateConfig(), &mRFService.RedisFailoverClient{}, mrfc, mrfh, &mK8SService.Services{}, metrics.Dummy, log.Dummy) ++ err := handler.CheckAndHeal(rf) ++ if resolveErr == nil { ++ assert.NoError(t, err) ++ } else { ++ assert.ErrorContains(t, err, "fix manually") ++ } ++ mrfh.AssertExpectations(t) ++ }) ++ } ++} +diff --git a/service/redis/client.go b/service/redis/client.go +index 0e4f8c6..f11c0d0 100644 +--- a/service/redis/client.go ++++ b/service/redis/client.go +@@ -30,6 +30,19 @@ type Client interface { + GetSentinelMonitor(ip, masterName string, tlsConfig *tls.Config) (string, string, error) + SetCustomSentinelConfig(ip, masterName string, configs []string, tlsConfig *tls.Config) error + SetSentinelAuthPass(ip, masterName, password string, tlsConfig *tls.Config) error ++ GetDefaultUserPasswords(ip, port, password string, tlsConfig *tls.Config) (DefaultUserPasswords, error) ++ SetUserACL(ip, port, auth, user string, rules []string, tlsConfig *tls.Config) error ++ ListUsers(ip, port, auth string, tlsConfig *tls.Config) ([]string, error) ++ DeleteUsers(ip, port, auth string, users []string, tlsConfig *tls.Config) error ++ ChangeClientPassword(ip, port, auth, password string, reset []ACLUser, deleteUsers, killUsers []string, tlsConfig *tls.Config) error ++ ListClients(ip, port, auth string, tlsConfig *tls.Config) ([]ClientInfo, error) ++ KillClients(ip, port, auth string, ids []string, tlsConfig *tls.Config) error ++ GetUserACL(ip, port, auth, user string, tlsConfig *tls.Config) (UserACL, error) ++ GetMasterAuth(ip, port, auth string, tlsConfig *tls.Config) (user, password string, err error) ++ GetClientUsers(ip, port, auth string, tlsConfig *tls.Config) (map[string][]string, error) ++ SetSentinelAuth(ip, masterName, user, password string, tlsConfig *tls.Config) error ++ SetMasterAuth(ip, port, auth, user, password string, tlsConfig *tls.Config) error ++ SentinelFailover(ip, masterName string, tlsConfig *tls.Config) error + SetCustomRedisConfig(ip string, port string, configs []string, password string, tlsConfig *tls.Config) error + SlaveIsReady(ip, port, password string, tlsConfig *tls.Config) (bool, error) + SentinelCheckQuorum(ip, masterName string, tlsConfig *tls.Config) error +@@ -365,6 +378,522 @@ func (c *client) SetSentinelAuthPass(ip, masterName, password string, tlsConfig + return nil + } + ++// DefaultUserPasswords is what ACL GETUSER reports about the passwords of ++// the default user: the SHA-256 hex of each password it accepts, and whether ++// it accepts any password at all (nopass). ++type DefaultUserPasswords struct { ++ Hashes []string ++ NoPass bool ++} ++ ++// IsAuthError tells a server that refused the password, and so runs on ++// another one, from one that could not be reached or failed otherwise. ++func IsAuthError(err error) bool { ++ if err == nil { ++ return false ++ } ++ msg := err.Error() ++ return strings.Contains(msg, "WRONGPASS") || strings.Contains(msg, "NOAUTH") || strings.Contains(msg, "invalid password") ++} ++ ++// GetDefaultUserPasswords authenticates with password and reads the ++// passwords of the default user. An error for which IsAuthError holds means ++// the server does not accept password. ++func (c *client) GetDefaultUserPasswords(ip, port, password string, tlsConfig *tls.Config) (DefaultUserPasswords, error) { ++ options := &rediscli.Options{ ++ Addr: net.JoinHostPort(ip, port), ++ Password: password, ++ DB: 0, ++ TLSConfig: tlsConfig, ++ } ++ rClient := rediscli.NewClient(options) ++ defer func() { _ = rClient.Close() }() ++ res, err := rClient.Do(context.TODO(), "ACL", "GETUSER", "default").Result() ++ if err != nil { ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_REDIS, ip, metrics.APPLY_REDIS_CONFIG, metrics.FAIL, getRedisError(err)) ++ return DefaultUserPasswords{}, err ++ } ++ return parseDefaultUser(res) ++} ++ ++// parseDefaultUser reads the RESP2 reply of ACL GETUSER: a flat list of ++// field names, each followed by its value. ++func parseDefaultUser(res interface{}) (DefaultUserPasswords, error) { ++ fields, ok := res.([]interface{}) ++ if !ok { ++ return DefaultUserPasswords{}, fmt.Errorf("unexpected ACL GETUSER reply %T", res) ++ } ++ var out DefaultUserPasswords ++ for i := 0; i+1 < len(fields); i += 2 { ++ name, _ := fields[i].(string) ++ values, _ := fields[i+1].([]interface{}) ++ switch name { ++ case "flags": ++ for _, v := range values { ++ if f, _ := v.(string); f == "nopass" { ++ out.NoPass = true ++ } ++ } ++ case "passwords": ++ for _, v := range values { ++ if h, ok := v.(string); ok { ++ out.Hashes = append(out.Hashes, h) ++ } ++ } ++ } ++ } ++ return out, nil ++} ++ ++// UserACL is what ACL GETUSER reports about a user. Keys, Channels and ++// Commands are the root rules as one space-separated string each, whichever ++// shape (a string in Redis 7 and Valkey, a list in Redis 6) the server uses. ++type UserACL struct { ++ Exists bool ++ On bool ++ NoPass bool ++ Hashes []string ++ Keys string ++ Channels string ++ Commands string ++ Selectors int ++} ++ ++func aclString(v interface{}) string { ++ switch t := v.(type) { ++ case string: ++ return t ++ case []interface{}: ++ parts := make([]string, 0, len(t)) ++ for _, p := range t { ++ if s, ok := p.(string); ok { ++ parts = append(parts, s) ++ } ++ } ++ return strings.Join(parts, " ") ++ } ++ return "" ++} ++ ++// parseUserACL reads the RESP2 reply of ACL GETUSER; nil means no such user. ++func parseUserACL(res interface{}) (UserACL, error) { ++ if res == nil { ++ return UserACL{}, nil ++ } ++ fields, ok := res.([]interface{}) ++ if !ok { ++ return UserACL{}, fmt.Errorf("unexpected ACL GETUSER reply %T", res) ++ } ++ out := UserACL{Exists: true} ++ for i := 0; i+1 < len(fields); i += 2 { ++ name, _ := fields[i].(string) ++ switch name { ++ case "flags": ++ values, _ := fields[i+1].([]interface{}) ++ for _, v := range values { ++ switch f, _ := v.(string); f { ++ case "on": ++ out.On = true ++ case "nopass": ++ out.NoPass = true ++ } ++ } ++ case "passwords": ++ values, _ := fields[i+1].([]interface{}) ++ for _, v := range values { ++ if h, ok := v.(string); ok { ++ out.Hashes = append(out.Hashes, h) ++ } ++ } ++ case "keys": ++ out.Keys = aclString(fields[i+1]) ++ case "channels": ++ out.Channels = aclString(fields[i+1]) ++ case "commands": ++ out.Commands = aclString(fields[i+1]) ++ case "selectors": ++ values, _ := fields[i+1].([]interface{}) ++ out.Selectors = len(values) ++ } ++ } ++ return out, nil ++} ++ ++// GetUserACL authenticates as the default user with auth and reads the ACL ++// of user. ++func (c *client) GetUserACL(ip, port, auth, user string, tlsConfig *tls.Config) (UserACL, error) { ++ options := &rediscli.Options{ ++ Addr: net.JoinHostPort(ip, port), ++ Password: auth, ++ DB: 0, ++ TLSConfig: tlsConfig, ++ } ++ rClient := rediscli.NewClient(options) ++ defer func() { _ = rClient.Close() }() ++ res, err := rClient.Do(context.TODO(), "ACL", "GETUSER", user).Result() ++ if err == rediscli.Nil { ++ return UserACL{}, nil ++ } ++ if err != nil { ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_REDIS, ip, metrics.APPLY_REDIS_CONFIG, metrics.FAIL, getRedisError(err)) ++ return UserACL{}, err ++ } ++ return parseUserACL(res) ++} ++ ++// GetMasterAuth reads the user and password the server replicates as. ++func (c *client) GetMasterAuth(ip, port, auth string, tlsConfig *tls.Config) (string, string, error) { ++ options := &rediscli.Options{ ++ Addr: net.JoinHostPort(ip, port), ++ Password: auth, ++ DB: 0, ++ TLSConfig: tlsConfig, ++ } ++ rClient := rediscli.NewClient(options) ++ defer func() { _ = rClient.Close() }() ++ res, err := rClient.ConfigGet(context.TODO(), "master*").Result() ++ if err != nil { ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_REDIS, ip, metrics.APPLY_REDIS_CONFIG, metrics.FAIL, getRedisError(err)) ++ return "", "", err ++ } ++ values := map[string]string{} ++ for i := 0; i+1 < len(res); i += 2 { ++ k, _ := res[i].(string) ++ v, _ := res[i+1].(string) ++ values[k] = v ++ } ++ return values["masteruser"], values["masterauth"], nil ++} ++ ++// GetClientUsers maps the IP of every client connected to the server to the ++// users its connections are authenticated as, from CLIENT LIST. ++func (c *client) GetClientUsers(ip, port, auth string, tlsConfig *tls.Config) (map[string][]string, error) { ++ options := &rediscli.Options{ ++ Addr: net.JoinHostPort(ip, port), ++ Password: auth, ++ DB: 0, ++ TLSConfig: tlsConfig, ++ } ++ rClient := rediscli.NewClient(options) ++ defer func() { _ = rClient.Close() }() ++ list, err := rClient.ClientList(context.TODO()).Result() ++ if err != nil { ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_REDIS, ip, metrics.APPLY_REDIS_CONFIG, metrics.FAIL, getRedisError(err)) ++ return nil, err ++ } ++ return parseClientUsers(list), nil ++} ++ ++// ClientInfo is one line of CLIENT LIST: the connection's id, the host it ++// comes from, the user it is authenticated as, and its flags. ++type ClientInfo struct { ++ ID, Host, User, Flags string ++} ++ ++// ListClients authenticates as the default user with auth and returns every ++// connection of the server, from CLIENT LIST. ++func (c *client) ListClients(ip, port, auth string, tlsConfig *tls.Config) ([]ClientInfo, error) { ++ options := &rediscli.Options{ ++ Addr: net.JoinHostPort(ip, port), ++ Password: auth, ++ DB: 0, ++ TLSConfig: tlsConfig, ++ } ++ rClient := rediscli.NewClient(options) ++ defer func() { _ = rClient.Close() }() ++ list, err := rClient.ClientList(context.TODO()).Result() ++ if err != nil { ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_REDIS, ip, metrics.APPLY_REDIS_CONFIG, metrics.FAIL, getRedisError(err)) ++ return nil, err ++ } ++ return parseClients(list), nil ++} ++ ++func parseClients(list string) []ClientInfo { ++ var out []ClientInfo ++ for _, line := range strings.Split(list, "\n") { ++ var info ClientInfo ++ var addr string ++ for _, field := range strings.Fields(line) { ++ k, v, ok := strings.Cut(field, "=") ++ if !ok { ++ continue ++ } ++ switch k { ++ case "id": ++ info.ID = v ++ case "addr": ++ addr = v ++ case "user": ++ info.User = v ++ case "flags": ++ info.Flags = v ++ } ++ } ++ if info.ID == "" || addr == "" { ++ continue ++ } ++ // A unix socket connection shows the socket path, with :0 appended. ++ if host, _, err := net.SplitHostPort(addr); err == nil { ++ info.Host = host ++ } else { ++ info.Host = strings.TrimSuffix(addr, ":0") ++ } ++ out = append(out, info) ++ } ++ return out ++} ++ ++// KillClients authenticates as the default user with auth and disconnects ++// the connections with the given ids. CLIENT KILL with a filter answers with ++// the number killed, so one already gone is no error. ++func (c *client) KillClients(ip, port, auth string, ids []string, tlsConfig *tls.Config) error { ++ options := &rediscli.Options{ ++ Addr: net.JoinHostPort(ip, port), ++ Password: auth, ++ DB: 0, ++ TLSConfig: tlsConfig, ++ } ++ rClient := rediscli.NewClient(options) ++ defer func() { _ = rClient.Close() }() ++ ctx := context.TODO() ++ _, err := rClient.Pipelined(ctx, func(pipe rediscli.Pipeliner) error { ++ for _, id := range ids { ++ pipe.Do(ctx, "CLIENT", "KILL", "ID", id) ++ } ++ return nil ++ }) ++ if err != nil { ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_REDIS, ip, metrics.APPLY_REDIS_CONFIG, metrics.FAIL, getRedisError(err)) ++ return err ++ } ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_REDIS, ip, metrics.APPLY_REDIS_CONFIG, metrics.SUCCESS, metrics.NOT_APPLICABLE) ++ return nil ++} ++ ++func parseClientUsers(list string) map[string][]string { ++ out := map[string][]string{} ++ for _, line := range strings.Split(list, "\n") { ++ var addr, user string ++ for _, field := range strings.Fields(line) { ++ if v, ok := strings.CutPrefix(field, "addr="); ok { ++ addr = v ++ } else if v, ok := strings.CutPrefix(field, "user="); ok { ++ user = v ++ } ++ } ++ if addr == "" { ++ continue ++ } ++ host, _, err := net.SplitHostPort(addr) ++ if err != nil { ++ continue ++ } ++ out[host] = append(out[host], user) ++ } ++ return out ++} ++ ++// SetUserACL authenticates as the default user with auth and replaces the ++// rules of user with rules, creating it if needed. reset comes first in the ++// same command, so the result does not depend on what the user had. ++func (c *client) SetUserACL(ip, port, auth, user string, rules []string, tlsConfig *tls.Config) error { ++ options := &rediscli.Options{ ++ Addr: net.JoinHostPort(ip, port), ++ Password: auth, ++ DB: 0, ++ TLSConfig: tlsConfig, ++ } ++ rClient := rediscli.NewClient(options) ++ defer func() { _ = rClient.Close() }() ++ args := []interface{}{"ACL", "SETUSER", user, "reset"} ++ for _, rule := range rules { ++ args = append(args, rule) ++ } ++ if err := rClient.Do(context.TODO(), args...).Err(); err != nil { ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_REDIS, ip, metrics.APPLY_REDIS_CONFIG, metrics.FAIL, getRedisError(err)) ++ return err ++ } ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_REDIS, ip, metrics.APPLY_REDIS_CONFIG, metrics.SUCCESS, metrics.NOT_APPLICABLE) ++ return nil ++} ++ ++// ListUsers authenticates as the default user with auth and returns the ++// names of every ACL user (ACL USERS). ++func (c *client) ListUsers(ip, port, auth string, tlsConfig *tls.Config) ([]string, error) { ++ options := &rediscli.Options{ ++ Addr: net.JoinHostPort(ip, port), ++ Password: auth, ++ DB: 0, ++ TLSConfig: tlsConfig, ++ } ++ rClient := rediscli.NewClient(options) ++ defer func() { _ = rClient.Close() }() ++ users, err := rClient.Do(context.TODO(), "ACL", "USERS").StringSlice() ++ if err != nil { ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_REDIS, ip, metrics.APPLY_REDIS_CONFIG, metrics.FAIL, getRedisError(err)) ++ return nil, err ++ } ++ return users, nil ++} ++ ++// DeleteUsers authenticates as the default user with auth and deletes users ++// with ACL DELUSER, which also disconnects every client authenticated as ++// one of them. ++func (c *client) DeleteUsers(ip, port, auth string, users []string, tlsConfig *tls.Config) error { ++ options := &rediscli.Options{ ++ Addr: net.JoinHostPort(ip, port), ++ Password: auth, ++ DB: 0, ++ TLSConfig: tlsConfig, ++ } ++ rClient := rediscli.NewClient(options) ++ defer func() { _ = rClient.Close() }() ++ args := []interface{}{"ACL", "DELUSER"} ++ for _, u := range users { ++ args = append(args, u) ++ } ++ if err := rClient.Do(context.TODO(), args...).Err(); err != nil { ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_REDIS, ip, metrics.APPLY_REDIS_CONFIG, metrics.FAIL, getRedisError(err)) ++ return err ++ } ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_REDIS, ip, metrics.APPLY_REDIS_CONFIG, metrics.SUCCESS, metrics.NOT_APPLICABLE) ++ return nil ++} ++ ++// ACLUser is a user and the rules ACL SETUSER gives it after a reset. ++type ACLUser struct { ++ Name string ++ Rules []string ++} ++ ++// ChangeClientPassword authenticates as the default user with auth and, in ++// one MULTI/EXEC transaction, resets every user in reset to its rules, ++// deletes deleteUsers, sets requirepass to password, and kills every ++// connection authenticated as one of killUsers but its own. No other client ++// runs a command in between, so none that authenticated with auth outlives ++// the change where the kill names its user. CLIENT KILL skips the caller by ++// default (SKIPME yes), and requirepass resets the passwords of the default ++// user (ACLUpdateDefaultUserPassword), so a password a tenant added to it ++// goes too. ++func (c *client) ChangeClientPassword(ip, port, auth, password string, reset []ACLUser, deleteUsers, killUsers []string, tlsConfig *tls.Config) error { ++ options := &rediscli.Options{ ++ Addr: net.JoinHostPort(ip, port), ++ Password: auth, ++ DB: 0, ++ TLSConfig: tlsConfig, ++ } ++ rClient := rediscli.NewClient(options) ++ defer func() { _ = rClient.Close() }() ++ ctx := context.TODO() ++ _, err := rClient.TxPipelined(ctx, func(pipe rediscli.Pipeliner) error { ++ for _, args := range clientPasswordChange(password, reset, deleteUsers, killUsers) { ++ pipe.Do(ctx, args...) ++ } ++ return nil ++ }) ++ if err != nil { ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_REDIS, ip, metrics.APPLY_REDIS_CONFIG, metrics.FAIL, getRedisError(err)) ++ return err ++ } ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_REDIS, ip, metrics.APPLY_REDIS_CONFIG, metrics.SUCCESS, metrics.NOT_APPLICABLE) ++ return nil ++} ++ ++// clientPasswordChange is the body of ChangeClientPassword's transaction. ++func clientPasswordChange(password string, reset []ACLUser, deleteUsers, killUsers []string) [][]interface{} { ++ var cmds [][]interface{} ++ for _, u := range reset { ++ args := []interface{}{"ACL", "SETUSER", u.Name, "reset"} ++ for _, rule := range u.Rules { ++ args = append(args, rule) ++ } ++ cmds = append(cmds, args) ++ } ++ if len(deleteUsers) > 0 { ++ args := []interface{}{"ACL", "DELUSER"} ++ for _, u := range deleteUsers { ++ args = append(args, u) ++ } ++ cmds = append(cmds, args) ++ } ++ cmds = append(cmds, []interface{}{"CONFIG", "SET", "requirepass", password}) ++ for _, u := range killUsers { ++ cmds = append(cmds, []interface{}{"CLIENT", "KILL", "USER", u}) ++ } ++ return cmds ++} ++ ++// SetMasterAuth sets the user and password the server replicates as, in one ++// CONFIG SET (Redis 7 and Valkey take several parameters at once), so a ++// replica never reconnects with one changed and not the other. ++func (c *client) SetMasterAuth(ip, port, auth, user, password string, tlsConfig *tls.Config) error { ++ options := &rediscli.Options{ ++ Addr: net.JoinHostPort(ip, port), ++ Password: auth, ++ DB: 0, ++ TLSConfig: tlsConfig, ++ } ++ rClient := rediscli.NewClient(options) ++ defer func() { _ = rClient.Close() }() ++ if err := rClient.Do(context.TODO(), "CONFIG", "SET", "masteruser", user, "masterauth", password).Err(); err != nil { ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_REDIS, ip, metrics.APPLY_REDIS_CONFIG, metrics.FAIL, getRedisError(err)) ++ return err ++ } ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_REDIS, ip, metrics.APPLY_REDIS_CONFIG, metrics.SUCCESS, metrics.NOT_APPLICABLE) ++ return nil ++} ++ ++// SetSentinelAuth sets the user and password the Sentinel authenticates to ++// the servers of masterName with. An empty user leaves auth-user alone and ++// sets the password of the default user, as SetSentinelAuthPass does. ++func (c *client) SetSentinelAuth(ip, masterName, user, password string, tlsConfig *tls.Config) error { ++ options := &rediscli.Options{ ++ Addr: net.JoinHostPort(ip, sentinelPort), ++ Password: "", ++ DB: 0, ++ TLSConfig: tlsConfig, ++ } ++ rClient := rediscli.NewClient(options) ++ defer func() { _ = rClient.Close() }() ++ if user != "" { ++ cmd := rediscli.NewStatusCmd(context.TODO(), "SENTINEL", "SET", masterName, "auth-user", user, "auth-pass", password) ++ if err := rClient.Process(context.TODO(), cmd); err != nil { ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_SENTINEL, ip, metrics.APPLY_SENTINEL_CONFIG, metrics.FAIL, getRedisError(err)) ++ return err ++ } ++ } else { ++ cmd := rediscli.NewStatusCmd(context.TODO(), "SENTINEL", "SET", masterName, "auth-pass", password) ++ if err := rClient.Process(context.TODO(), cmd); err != nil { ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_SENTINEL, ip, metrics.APPLY_SENTINEL_CONFIG, metrics.FAIL, getRedisError(err)) ++ return err ++ } ++ } ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_SENTINEL, ip, metrics.APPLY_SENTINEL_CONFIG, metrics.SUCCESS, metrics.NOT_APPLICABLE) ++ return nil ++} ++ ++// SentinelFailover asks the Sentinel to fail masterName over to one of its ++// replicas without waiting for the master to fail. The Sentinel answers ++// before the failover completes; GetSentinelMonitor tells when it did. ++func (c *client) SentinelFailover(ip, masterName string, tlsConfig *tls.Config) error { ++ options := &rediscli.Options{ ++ Addr: net.JoinHostPort(ip, sentinelPort), ++ Password: "", ++ DB: 0, ++ TLSConfig: tlsConfig, ++ } ++ rClient := rediscli.NewClient(options) ++ defer func() { _ = rClient.Close() }() ++ cmd := rediscli.NewStatusCmd(context.TODO(), "SENTINEL", "FAILOVER", masterName) ++ if err := rClient.Process(context.TODO(), cmd); err != nil { ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_SENTINEL, ip, metrics.APPLY_SENTINEL_CONFIG, metrics.FAIL, getRedisError(err)) ++ return err ++ } ++ c.metricsRecorder.RecordRedisOperation(metrics.KIND_SENTINEL, ip, metrics.APPLY_SENTINEL_CONFIG, metrics.SUCCESS, metrics.NOT_APPLICABLE) ++ return nil ++} ++ + func (c *client) SentinelCheckQuorum(ip, masterName string, tlsConfig *tls.Config) error { + + options := &rediscli.Options{ +diff --git a/service/redis/password_test.go b/service/redis/password_test.go +new file mode 100644 +index 0000000..80061d4 +--- /dev/null ++++ b/service/redis/password_test.go +@@ -0,0 +1,113 @@ ++package redis ++ ++import ( ++ "errors" ++ "testing" ++ ++ "github.com/stretchr/testify/assert" ++) ++ ++func TestParseDefaultUser(t *testing.T) { ++ reply := []interface{}{ ++ "flags", []interface{}{"on", "sanitize-payload"}, ++ "passwords", []interface{}{"aa", "bb"}, ++ "commands", "+@all", ++ } ++ got, err := parseDefaultUser(reply) ++ assert.NoError(t, err) ++ assert.Equal(t, DefaultUserPasswords{Hashes: []string{"aa", "bb"}}, got) ++ ++ got, err = parseDefaultUser([]interface{}{"flags", []interface{}{"on", "nopass"}, "passwords", []interface{}{}}) ++ assert.NoError(t, err) ++ assert.Equal(t, DefaultUserPasswords{NoPass: true}, got) ++ ++ _, err = parseDefaultUser("OK") ++ assert.Error(t, err) ++} ++ ++func TestIsAuthError(t *testing.T) { ++ assert.True(t, IsAuthError(errors.New("WRONGPASS invalid username-password pair or user is disabled."))) ++ assert.True(t, IsAuthError(errors.New("NOAUTH Authentication required."))) ++ assert.False(t, IsAuthError(errors.New("dial tcp 10.0.0.1:6379: connect: connection refused"))) ++ assert.False(t, IsAuthError(nil)) ++} ++ ++func TestParseUserACL(t *testing.T) { ++ // Redis 7 and Valkey: keys, channels and commands as strings. ++ got, err := parseUserACL([]interface{}{ ++ "flags", []interface{}{"on", "sanitize-payload"}, ++ "passwords", []interface{}{"aa"}, ++ "commands", "+@all", ++ "keys", "~*", ++ "channels", "&*", ++ "selectors", []interface{}{}, ++ }) ++ assert.NoError(t, err) ++ assert.Equal(t, UserACL{Exists: true, On: true, Hashes: []string{"aa"}, Keys: "~*", Channels: "&*", Commands: "+@all"}, got) ++ ++ // Redis 6: keys and channels as lists; an extra selector is counted. ++ got, err = parseUserACL([]interface{}{ ++ "flags", []interface{}{"off", "nopass"}, ++ "passwords", []interface{}{}, ++ "commands", "-@all +ping", ++ "keys", []interface{}{"~a", "~b"}, ++ "channels", []interface{}{}, ++ "selectors", []interface{}{[]interface{}{"commands", "+get"}}, ++ }) ++ assert.NoError(t, err) ++ assert.Equal(t, UserACL{Exists: true, NoPass: true, Keys: "~a ~b", Commands: "-@all +ping", Selectors: 1}, got) ++ ++ // No such user. ++ got, err = parseUserACL(nil) ++ assert.NoError(t, err) ++ assert.False(t, got.Exists) ++} ++ ++func TestParseClientUsers(t *testing.T) { ++ list := "id=3 addr=10.0.1.1:41000 laddr=10.0.0.1:6379 fd=8 name= age=9 user=rf-internal\n" + ++ "id=4 addr=10.0.1.1:41002 laddr=10.0.0.1:6379 fd=9 name= age=9 user=default\n" + ++ "id=5 addr=[fd00::7]:5000 laddr=[fd00::1]:6379 fd=10 user=rf-internal\n" ++ assert.Equal(t, map[string][]string{ ++ "10.0.1.1": {"rf-internal", "default"}, ++ "fd00::7": {"rf-internal"}, ++ }, parseClientUsers(list)) ++} ++ ++// The whole change is one transaction, users first, the kill last, and the ++// kill keeps the default SKIPME yes so the transaction's own connection ++// survives it. ++func TestClientPasswordChangeCommands(t *testing.T) { ++ got := clientPasswordChange("new", ++ []ACLUser{{Name: "rf-internal", Rules: []string{"on", "#aa"}}, {Name: "rf-exporter", Rules: []string{"on", "#bb"}}}, ++ []string{"backdoor", "spare"}, ++ []string{"default", "rf-exporter"}) ++ assert.Equal(t, [][]interface{}{ ++ {"ACL", "SETUSER", "rf-internal", "reset", "on", "#aa"}, ++ {"ACL", "SETUSER", "rf-exporter", "reset", "on", "#bb"}, ++ {"ACL", "DELUSER", "backdoor", "spare"}, ++ {"CONFIG", "SET", "requirepass", "new"}, ++ {"CLIENT", "KILL", "USER", "default"}, ++ {"CLIENT", "KILL", "USER", "rf-exporter"}, ++ }, got) ++ ++ // No foreign user, no ACL DELUSER: it takes at least one name. ++ got = clientPasswordChange("new", nil, nil, []string{"default"}) ++ assert.Equal(t, [][]interface{}{ ++ {"CONFIG", "SET", "requirepass", "new"}, ++ {"CLIENT", "KILL", "USER", "default"}, ++ }, got) ++} ++ ++func TestParseClients(t *testing.T) { ++ list := "id=3 addr=10.0.1.1:41000 laddr=10.0.0.1:6379 fd=8 name=sentinel-1-cmd age=9 flags=N db=0 cmd=ping user=rf-internal\n" + ++ "id=4 addr=10.0.0.2:50000 laddr=10.0.0.1:6379 fd=9 name= age=9 flags=S db=0 cmd=replconf user=rf-internal\n" + ++ "id=5 addr=[fd00::7]:5000 laddr=[fd00::1]:6379 fd=10 flags=O db=0 cmd=monitor user=pinger\n" + ++ "id=6 addr=/tmp/redis.sock:0 laddr=/tmp/redis.sock:0 fd=11 flags=N db=0 cmd=info user=rf-internal\n" + ++ "\n" ++ assert.Equal(t, []ClientInfo{ ++ {ID: "3", Host: "10.0.1.1", User: "rf-internal", Flags: "N"}, ++ {ID: "4", Host: "10.0.0.2", User: "rf-internal", Flags: "S"}, ++ {ID: "5", Host: "fd00::7", User: "pinger", Flags: "O"}, ++ {ID: "6", Host: "/tmp/redis.sock", User: "rf-internal", Flags: "N"}, ++ }, parseClients(list)) ++} diff --git a/packages/system/redis-rd/cozyrds/redis.yaml b/packages/system/redis-rd/cozyrds/redis.yaml index 92eead0bb..768fd25b1 100644 --- a/packages/system/redis-rd/cozyrds/redis.yaml +++ b/packages/system/redis-rd/cozyrds/redis.yaml @@ -8,7 +8,7 @@ spec: plural: redises singular: redis openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Redis replicas. Three Sentinels watch them, or a single one when `replicas` is 1, since a lone pod has no replica to fail over to.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each Redis replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"affinity":{"description":"Kubernetes affinity configuration for Redis and Sentinel pods.","type":"object","default":{},"properties":{"redis":{"description":"Kubernetes Affinity for Redis pods. When set, redis-operator uses it verbatim and does not add its default soft podAntiAffinity; include podAntiAffinity unless replica co-location is intended.","type":"object","default":{},"x-kubernetes-preserve-unknown-fields":true},"sentinel":{"description":"Kubernetes Affinity for Sentinel pods. When set, redis-operator uses it verbatim and does not add its default soft podAntiAffinity; include podAntiAffinity unless replica co-location is intended.","type":"object","default":{},"x-kubernetes-preserve-unknown-fields":true}}},"size":{"description":"Persistent Volume Claim size available for application data.","default":"1Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster. Can be enabled only when the instance is created, together with `tls.enabled: true`; turning it on for an existing instance, or changing `tls.enabled` while it is on, is refused at admission.","type":"boolean","default":false},"version":{"description":"Redis major version to deploy. The Redis and Sentinel pods run the same image.","type":"string","default":"v8","enum":["v8","v7"]},"tls":{"description":"TLS configuration. TLS is opt-in and is not inferred from `external`.","type":"object","default":{},"properties":{"authClients":{"description":"Maps to the Redis `tls-auth-clients` directive. Defaults to `no` — the server certificate is presented but client certificates are not validated. `yes` requires a client certificate signed by this release's CA, which the platform does not issue. Changing it restarts the Redis and Sentinel pods, because the directive is read from the config file once at startup.","type":"string","enum":["no","optional","yes"]},"enabled":{"description":"Enable TLS for Redis and Sentinel connections. Disabled unless set. Enabling it moves Redis and Sentinel to a TLS-only listener, so existing plaintext clients must be migrated at the same time. Encryption is provided by the redis-operator fork that mounts the certificate Secret into both Redis and Sentinel pods at `/tls`.","type":"boolean"}}},"authEnabled":{"description":"Enable password generation.","type":"boolean","default":true},"minReplicasToWrite":{"description":"Redis `min-replicas-to-write`: the master refuses writes unless at least this many replicas are connected and within `minReplicasMaxLag`. Unset by default, which leaves the Redis default (disabled). With `replicas: 2` and a value of 1 the master rejects writes while its only replica is down, trading availability for a bound on the writes lost if an isolated master is failed over. Replication stays asynchronous, so this bounds the loss, it does not remove it. Must be 0 or more and below `replicas` (a master with `replicas` pods has `replicas - 1` replicas), otherwise every write is refused; the chart refuses such a value.","type":"integer","minimum":0},"minReplicasMaxLag":{"description":"Redis `min-replicas-max-lag`, in seconds: a replica whose last acknowledgement is older than this does not count towards `minReplicasToWrite`. Unset by default, which leaves the Redis default (10). Has no effect unless `minReplicasToWrite` is set. Must be at least 1 when `minReplicasToWrite` is set: Redis treats 0 as disabling the check, so the chart refuses it.","type":"integer","minimum":0},"maxmemory":{"description":"Redis `maxmemory`: the dataset size at which Redis applies `maxmemoryPolicy`. Unset by default, which renders `maxmemory 0` (no limit, the Redis default), so a value set by hand with `CONFIG SET` is reset on the next reconcile. Must be at most 90% of the memory request of each Redis pod (from `resources` or `resourcesPreset`): the operator silently drops a larger value, so the chart refuses it. Leave headroom below that for replication and snapshot buffers.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"maxmemoryPolicy":{"description":"Redis `maxmemory-policy`: what Redis does once `maxmemory` is reached. `noeviction` refuses writes; `allkeys-lru` evicts the least recently used keys, which suits an instance used purely as a cache. Has no effect while `maxmemory` is unset.","type":"string","default":"noeviction","enum":["noeviction","allkeys-lru","allkeys-lfu","allkeys-random","volatile-lru","volatile-lfu","volatile-random","volatile-ttl"]},"snapshots":{"description":"Write RDB snapshots to the persistent volume (the Redis `save` directive, with the Redis default schedule). Set to `false` for an instance used purely as a cache: `save \"\"` is rendered and the volume is kept, so no further scheduled snapshot is written while replicas still have room for the full-sync RDB they write to disk. An RDB file already on the volume is not removed, and Redis loads it on restart, so turning snapshots off does not by itself empty the dataset. Always off when `size` is empty.","type":"boolean","default":true},"sentinel":{"description":"Sentinel configuration. When `sentinel.resources` is empty and `sentinel.resourcesPreset` is unset, the Sentinel pods are sized like the Redis pods (`resources` and `resourcesPreset`). An empty `sentinel.resources` map counts as unset, as an empty top-level `resources` does.","type":"object","default":{},"properties":{"resources":{"description":"Explicit CPU and memory configuration for each Sentinel pod. Keys left out are filled from the preset in `sentinel.resourcesPreset`.","type":"object","properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Sizing preset for the Sentinel pods. Defaults to `resourcesPreset`.","type":"string","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]}}},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Redis replicas. Three Sentinels watch them, or a single one when `replicas` is 1, since a lone pod has no replica to fail over to.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each Redis replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"affinity":{"description":"Kubernetes affinity configuration for Redis and Sentinel pods.","type":"object","default":{},"properties":{"redis":{"description":"Kubernetes Affinity for Redis pods. When set, redis-operator uses it verbatim and does not add its default soft podAntiAffinity; include podAntiAffinity unless replica co-location is intended.","type":"object","default":{},"x-kubernetes-preserve-unknown-fields":true},"sentinel":{"description":"Kubernetes Affinity for Sentinel pods. When set, redis-operator uses it verbatim and does not add its default soft podAntiAffinity; include podAntiAffinity unless replica co-location is intended.","type":"object","default":{},"x-kubernetes-preserve-unknown-fields":true}}},"size":{"description":"Persistent Volume Claim size available for application data.","default":"1Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster. Can be enabled only when the instance is created, together with `tls.enabled: true`; turning it on for an existing instance, or changing `tls.enabled` while it is on, is refused at admission.","type":"boolean","default":false},"version":{"description":"Redis major version to deploy. The Redis and Sentinel pods run the same image.","type":"string","default":"v8","enum":["v8","v7"]},"tls":{"description":"TLS configuration. TLS is opt-in and is not inferred from `external`.","type":"object","default":{},"properties":{"authClients":{"description":"Maps to the Redis `tls-auth-clients` directive. Defaults to `no` — the server certificate is presented but client certificates are not validated. `yes` requires a client certificate signed by this release's CA, which the platform does not issue. Changing it restarts the Redis and Sentinel pods, because the directive is read from the config file once at startup.","type":"string","enum":["no","optional","yes"]},"enabled":{"description":"Enable TLS for Redis and Sentinel connections. Disabled unless set. Enabling it moves Redis and Sentinel to a TLS-only listener, so existing plaintext clients must be migrated at the same time. Encryption is provided by the redis-operator fork that mounts the certificate Secret into both Redis and Sentinel pods at `/tls`.","type":"boolean"}}},"authEnabled":{"description":"Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password.","type":"boolean","default":true},"minReplicasToWrite":{"description":"Redis `min-replicas-to-write`: the master refuses writes unless at least this many replicas are connected and within `minReplicasMaxLag`. Unset by default, which leaves the Redis default (disabled). With `replicas: 2` and a value of 1 the master rejects writes while its only replica is down, trading availability for a bound on the writes lost if an isolated master is failed over. Replication stays asynchronous, so this bounds the loss, it does not remove it. Must be 0 or more and below `replicas` (a master with `replicas` pods has `replicas - 1` replicas), otherwise every write is refused; the chart refuses such a value.","type":"integer","minimum":0},"minReplicasMaxLag":{"description":"Redis `min-replicas-max-lag`, in seconds: a replica whose last acknowledgement is older than this does not count towards `minReplicasToWrite`. Unset by default, which leaves the Redis default (10). Has no effect unless `minReplicasToWrite` is set. Must be at least 1 when `minReplicasToWrite` is set: Redis treats 0 as disabling the check, so the chart refuses it.","type":"integer","minimum":0},"maxmemory":{"description":"Redis `maxmemory`: the dataset size at which Redis applies `maxmemoryPolicy`. Unset by default, which renders `maxmemory 0` (no limit, the Redis default), so a value set by hand with `CONFIG SET` is reset on the next reconcile. Must be at most 90% of the memory request of each Redis pod (from `resources` or `resourcesPreset`): the operator silently drops a larger value, so the chart refuses it. Leave headroom below that for replication and snapshot buffers.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"maxmemoryPolicy":{"description":"Redis `maxmemory-policy`: what Redis does once `maxmemory` is reached. `noeviction` refuses writes; `allkeys-lru` evicts the least recently used keys, which suits an instance used purely as a cache. Has no effect while `maxmemory` is unset.","type":"string","default":"noeviction","enum":["noeviction","allkeys-lru","allkeys-lfu","allkeys-random","volatile-lru","volatile-lfu","volatile-random","volatile-ttl"]},"snapshots":{"description":"Write RDB snapshots to the persistent volume (the Redis `save` directive, with the Redis default schedule). Set to `false` for an instance used purely as a cache: `save \"\"` is rendered and the volume is kept, so no further scheduled snapshot is written while replicas still have room for the full-sync RDB they write to disk. An RDB file already on the volume is not removed, and Redis loads it on restart, so turning snapshots off does not by itself empty the dataset. Always off when `size` is empty.","type":"boolean","default":true},"sentinel":{"description":"Sentinel configuration. When `sentinel.resources` is empty and `sentinel.resourcesPreset` is unset, the Sentinel pods are sized like the Redis pods (`resources` and `resourcesPreset`). An empty `sentinel.resources` map counts as unset, as an empty top-level `resources` does.","type":"object","default":{},"properties":{"resources":{"description":"Explicit CPU and memory configuration for each Sentinel pod. Keys left out are filled from the preset in `sentinel.resourcesPreset`.","type":"object","properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Sizing preset for the Sentinel pods. Defaults to `resourcesPreset`.","type":"string","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]}}},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63}}} release: prefix: redis- labels: @@ -59,9 +59,11 @@ spec: # of its labels, so it is the one of the three a lineage walk can # resolve at all. - redis-{{ .name }}.ca-cert + # The operator's internal account, which replication, the Sentinels, + # the probes and the exporter authenticate with. It carries an + # ownerReference to the RedisFailover, as the CA-only copy does. + - rfr-redis-{{ .name }}-internal include: - - resourceNames: - - redis-{{ .name }}-auth # The key-free trust anchor the CA-extraction controller publishes. This # is the single, engine-agnostic selector every converged engine shares; # it carries no per-release name templating. diff --git a/packages/system/valkey-rd/cozyrds/valkey.yaml b/packages/system/valkey-rd/cozyrds/valkey.yaml index bb1036dd8..a621a3b03 100644 --- a/packages/system/valkey-rd/cozyrds/valkey.yaml +++ b/packages/system/valkey-rd/cozyrds/valkey.yaml @@ -8,7 +8,7 @@ spec: plural: valkeys singular: valkey openAPISchema: |- - {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Valkey replicas.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each Valkey replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"1Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"Valkey major version to deploy","type":"string","default":"v8","enum":["v8","v7"]},"authEnabled":{"description":"Enable password generation.","type":"boolean","default":true},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63}}} + {"title":"Chart Values","type":"object","properties":{"replicas":{"description":"Number of Valkey replicas.","type":"integer","default":2},"resources":{"description":"Explicit CPU and memory configuration for each Valkey replica. When omitted, the preset defined in `resourcesPreset` is applied.","type":"object","default":{},"properties":{"cpu":{"description":"CPU available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"memory":{"description":"Memory (RAM) available to each replica.","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}}},"resourcesPreset":{"description":"Default sizing preset used when `resources` is omitted.","type":"string","default":"t1.nano","enum":["t1.nano","t1.micro","t1.small","t1.medium","t1.large","t1.xlarge","t1.2xlarge","t1.4xlarge","c1.nano","c1.micro","c1.small","c1.medium","c1.large","c1.xlarge","c1.2xlarge","c1.4xlarge","s1.nano","s1.micro","s1.small","s1.medium","s1.large","s1.xlarge","s1.2xlarge","s1.4xlarge","u1.nano","u1.micro","u1.small","u1.medium","u1.large","u1.xlarge","u1.2xlarge","u1.4xlarge","m1.nano","m1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m1.2xlarge","m1.4xlarge","nano","micro","small","medium","large","xlarge","2xlarge"]},"size":{"description":"Persistent Volume Claim size available for application data.","default":"1Gi","pattern":"^(\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\\+|-)?(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))))?$","anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true},"storageClass":{"description":"StorageClass used to store the data.","type":"string","default":"","x-kubernetes-validations":[{"rule":"self == oldSelf","message":"storageClass is immutable"}],"x-cozystack-options":{"source":"storageclass"}},"external":{"description":"Enable external access from outside the cluster.","type":"boolean","default":false},"version":{"description":"Valkey major version to deploy","type":"string","default":"v8","enum":["v8","v7"]},"authEnabled":{"description":"Require a password. The password of the `default` user is issued through the credentials API, and issuing a new one takes effect without restarting anything. Replication, the Sentinels and the metrics exporter use an internal account of their own; backups use the `default` password.","type":"boolean","default":true},"schedulingClass":{"description":"Name of a SchedulingClass CR (cluster-scoped, group cozystack.io) used in place of the tenant's for this application's pods. A pod gets its class when it is created, so running pods keep theirs until they are recreated. Must be the tenant's own class or one listed in the tenant's `allowedSchedulingClasses`. Setting any other value is refused, and the pods of an application whose class is not, or no longer, in that list get the tenant's class. Empty means inherit from the tenant.","type":"string","default":"","maxLength":63}}} release: prefix: valkey- labels: @@ -27,10 +27,13 @@ spec: icon: PHN2ZyB3aWR0aD0iMTQ0IiBoZWlnaHQ9IjE0NCIgdmlld0JveD0iMCAwIDE0NCAxNDQiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CiAgPHJlY3Qgd2lkdGg9IjE0NCIgaGVpZ2h0PSIxNDQiIHJ4PSIyNCIgZmlsbD0idXJsKCN2YWxrZXlfYmcpIi8+CiAgPHBhdGggZD0iTTM2IDQwaDE4bDE4IDQ0IDE4LTQ0aDE4TDgwIDEwOGgtMTZMMzYgNDB6IiBmaWxsPSIjZmZmZmZmIi8+CiAgPGNpcmNsZSBjeD0iNzIiIGN5PSI1MiIgcj0iNyIgZmlsbD0iI2ZmZmZmZiIvPgogIDxkZWZzPgogICAgPGxpbmVhckdyYWRpZW50IGlkPSJ2YWxrZXlfYmciIHgxPSIwIiB5MT0iMCIgeDI9IjE0NCIgeTI9IjE0NCIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPgogICAgICA8c3RvcCBzdG9wLWNvbG9yPSIjN0EzQkZGIi8+CiAgICAgIDxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iI0M2MjQ5QiIvPgogICAgPC9saW5lYXJHcmFkaWVudD4KICA8L2RlZnM+Cjwvc3ZnPgo= keysOrder: [["apiVersion"], ["appVersion"], ["kind"], ["metadata"], ["metadata", "name"], ["spec", "replicas"], ["spec", "resources"], ["spec", "resourcesPreset"], ["spec", "size"], ["spec", "storageClass"], ["spec", "external"], ["spec", "version"], ["spec", "authEnabled"], ["spec", "schedulingClass"]] secrets: - exclude: [] - include: + exclude: + # The operator's internal account, which replication, the Sentinels, + # the probes and the exporter authenticate with. It carries an + # ownerReference to the RedisFailover, so a lineage walk resolves it. - resourceNames: - - valkey-{{ .name }}-auth + - rfr-valkey-{{ .name }}-internal + include: [] services: exclude: [] include: diff --git a/pkg/apis/core/v1alpha1/credential_types.go b/pkg/apis/core/v1alpha1/credential_types.go index 26a0b31ce..af2525f51 100644 --- a/pkg/apis/core/v1alpha1/credential_types.go +++ b/pkg/apis/core/v1alpha1/credential_types.go @@ -136,6 +136,11 @@ type CredentialRequestStatus struct { // shown once. // +optional Password string `json:"password,omitempty"` + // AccessKeyID is the access key that goes with Password, for an account + // whose engine issues a key pair (a template with bucketAccess); present + // in a mint's answer only and shown once. + // +optional + AccessKeyID string `json:"accessKeyID,omitempty"` // IssuedAt is when the operation took effect in the record. IssuedAt metav1.Time `json:"issuedAt,omitempty"` } diff --git a/pkg/apiserver/apiserver.go b/pkg/apiserver/apiserver.go index a48a42c70..53d7829a0 100644 --- a/pkg/apiserver/apiserver.go +++ b/pkg/apiserver/apiserver.go @@ -117,6 +117,9 @@ type Config struct { GenericConfig *genericapiserver.RecommendedConfig ResourceConfig *config.ResourceConfig ServeSDN bool + // CredentialsCOSIWait bounds the wait of a mint or a revoke on an + // engine-issued credential; zero keeps the default. + CredentialsCOSIWait time.Duration } // CozyServer holds the state for the Kubernetes master/api server. @@ -125,9 +128,10 @@ type CozyServer struct { } type completedConfig struct { - GenericConfig genericapiserver.CompletedConfig - ResourceConfig *config.ResourceConfig - ServeSDN bool + GenericConfig genericapiserver.CompletedConfig + ResourceConfig *config.ResourceConfig + ServeSDN bool + CredentialsCOSIWait time.Duration } // CompletedConfig embeds a private pointer that cannot be created outside of this package. @@ -141,6 +145,7 @@ func (cfg *Config) Complete() CompletedConfig { cfg.GenericConfig.Complete(), cfg.ResourceConfig, cfg.ServeSDN, + cfg.CredentialsCOSIWait, } return CompletedConfig{&c} @@ -239,7 +244,7 @@ func (c completedConfig) New() (*CozyServer, error) { if err != nil { return nil, fmt.Errorf("failed to build dynamic client: %w", err) } - if err := InstallStaticAPIGroups(s.GenericAPIServer, cli, watchCli, dyn, c.ServeSDN); err != nil { + if err := InstallStaticAPIGroups(s.GenericAPIServer, cli, watchCli, dyn, c.ServeSDN, c.CredentialsCOSIWait); err != nil { return nil, err } @@ -261,7 +266,9 @@ func (c completedConfig) New() (*CozyServer, error) { // another server owns the group: kube-aggregator still merges this server's // /openapi/v3 index, so both backends list the group-version and fetching its // OpenAPI fails on a redirect whenever the two disagree on the hash. -func InstallStaticAPIGroups(server *genericapiserver.GenericAPIServer, cli client.Client, watchCli client.WithWatch, dyn dynamic.Interface, serveSDN bool) error { +// credentialsCOSIWait bounds the wait of a mint or a revoke on an +// engine-issued credential; zero keeps the default. +func InstallStaticAPIGroups(server *genericapiserver.GenericAPIServer, cli client.Client, watchCli client.WithWatch, dyn dynamic.Interface, serveSDN bool, credentialsCOSIWait time.Duration) error { // --- static, cluster-scoped resource for core group --- coreV1alpha1Storage := map[string]rest.Storage{} coreV1alpha1Storage["tenantnamespaces"] = cozyregistry.RESTInPeace( @@ -283,6 +290,9 @@ func InstallStaticAPIGroups(server *genericapiserver.GenericAPIServer, cli clien tapstorage.NewREST(dyn), ) credentials := credentialstorage.NewREST(cli, watchCli) + if credentialsCOSIWait > 0 { + credentials.SetCOSIWait(credentialsCOSIWait) + } coreV1alpha1Storage["credentials"] = cozyregistry.RESTInPeace(credentials) coreV1alpha1Storage["credentials/mint"] = credentialstorage.NewMintREST(credentials) coreV1alpha1Storage["credentials/revoke"] = credentialstorage.NewRevokeREST(credentials) diff --git a/pkg/cmd/server/serve_sdn_test.go b/pkg/cmd/server/serve_sdn_test.go index 0a12b1f15..3512b303d 100644 --- a/pkg/cmd/server/serve_sdn_test.go +++ b/pkg/cmd/server/serve_sdn_test.go @@ -63,7 +63,7 @@ func startStaticGroupsServer(t *testing.T, serveSDN bool) *httptest.Server { } cli := fake.NewClientBuilder().Build() dyn := dynamicfake.NewSimpleDynamicClient(runtime.NewScheme()) - if err := apiserver.InstallStaticAPIGroups(srv, cli, cli, dyn, serveSDN); err != nil { + if err := apiserver.InstallStaticAPIGroups(srv, cli, cli, dyn, serveSDN, 0); err != nil { t.Fatal(err) } srv.PrepareRun() diff --git a/pkg/cmd/server/start.go b/pkg/cmd/server/start.go index 327446e6f..99bac2539 100644 --- a/pkg/cmd/server/start.go +++ b/pkg/cmd/server/start.go @@ -35,6 +35,7 @@ import ( sdnv1alpha1 "github.com/cozystack/cozystack/pkg/apis/sdn/v1alpha1" "github.com/cozystack/cozystack/pkg/apiserver" "github.com/cozystack/cozystack/pkg/config" + credentialstorage "github.com/cozystack/cozystack/pkg/registry/core/credential" "github.com/spf13/cobra" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" @@ -78,6 +79,12 @@ type CozyServerOptions struct { // ServeSDN installs the sdn.cozystack.io group; off where another // aggregated server owns it. ServeSDN bool + + // CredentialsCOSIWait bounds how long a mint or a revoke of an + // engine-issued credential waits for cozystack-controller to serve it, + // with a new grant or with the old one gone, before it answers a retryable + // timeout. + CredentialsCOSIWait time.Duration } // NewCozyServerOptions returns a new instance of CozyServerOptions @@ -176,6 +183,9 @@ func NewCommandStartCozyServer(ctx context.Context, defaults *CozyServerOptions) flags.IntVar(&o.HelmReleaseMaxHistory, "helmrelease-max-history", o.HelmReleaseMaxHistory, "Number of release revisions Helm keeps for HelmReleases generated from Application "+ "resources (Spec.MaxHistory). 0 means unlimited; 5 matches Helm's default.") + flags.DurationVar(&o.CredentialsCOSIWait, "credentials-cosi-wait", credentialstorage.DefaultCOSIWait, + "How long a mint or a revoke of a credential whose keys a COSI driver issues waits for "+ + "cozystack-controller to serve it before it answers a retryable timeout.") flags.BoolVar(&o.ServeSDN, "serve-sdn", o.ServeSDN, "Serve the sdn.cozystack.io API group. Turn off where another aggregated API server owns the group.") @@ -496,9 +506,10 @@ func (o *CozyServerOptions) Config() (*apiserver.Config, error) { } config := &apiserver.Config{ - GenericConfig: serverConfig, - ResourceConfig: o.ResourceConfig, - ServeSDN: o.ServeSDN, + GenericConfig: serverConfig, + ResourceConfig: o.ResourceConfig, + ServeSDN: o.ServeSDN, + CredentialsCOSIWait: o.CredentialsCOSIWait, } return config, nil } diff --git a/pkg/credentials/account/account.go b/pkg/credentials/account/account.go index 88012e5d9..3afaf053f 100644 --- a/pkg/credentials/account/account.go +++ b/pkg/credentials/account/account.go @@ -59,6 +59,30 @@ const ( PasswordKey = "password" ) +// What the API and the controller share about an engine-issued account, one +// whose template names a BucketAccess and whose keys the COSI driver issues: +// the secret key is the password, stored as issued in the plaintext format, +// the access key sits beside it, and a mint or a revoke is a request the +// controller serves by re-creating the BucketAccess, or, for a revoke, by +// deleting it. +const ( + // BucketAccessAnnotation on an account Secret names the BucketAccess whose + // grant issues its keys, which marks the account engine-issued. + BucketAccessAnnotation = "credentials.cozystack.io/bucket-access" + // AccessKeyIDKey holds the access key that goes with the password. + AccessKeyIDKey = "accessKeyID" + // RequestAnnotation carries the id of the latest mint or revoke, which the + // API writes with the Secret and the controller puts on the BucketAccess + // it creates to serve it. + RequestAnnotation = "credentials.cozystack.io/request" + // GrantedAnnotation carries the request id the Secret's keys were issued + // for; the API returns them only to the request that id names. + GrantedAnnotation = "credentials.cozystack.io/granted" + // AdoptLabel on a BucketAccess lets the controller take over one the + // chart rendered before the conversion, keeping its keys. + AdoptLabel = "credentials.cozystack.io/adopt" +) + var nonNameChars = regexp.MustCompile(`[^a-z0-9-]`) // Account is one tenant account of an application. @@ -206,3 +230,9 @@ func IsAccountValuesFrom(ref helmv2.ValuesReference) bool { func IsAccountSecret(sec *corev1.Secret) bool { return sec != nil && sec.Labels[AccountLabel] == "true" } + +// IsEngineIssued reports whether an account Secret belongs to an account +// whose keys the COSI driver issues. +func IsEngineIssued(sec *corev1.Secret) bool { + return sec != nil && sec.Annotations[BucketAccessAnnotation] != "" +} diff --git a/pkg/generated/openapi/zz_generated.openapi.go b/pkg/generated/openapi/zz_generated.openapi.go index 511e8bf8b..6de2f7f33 100644 --- a/pkg/generated/openapi/zz_generated.openapi.go +++ b/pkg/generated/openapi/zz_generated.openapi.go @@ -635,6 +635,13 @@ func schema_pkg_apis_core_v1alpha1_CredentialRequestStatus(ref common.ReferenceC Format: "", }, }, + "accessKeyID": { + SchemaProps: spec.SchemaProps{ + Description: "AccessKeyID is the access key that goes with Password, for an account whose engine issues a key pair (a template with bucketAccess); present in a mint's answer only and shown once.", + Type: []string{"string"}, + Format: "", + }, + }, "issuedAt": { SchemaProps: spec.SchemaProps{ Description: "IssuedAt is when the operation took effect in the record.", diff --git a/pkg/registry/apps/application/rest.go b/pkg/registry/apps/application/rest.go index 9afac7902..9a79cb93f 100644 --- a/pkg/registry/apps/application/rest.go +++ b/pkg/registry/apps/application/rest.go @@ -2369,6 +2369,7 @@ var removedUserPasswordKinds = map[string]string{ mariadbKind: mintedPasswordWarning, clickhouseKind: mintedPasswordWarning, mongodbKind: mintedPasswordWarning, + rabbitmqKind: mintedPasswordWarning, } // mintedPasswordWarning is the warning of a kind whose user passwords the @@ -2379,6 +2380,7 @@ const mintedPasswordWarning = "spec.users[%q].password is ignored: passwords are const ( clickhouseKind = "ClickHouse" mongodbKind = "MongoDB" + rabbitmqKind = "RabbitMQ" postgresKind = "Postgres" mariadbKind = "MariaDB" ) diff --git a/pkg/registry/apps/application/rest_warn_removed_password_callsite_test.go b/pkg/registry/apps/application/rest_warn_removed_password_callsite_test.go index 399c4816a..d4b431e70 100644 --- a/pkg/registry/apps/application/rest_warn_removed_password_callsite_test.go +++ b/pkg/registry/apps/application/rest_warn_removed_password_callsite_test.go @@ -164,6 +164,7 @@ func TestWarnRemovedUserPasswords(t *testing.T) { }{ {"postgres warns", postgresKind, rawWithPassword, true}, {"mariadb warns", mariadbKind, rawWithPassword, true}, + {"rabbitmq warns", rabbitmqKind, rawWithPassword, true}, {"mongodb warns", mongodbKind, rawWithPassword, true}, {"clickhouse warns", clickhouseKind, rawWithPassword, true}, {"other kind stays quiet", "Redis", rawWithPassword, false}, @@ -197,7 +198,7 @@ func TestWarnRemovedUserPasswords(t *testing.T) { // mint on the user's Credential: its -credentials Secret holds no user // password a tenant can read, so naming it sends the reader to a dead end. func TestWarnRemovedUserPasswords_PointsAtMint(t *testing.T) { - for _, kind := range []string{postgresKind, clickhouseKind, mariadbKind, mongodbKind} { + for _, kind := range []string{postgresKind, clickhouseKind, mariadbKind, mongodbKind, rabbitmqKind} { t.Run(kind, func(t *testing.T) { r := &REST{kindName: kind} app := &appsv1alpha1.Application{Spec: &apiextv1.JSON{Raw: []byte(`{"users":{"app":{"password":"hackme"}}}`)}} diff --git a/pkg/registry/core/credential/cosi.go b/pkg/registry/core/credential/cosi.go new file mode 100644 index 000000000..c8e97f25c --- /dev/null +++ b/pkg/registry/core/credential/cosi.go @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: Apache-2.0 + +package credential + +import ( + "context" + "crypto/rand" + "encoding/hex" + "fmt" + "time" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/wait" + + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" + "github.com/cozystack/cozystack/pkg/credentials/account" +) + +// DefaultCOSIWait is how long a mint or a revoke of an engine-issued +// credential waits to be served unless cozystack-api is told otherwise. A COSI +// grant or revoke usually takes seconds. +const DefaultCOSIWait = 60 * time.Second + +// regrant performs a mint or a revoke on an account whose keys the COSI +// driver issues, which the API cannot choose. It writes the account Secret, +// rebuilt from the template without keys and carrying a fresh request id, in +// the one write every operation makes. cozystack-controller serves the +// request by deleting the BucketAccess, which revokes the keys the account +// held, and marks the Secret with the id: for a mint, once it has created a +// new BucketAccess and copied its keys into the Secret; for a revoke, once +// the old one is gone, leaving the account without keys until the next +// mint. The request waits for that mark. A mint reads the keys back and +// returns them, once: no other request carries the id, so no later caller +// is shown them. A revoke returns none. A wait that runs out answers a +// retryable timeout and shows nothing; the controller still serves the +// request, and the next mint or revoke supersedes it. +func (o *OperationREST) regrant(ctx context.Context, name string, res *resolved, by, mirrored string) (*corev1alpha1.CredentialRequest, error) { + r := o.parent + tmpl := res.tmpl + id, err := requestID() + if err != nil { + return nil, apierrors.NewInternalError(err) + } + now := metav1.NewTime(r.now()) + sec := buildSecret(tmpl, "", recordOf(tmpl).Apply(o.op, now, by)) + delete(sec.Data, account.PasswordKey) + sec.Annotations[account.BucketAccessAnnotation] = tmpl.Spec.BucketAccess.Name + sec.Annotations[account.RequestAnnotation] = id + if err := o.write(ctx, name, sec, mirrored); err != nil { + return nil, err + } + + reason := ReasonCredentialIssued + if o.op == corev1alpha1.CredentialOperationRevoke { + reason = ReasonCredentialRevoked + } + Emit(ctx, r.direct, res.hr, reason, tmpl.Spec.Username, by) + + mint := o.op == corev1alpha1.CredentialOperationMint + issued, err := o.awaitGrant(ctx, name, types.NamespacedName{Namespace: sec.Namespace, Name: sec.Name}, id, mint) + if err != nil { + return nil, err + } + if issued == nil && mint { + return nil, apierrors.NewTimeoutError(fmt.Sprintf( + "credential %s: the new keys were not issued within %s; they will not be shown, mint again", name, r.cosiWait), 1) + } + if issued == nil { + return nil, apierrors.NewTimeoutError(fmt.Sprintf( + "credential %s: the old keys were not revoked within %s; they keep working until cozystack-controller removes their BucketAccess, which it still does, and a new revoke waits for that again", name, r.cosiWait), 1) + } + + out := &corev1alpha1.CredentialRequest{ + TypeMeta: metav1.TypeMeta{APIVersion: corev1alpha1.SchemeGroupVersion.String(), Kind: "CredentialRequest"}, + Status: corev1alpha1.CredentialRequestStatus{Username: tmpl.Spec.Username, IssuedAt: now}, + } + if mint { + out.Status.Password = string(issued.Data[account.PasswordKey]) + out.Status.AccessKeyID = string(issued.Data[account.AccessKeyIDKey]) + } + return out, nil +} + +// awaitGrant polls the account Secret, uncached, until the controller marks +// it as served for the request id, holding keys when withKeys asks for them, +// and returns it; nil when the wait runs out. A Secret marked for another id +// means a later request took over, which is a conflict for this one. +func (o *OperationREST) awaitGrant(ctx context.Context, name string, key types.NamespacedName, id string, withKeys bool) (*corev1.Secret, error) { + r := o.parent + var issued *corev1.Secret + var lost bool + err := wait.PollUntilContextTimeout(ctx, r.cosiPoll, r.cosiWait, false, func(ctx context.Context) (bool, error) { + sec := &corev1.Secret{} + if err := r.direct.Get(ctx, key, sec); err != nil { + return false, client404(err) + } + if sec.Annotations[account.RequestAnnotation] != id { + lost = true + return true, nil + } + if sec.Annotations[account.GrantedAnnotation] == id && (!withKeys || len(sec.Data[account.PasswordKey]) > 0) { + issued = sec + return true, nil + } + return false, nil + }) + if lost { + return nil, apierrors.NewConflict(r.gvr.GroupResource(), name, + fmt.Errorf("another request on this credential took over before its keys were issued; retry")) + } + if issued != nil { + return issued, nil + } + if err != nil && !wait.Interrupted(err) { + return nil, err + } + return nil, nil +} + +// client404 keeps polling through a Secret that is momentarily missing. +func client404(err error) error { + if apierrors.IsNotFound(err) { + return nil + } + return err +} + +func requestID() (string, error) { + b := make([]byte, 16) + if _, err := rand.Read(b); err != nil { + return "", err + } + return hex.EncodeToString(b), nil +} diff --git a/pkg/registry/core/credential/cosi_test.go b/pkg/registry/core/credential/cosi_test.go new file mode 100644 index 000000000..d9a6e20d0 --- /dev/null +++ b/pkg/registry/core/credential/cosi_test.go @@ -0,0 +1,229 @@ +// SPDX-License-Identifier: Apache-2.0 + +package credential + +import ( + "context" + "strings" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1" + "github.com/cozystack/cozystack/pkg/credentials/account" + "github.com/cozystack/cozystack/pkg/credentials/format" +) + +// cosiSeeded returns an engine-issued template with the account Secret the +// controller leaves after the first grant, and the status mirroring it. +func (f *fixture) cosiSeeded(t *testing.T) *cozyv1alpha1.CredentialTemplate { + t.Helper() + tmpl := template(cred, "web") + tmpl.Spec.Format.Name = format.Plaintext + tmpl.Spec.Secret = cozyv1alpha1.CredentialTemplateSecret{} + tmpl.Spec.BucketAccess = &cozyv1alpha1.CredentialTemplateBucketAccess{Name: release + "-web", BucketClaimName: release, BucketAccessClassName: "seaweedfs"} + if err := f.c.Create(f.ctx, tmpl); err != nil { + t.Fatal(err) + } + at := metav1.NewTime(f.r.now()) + sec := buildSecret(tmpl, "first-secret", account.Record{}.Apply(corev1alpha1.CredentialOperationCreate, at, "controller")) + sec.Data[account.AccessKeyIDKey] = []byte("AKIAFIRST") + sec.Annotations[account.GrantedAnnotation] = "" + sec.Annotations[account.BucketAccessAnnotation] = release + "-web" + if err := f.c.Create(f.ctx, sec); err != nil { + t.Fatal(err) + } + tmpl.Status.SecretResourceVersion = sec.ResourceVersion + if err := f.c.Status().Update(f.ctx, tmpl); err != nil { + t.Fatal(err) + } + f.mu.Lock() + f.writes = nil + f.mu.Unlock() + f.r.cosiPoll = 5 * time.Millisecond + f.r.cosiWait = 2 * time.Second + return tmpl +} + +// serveGrants does what cozystack-controller does for each request a mint or +// a revoke writes: it marks the Secret with the request id, storing a new key +// pair for a mint and none for a revoke, and mirrors the Secret's version into +// the template's status. It stops with the test. +func (f *fixture) serveGrants(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + key := types.NamespacedName{Namespace: ns, Name: cred + account.SecretSuffix} + n := 0 + go func() { + for ctx.Err() == nil { + time.Sleep(5 * time.Millisecond) + sec := &corev1.Secret{} + if err := f.c.Get(ctx, key, sec); err != nil { + continue + } + id := sec.Annotations[account.RequestAnnotation] + if id == "" || sec.Annotations[account.GrantedAnnotation] == id { + continue + } + n++ + if account.ReadRecord(sec).Origin != corev1alpha1.CredentialOriginRevoked { + sec.Data[account.PasswordKey] = []byte("secret-" + id) + sec.Data[account.AccessKeyIDKey] = []byte("AKIA" + string(rune('A'+n))) + } + sec.Annotations[account.GrantedAnnotation] = id + if err := f.c.Update(ctx, sec); err != nil { + continue + } + tmpl := &cozyv1alpha1.CredentialTemplate{} + if err := f.c.Get(ctx, types.NamespacedName{Namespace: ns, Name: cred}, tmpl); err == nil { + tmpl.Status.SecretResourceVersion = sec.ResourceVersion + _ = f.c.Status().Update(ctx, tmpl) + } + } + }() +} + +// awaitMirror waits until the template's status mirrors the account Secret. +func (f *fixture) awaitMirror(t *testing.T) { + t.Helper() + for deadline := time.Now().Add(2 * time.Second); time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) { + sec := f.secret(t, cred+account.SecretSuffix) + tmpl := &cozyv1alpha1.CredentialTemplate{} + if err := f.c.Get(f.ctx, types.NamespacedName{Namespace: ns, Name: cred}, tmpl); err != nil { + t.Fatal(err) + } + if tmpl.Status.SecretResourceVersion == sec.ResourceVersion { + return + } + } + t.Fatal("the status never mirrored the account Secret") +} + +func TestCOSIMintReturnsTheKeysOfItsOwnGrantOnce(t *testing.T) { + f := newFixture(t) + f.cosiSeeded(t) + f.serveGrants(t) + + first, err := f.do(NewMintREST(f.r), cred, "", false) + if err != nil { + t.Fatal(err) + } + f.mu.Lock() + firstWrite := f.writes[0] + f.mu.Unlock() + if firstWrite != "update "+cred+account.SecretSuffix { + t.Errorf("first write = %q, want the account Secret update", firstWrite) + } + if first.Status.Username != "web" || first.Status.Password == "" || first.Status.AccessKeyID == "" { + t.Fatalf("answer = %+v, want the new key pair", first.Status) + } + if first.Status.Password == "first-secret" || first.Status.AccessKeyID == "AKIAFIRST" { + t.Error("the mint returned the keys it replaced") + } + sec := f.secret(t, cred+account.SecretSuffix) + if string(sec.Data[account.PasswordKey]) != first.Status.Password { + t.Error("the answer is not what the Secret holds") + } + if rec := account.ReadRecord(sec); rec.Origin != corev1alpha1.CredentialOriginMinted || rec.By != "jane@example.org" { + t.Errorf("record = %+v", rec) + } + + // The controller mirrors the Secret into the status after marking it, so + // a mint that starts in between would be answered with a conflict. + f.awaitMirror(t) + second, err := f.do(NewMintREST(f.r), cred, "", false) + if err != nil { + t.Fatal(err) + } + if second.Status.Password == first.Status.Password || second.Status.AccessKeyID == first.Status.AccessKeyID { + t.Error("a second mint showed the first mint's keys again") + } +} + +func TestCOSIRevokeReturnsNoKeys(t *testing.T) { + f := newFixture(t) + f.cosiSeeded(t) + f.serveGrants(t) + + res, err := f.do(NewRevokeREST(f.r), cred, "", false) + if err != nil { + t.Fatal(err) + } + if res.Status.Password != "" || res.Status.AccessKeyID != "" { + t.Errorf("answer = %+v, want no keys", res.Status) + } + sec := f.secret(t, cred+account.SecretSuffix) + if _, held := sec.Data[account.PasswordKey]; held || len(sec.Data[account.AccessKeyIDKey]) > 0 { + t.Errorf("data = %v, want no keys after a revoke", sec.Data) + } + if id := sec.Annotations[account.RequestAnnotation]; id == "" || sec.Annotations[account.GrantedAnnotation] != id { + t.Errorf("annotations = %v, want the revoke served", sec.Annotations) + } + if rec := account.ReadRecord(sec); rec.Origin != corev1alpha1.CredentialOriginRevoked { + t.Errorf("record = %+v, want Revoked", rec) + } +} + +func TestCOSIRevokeThatOutwaitsTheControllerSaysTheKeysStillWork(t *testing.T) { + f := newFixture(t) + f.cosiSeeded(t) + f.r.cosiWait = 50 * time.Millisecond + + _, err := f.do(NewRevokeREST(f.r), cred, "", false) + if !apierrors.IsTimeout(err) || !strings.Contains(err.Error(), "keep working") { + t.Fatalf("err = %v, want a retryable timeout saying the keys still work", err) + } +} + +func TestCOSIRefusesACredentialWithAForeignBucketAccess(t *testing.T) { + f := newFixture(t) + tmpl := f.cosiSeeded(t) + meta.SetStatusCondition(&tmpl.Status.Conditions, metav1.Condition{ + Type: cozyv1alpha1.CredentialTemplateBucketAccessConflict, Status: metav1.ConditionTrue, Reason: "ForeignBucketAccess", + }) + if err := f.c.Status().Update(f.ctx, tmpl); err != nil { + t.Fatal(err) + } + for _, op := range []*OperationREST{NewMintREST(f.r), NewRevokeREST(f.r)} { + if _, err := f.do(op, cred, "", false); !apierrors.IsConflict(err) { + t.Fatalf("%s: err = %v, want a conflict", op.op, err) + } + } + f.mu.Lock() + defer f.mu.Unlock() + if len(f.writes) != 0 { + t.Errorf("writes = %v, want none", f.writes) + } +} + +func TestCOSIMintThatOutwaitsTheGrantShowsNothing(t *testing.T) { + f := newFixture(t) + f.cosiSeeded(t) + f.r.cosiWait = 50 * time.Millisecond + + _, err := f.do(NewMintREST(f.r), cred, "", false) + if !apierrors.IsTimeout(err) { + t.Fatalf("err = %v, want a retryable timeout", err) + } + sec := f.secret(t, cred+account.SecretSuffix) + if _, held := sec.Data[account.PasswordKey]; held { + t.Error("the Secret still holds keys the mint replaced") + } + if _, held := sec.Data[account.AccessKeyIDKey]; held { + t.Error("the Secret still holds an access key the mint replaced") + } + if sec.Annotations[account.RequestAnnotation] == "" { + t.Error("the mint wrote no request for the controller") + } + f.mu.Lock() + defer f.mu.Unlock() + if len(f.writes) != 1 { + t.Errorf("writes = %v, want the one Secret update", f.writes) + } +} diff --git a/pkg/registry/core/credential/rest.go b/pkg/registry/core/credential/rest.go index 0126818fb..7feff633c 100644 --- a/pkg/registry/core/credential/rest.go +++ b/pkg/registry/core/credential/rest.go @@ -3,8 +3,9 @@ // Package credential serves core.cozystack.io/credentials, a view over the // CredentialTemplates a kind's chart renders, with the mint and revoke // subresources. The view shows the account's record as the template's status -// mirrors it, and never reads a Secret. See design-proposals/user-secrets-api -// in cozystack/community. +// mirrors it, and reads no Secret but the one a mint of an engine-issued +// account waits on. See design-proposals/user-secrets-api in +// cozystack/community. package credential import ( @@ -56,6 +57,11 @@ type REST struct { direct client.Client gvr schema.GroupVersionResource now func() time.Time + // cosiWait bounds how long a mint or a revoke of an engine-issued + // credential waits for the controller to serve it; cosiPoll is how often + // it looks. + cosiWait time.Duration + cosiPoll time.Duration } // NewREST creates the credentials storage. @@ -68,10 +74,16 @@ func NewREST(c, direct client.Client) *REST { Version: "v1alpha1", Resource: "credentials", }, - now: time.Now, + now: time.Now, + cosiWait: DefaultCOSIWait, + cosiPoll: 500 * time.Millisecond, } } +// SetCOSIWait sets how long a mint or a revoke of an engine-issued credential +// waits for its new grant. +func (r *REST) SetCOSIWait(d time.Duration) { r.cosiWait = d } + func (*REST) NamespaceScoped() bool { return true } func (*REST) GetSingularName() string { return singularName } func (*REST) Destroy() {} diff --git a/pkg/registry/core/credential/rest_test.go b/pkg/registry/core/credential/rest_test.go index cce84140b..335403057 100644 --- a/pkg/registry/core/credential/rest_test.go +++ b/pkg/registry/core/credential/rest_test.go @@ -10,6 +10,7 @@ import ( "flag" "io" "strings" + "sync" "testing" "time" @@ -46,6 +47,7 @@ type fixture struct { c client.Client r *REST ctx context.Context + mu sync.Mutex writes []string } @@ -69,7 +71,9 @@ func newFixture(t *testing.T, objs ...client.Object) *fixture { record := func(verb string) func(ctx context.Context, c client.WithWatch, obj client.Object, _ ...any) { return func(_ context.Context, _ client.WithWatch, obj client.Object, _ ...any) { if _, isEvent := obj.(*corev1.Event); !isEvent { + f.mu.Lock() f.writes = append(f.writes, verb+" "+obj.GetName()) + f.mu.Unlock() } } } diff --git a/pkg/registry/core/credential/subresources.go b/pkg/registry/core/credential/subresources.go index 8f1158735..c3d496505 100644 --- a/pkg/registry/core/credential/subresources.go +++ b/pkg/registry/core/credential/subresources.go @@ -87,6 +87,16 @@ func (o *OperationREST) Create(ctx context.Context, name string, obj runtime.Obj return nil, apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf( "credential %s has a Secret it did not create; a platform administrator has to remove it first", name)) } + // A template that names a BucketAccess is engine-issued: the COSI driver, + // not the API, chooses its keys. + engineIssued := tmpl.Spec.BucketAccess != nil + if engineIssued && meta.IsStatusConditionTrue(tmpl.Status.Conditions, cozyv1alpha1.CredentialTemplateBucketAccessConflict) { + // The controller leaves a BucketAccess it did not create alone, so + // it could serve neither operation, and the request would only wait + // out its timeout. + return nil, apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf( + "credential %s has a BucketAccess it did not create; a platform administrator has to remove it first", name)) + } if !format.Known(tmpl.Spec.Format.Name) { return nil, apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf( "credential %s names the format %q, which is not built in", name, tmpl.Spec.Format.Name)) @@ -115,6 +125,10 @@ func (o *OperationREST) Create(ctx context.Context, name string, obj runtime.Obj }, nil } + if engineIssued { + return o.regrant(ctx, name, res, user.GetName(), mirrored) + } + password, err := format.GeneratePassword() if err != nil { return nil, apierrors.NewInternalError(err) @@ -126,26 +140,8 @@ func (o *OperationREST) Create(ctx context.Context, name string, obj runtime.Obj now := metav1.NewTime(r.now()) by := user.GetName() sec := buildSecret(tmpl, stored, recordOf(tmpl).Apply(o.op, now, by)) - - // The status is all the API knows of the Secret. A status that lags the - // Secret, or a Secret written since the status was read, makes the write - // fail rather than overwrite it, and the caller gets a conflict and no - // password. - if mirrored == "" { - if err := r.direct.Create(ctx, sec); err != nil { - if apierrors.IsAlreadyExists(err) { - return nil, apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf("credential %s is being seeded; retry", name)) - } - return nil, err - } - } else { - sec.ResourceVersion = mirrored - if err := r.direct.Update(ctx, sec); err != nil { - if apierrors.IsConflict(err) || apierrors.IsNotFound(err) { - return nil, apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf("credential %s changed while the request was in flight; retry", name)) - } - return nil, err - } + if err := o.write(ctx, name, sec, mirrored); err != nil { + return nil, err } reason := ReasonCredentialIssued @@ -168,6 +164,32 @@ func (o *OperationREST) Create(ctx context.Context, name string, obj runtime.Obj }, nil } +// write stores the account Secret under the version the template's status +// mirrors, or creates it when the account has none. The status is all the +// API knows of the Secret. A status that lags the Secret, or a Secret written +// since the status was read, makes the write fail rather than overwrite it, +// and the caller gets a conflict and no password. +func (o *OperationREST) write(ctx context.Context, name string, sec *corev1.Secret, mirrored string) error { + r := o.parent + if mirrored == "" { + if err := r.direct.Create(ctx, sec); err != nil { + if apierrors.IsAlreadyExists(err) { + return apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf("credential %s is being seeded; retry", name)) + } + return err + } + return nil + } + sec.ResourceVersion = mirrored + if err := r.direct.Update(ctx, sec); err != nil { + if apierrors.IsConflict(err) || apierrors.IsNotFound(err) { + return apierrors.NewConflict(r.gvr.GroupResource(), name, fmt.Errorf("credential %s changed while the request was in flight; retry", name)) + } + return err + } + return nil +} + // recordOf returns the record the template's status mirrors, which the mint // extends with its own operation. func recordOf(tmpl *cozyv1alpha1.CredentialTemplate) account.Record {