diff --git a/hack/e2e-chainsaw/redis/chainsaw-test.yaml b/hack/e2e-chainsaw/redis/chainsaw-test.yaml index feb45281e..61ac67dd0 100644 --- a/hack/e2e-chainsaw/redis/chainsaw-test.yaml +++ b/hack/e2e-chainsaw/redis/chainsaw-test.yaml @@ -523,7 +523,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 +537,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/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)) ++}