From 6d5401c50dcc4d9f0742e894922e1c2bdb6d2197 Mon Sep 17 00:00:00 2001
From: subhamkrai
Date: Mon, 23 Jun 2025 14:48:49 +0530
Subject: [PATCH] csi: automate CSI cephx key rotation
This PR implements the CSI cephx key rotation feature,
which follows overlapping rotation for non-daemon keys.
Refer to the cephx rotation API from design PR 15915 for details.
Signed-off-by: subhamkrai
---
Documentation/CRDs/specification.md | 124 +++++-
.../charts/rook-ceph/templates/resources.yaml | 67 +++
deploy/examples/crds.yaml | 67 +++
pkg/apis/ceph.rook.io/v1/types.go | 30 ++
.../ceph.rook.io/v1/zz_generated.deepcopy.go | 40 ++
pkg/daemon/ceph/client/auth.go | 29 ++
pkg/operator/ceph/cluster/cluster.go | 7 +-
pkg/operator/ceph/cluster/cluster_external.go | 2 +-
pkg/operator/ceph/cluster/controller.go | 2 +-
pkg/operator/ceph/csi/secrets.go | 352 +++++++++++++--
pkg/operator/ceph/csi/secrets_test.go | 400 +++++++++++++++++-
tests/scripts/collect-logs.sh | 1 +
12 files changed, 1078 insertions(+), 43 deletions(-)
diff --git a/Documentation/CRDs/specification.md b/Documentation/CRDs/specification.md
index 6197aba3f..1a9c25e49 100644
--- a/Documentation/CRDs/specification.md
+++ b/Documentation/CRDs/specification.md
@@ -4502,10 +4502,60 @@ One of Always, Never, IfNotPresent.
+CephXConfigWithPriorCount
+
+
+(Appears on:ClusterCephxConfig)
+
+
+
+
+
+
+| Field |
+Description |
+
+
+
+
+
+CephxConfig
+
+
+CephxConfig
+
+
+ |
+
+
+(Members of CephxConfig are embedded into this type.)
+
+ |
+
+
+
+keepPriorKeyCountMax
+
+byte
+
+ |
+
+(Optional)
+ KeepPriorKeyCountMax tells Rook how many prior keys to keep active.
+Generally, this would be set to 1 to allow for a migration period for applications.
+If desired, set this to 0 to delete prior keys after migration.
+This config only applies to prior keys that already exist.
+If PriorKeyCount is set to 2 while only a single key currently exists, only a single prior key will be kept,
+and the reported status will only indicate the actual number of prior keys,
+not necessarily a reflection of PriorKeyCount config here.
+ |
+
+
+
CephxConfig
-(Appears on:ClientSecuritySpec, ClusterCephxConfig)
+(Appears on:CephXConfigWithPriorCount, ClientSecuritySpec, ClusterCephxConfig)
@@ -4574,7 +4624,7 @@ are not rotated.
CephxStatus
-(Appears on:CephClientStatus, ClusterCephxStatus, LocalCephxStatus)
+(Appears on:CephClientStatus, CephxStatusWithKeyCount, ClusterCephxStatus, LocalCephxStatus)
@@ -4619,6 +4669,49 @@ An empty string indicates that the version is unknown, as expected in brownfield
+CephxStatusWithKeyCount
+
+
+(Appears on:ClusterCephxStatus)
+
+
+
+
+
+
+| Field |
+Description |
+
+
+
+
+
+CephxStatus
+
+
+CephxStatus
+
+
+ |
+
+
+(Members of CephxStatus are embedded into this type.)
+
+ |
+
+
+
+priorKeyCount
+
+byte
+
+ |
+
+ PriorKeyCount reports the number of prior-generation CephX keys that remain active for the related component
+ |
+
+
+
CleanupConfirmationProperty
(string alias)
@@ -4850,6 +4943,20 @@ CephxConfig
Ceph cluster. Daemon CephX keys can be rotated without affecting client connections.
+
+
+csi
+
+
+CephXConfigWithPriorCount
+
+
+ |
+
+ CSI configures CephX key rotation settings for the Ceph-CSI daemons in the current Kubernetes cluster.
+CSI key rotation can affect existing PV connections, so take care when exercising this option.
+ |
+
ClusterCephxStatus
@@ -4894,6 +5001,19 @@ CephxStatus
RBDMirrorPeer represents the cephx key rotation status of the rbd-mirror-peer user
+
+
+csi
+
+
+CephxStatusWithKeyCount
+
+
+ |
+
+ CSI shows the CephX key status for Ceph-CSI components.
+ |
+
ClusterSecuritySpec
diff --git a/deploy/charts/rook-ceph/templates/resources.yaml b/deploy/charts/rook-ceph/templates/resources.yaml
index 823d45b80..29e37e9fd 100644
--- a/deploy/charts/rook-ceph/templates/resources.yaml
+++ b/deploy/charts/rook-ceph/templates/resources.yaml
@@ -3692,6 +3692,48 @@ spec:
cephx:
description: 'CephX configures CephX key settings. More: https://docs.ceph.com/en/latest/dev/cephx/'
properties:
+ csi:
+ description: |-
+ CSI configures CephX key rotation settings for the Ceph-CSI daemons in the current Kubernetes cluster.
+ CSI key rotation can affect existing PV connections, so take care when exercising this option.
+ properties:
+ keepPriorKeyCountMax:
+ description: |-
+ KeepPriorKeyCountMax tells Rook how many prior keys to keep active.
+ Generally, this would be set to 1 to allow for a migration period for applications.
+ If desired, set this to 0 to delete prior keys after migration.
+ This config only applies to prior keys that already exist.
+ If PriorKeyCount is set to 2 while only a single key currently exists, only a single prior key will be kept,
+ and the reported status will only indicate the actual number of prior keys,
+ not necessarily a reflection of PriorKeyCount config here.
+ maximum: 10
+ minimum: 0
+ type: integer
+ keyGeneration:
+ description: |-
+ KeyGeneration specifies the desired CephX key generation. This is used when KeyRotationPolicy
+ is KeyGeneration and ignored for other policies. If this is set to greater than the current
+ key generation, relevant keys will be rotated, and the generation value will be updated to
+ this new value (generation values are not necessarily incremental, though that is the
+ intended use case). If this is set to less than or equal to the current key generation, keys
+ are not rotated.
+ format: int32
+ maximum: 4294967295
+ minimum: 0
+ type: integer
+ x-kubernetes-validations:
+ - message: keyGeneration cannot be decreased
+ rule: self >= oldSelf
+ keyRotationPolicy:
+ description: |-
+ KeyRotationPolicy controls if and when CephX keys are rotated after initial creation.
+ One of Disabled, or KeyGeneration. Default Disabled.
+ enum:
+ - ""
+ - Disabled
+ - KeyGeneration
+ type: string
+ type: object
daemon:
description: |-
Daemon configures CephX key settings for local Ceph daemons managed by Rook and part of the
@@ -5871,6 +5913,31 @@ spec:
cephx:
description: ClusterCephxStatus defines the cephx key rotation status of various daemons on the cephCluster resource
properties:
+ csi:
+ description: CSI shows the CephX key status for Ceph-CSI components.
+ properties:
+ keyCephVersion:
+ description: |-
+ KeyCephVersion reports the Ceph version that created the current generation's keys. This is
+ same string format as reported by `CephCluster.status.version.version` to allow them to be
+ compared. E.g., `20.2.0-0`.
+ For all newly-created resources, this field set to the version of Ceph that created the key.
+ The special value "Uninitialized" indicates that keys are being created for the first time.
+ An empty string indicates that the version is unknown, as expected in brownfield deployments.
+ type: string
+ keyGeneration:
+ description: |-
+ KeyGeneration represents the CephX key generation for the last successful reconcile.
+ For all newly-created resources, this field is set to `1`.
+ When keys are rotated due to any rotation policy, the generation is incremented or updated to
+ the configured policy generation.
+ Generation `0` indicates that keys existed prior to the implementation of key tracking.
+ format: int32
+ type: integer
+ priorKeyCount:
+ description: PriorKeyCount reports the number of prior-generation CephX keys that remain active for the related component
+ type: integer
+ type: object
mgr:
description: Mgr represents the cephx key rotation status of the ceph manager daemon
properties:
diff --git a/deploy/examples/crds.yaml b/deploy/examples/crds.yaml
index 53825cd43..871d5661f 100644
--- a/deploy/examples/crds.yaml
+++ b/deploy/examples/crds.yaml
@@ -3690,6 +3690,48 @@ spec:
cephx:
description: 'CephX configures CephX key settings. More: https://docs.ceph.com/en/latest/dev/cephx/'
properties:
+ csi:
+ description: |-
+ CSI configures CephX key rotation settings for the Ceph-CSI daemons in the current Kubernetes cluster.
+ CSI key rotation can affect existing PV connections, so take care when exercising this option.
+ properties:
+ keepPriorKeyCountMax:
+ description: |-
+ KeepPriorKeyCountMax tells Rook how many prior keys to keep active.
+ Generally, this would be set to 1 to allow for a migration period for applications.
+ If desired, set this to 0 to delete prior keys after migration.
+ This config only applies to prior keys that already exist.
+ If PriorKeyCount is set to 2 while only a single key currently exists, only a single prior key will be kept,
+ and the reported status will only indicate the actual number of prior keys,
+ not necessarily a reflection of PriorKeyCount config here.
+ maximum: 10
+ minimum: 0
+ type: integer
+ keyGeneration:
+ description: |-
+ KeyGeneration specifies the desired CephX key generation. This is used when KeyRotationPolicy
+ is KeyGeneration and ignored for other policies. If this is set to greater than the current
+ key generation, relevant keys will be rotated, and the generation value will be updated to
+ this new value (generation values are not necessarily incremental, though that is the
+ intended use case). If this is set to less than or equal to the current key generation, keys
+ are not rotated.
+ format: int32
+ maximum: 4294967295
+ minimum: 0
+ type: integer
+ x-kubernetes-validations:
+ - message: keyGeneration cannot be decreased
+ rule: self >= oldSelf
+ keyRotationPolicy:
+ description: |-
+ KeyRotationPolicy controls if and when CephX keys are rotated after initial creation.
+ One of Disabled, or KeyGeneration. Default Disabled.
+ enum:
+ - ""
+ - Disabled
+ - KeyGeneration
+ type: string
+ type: object
daemon:
description: |-
Daemon configures CephX key settings for local Ceph daemons managed by Rook and part of the
@@ -5869,6 +5911,31 @@ spec:
cephx:
description: ClusterCephxStatus defines the cephx key rotation status of various daemons on the cephCluster resource
properties:
+ csi:
+ description: CSI shows the CephX key status for Ceph-CSI components.
+ properties:
+ keyCephVersion:
+ description: |-
+ KeyCephVersion reports the Ceph version that created the current generation's keys. This is
+ same string format as reported by `CephCluster.status.version.version` to allow them to be
+ compared. E.g., `20.2.0-0`.
+ For all newly-created resources, this field set to the version of Ceph that created the key.
+ The special value "Uninitialized" indicates that keys are being created for the first time.
+ An empty string indicates that the version is unknown, as expected in brownfield deployments.
+ type: string
+ keyGeneration:
+ description: |-
+ KeyGeneration represents the CephX key generation for the last successful reconcile.
+ For all newly-created resources, this field is set to `1`.
+ When keys are rotated due to any rotation policy, the generation is incremented or updated to
+ the configured policy generation.
+ Generation `0` indicates that keys existed prior to the implementation of key tracking.
+ format: int32
+ type: integer
+ priorKeyCount:
+ description: PriorKeyCount reports the number of prior-generation CephX keys that remain active for the related component
+ type: integer
+ type: object
mgr:
description: Mgr represents the cephx key rotation status of the ceph manager daemon
properties:
diff --git a/pkg/apis/ceph.rook.io/v1/types.go b/pkg/apis/ceph.rook.io/v1/types.go
index c93f74b89..06d84600b 100755
--- a/pkg/apis/ceph.rook.io/v1/types.go
+++ b/pkg/apis/ceph.rook.io/v1/types.go
@@ -329,6 +329,26 @@ type ClusterCephxConfig struct {
// Daemon configures CephX key settings for local Ceph daemons managed by Rook and part of the
// Ceph cluster. Daemon CephX keys can be rotated without affecting client connections.
Daemon CephxConfig `json:"daemon,omitempty"`
+
+ // CSI configures CephX key rotation settings for the Ceph-CSI daemons in the current Kubernetes cluster.
+ // CSI key rotation can affect existing PV connections, so take care when exercising this option.
+ CSI CephXConfigWithPriorCount `json:"csi,omitempty"`
+}
+
+type CephXConfigWithPriorCount struct {
+ CephxConfig `json:",inline"` // inline core CephxConfig
+
+ // KeepPriorKeyCountMax tells Rook how many prior keys to keep active.
+ // Generally, this would be set to 1 to allow for a migration period for applications.
+ // If desired, set this to 0 to delete prior keys after migration.
+ // This config only applies to prior keys that already exist.
+ // If PriorKeyCount is set to 2 while only a single key currently exists, only a single prior key will be kept,
+ // and the reported status will only indicate the actual number of prior keys,
+ // not necessarily a reflection of PriorKeyCount config here.
+ // +optional
+ // +kubebuilder:validation:Minimum=0
+ // +kubebuilder:validation:Maximum=10
+ KeepPriorKeyCountMax uint8 `json:"keepPriorKeyCountMax,omitempty"`
}
type CephxConfig struct {
@@ -703,6 +723,13 @@ type CephxStatus struct {
KeyCephVersion string `json:"keyCephVersion,omitempty"`
}
+type CephxStatusWithKeyCount struct {
+ CephxStatus `json:",inline"` // inline core CephxStatus
+
+ // PriorKeyCount reports the number of prior-generation CephX keys that remain active for the related component
+ PriorKeyCount uint8 `json:"priorKeyCount,omitempty"`
+}
+
// UninitializedCephxKeyCephVersion is a special value for CephxStatus.KeyCephVersion that is
// applied when a resource status is first initialized. Rook replaces this value with the current
// Ceph version after keys are first created and the resource is reconciled successfully.
@@ -719,6 +746,9 @@ type ClusterCephxStatus struct {
Mgr *CephxStatus `json:"mgr,omitempty"`
// RBDMirrorPeer represents the cephx key rotation status of the `rbd-mirror-peer` user
RBDMirrorPeer *CephxStatus `json:"rbdMirrorPeer,omitempty"`
+
+ // CSI shows the CephX key status for Ceph-CSI components.
+ CSI *CephxStatusWithKeyCount `json:"csi,omitempty"`
}
// MonSpec represents the specification of the monitor
diff --git a/pkg/apis/ceph.rook.io/v1/zz_generated.deepcopy.go b/pkg/apis/ceph.rook.io/v1/zz_generated.deepcopy.go
index d615880d9..559465b2d 100644
--- a/pkg/apis/ceph.rook.io/v1/zz_generated.deepcopy.go
+++ b/pkg/apis/ceph.rook.io/v1/zz_generated.deepcopy.go
@@ -1929,6 +1929,23 @@ func (in *CephVersionSpec) DeepCopy() *CephVersionSpec {
return out
}
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CephXConfigWithPriorCount) DeepCopyInto(out *CephXConfigWithPriorCount) {
+ *out = *in
+ out.CephxConfig = in.CephxConfig
+ return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CephXConfigWithPriorCount.
+func (in *CephXConfigWithPriorCount) DeepCopy() *CephXConfigWithPriorCount {
+ if in == nil {
+ return nil
+ }
+ out := new(CephXConfigWithPriorCount)
+ in.DeepCopyInto(out)
+ return out
+}
+
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *CephxConfig) DeepCopyInto(out *CephxConfig) {
*out = *in
@@ -1961,6 +1978,23 @@ func (in *CephxStatus) DeepCopy() *CephxStatus {
return out
}
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CephxStatusWithKeyCount) DeepCopyInto(out *CephxStatusWithKeyCount) {
+ *out = *in
+ out.CephxStatus = in.CephxStatus
+ return
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CephxStatusWithKeyCount.
+func (in *CephxStatusWithKeyCount) DeepCopy() *CephxStatusWithKeyCount {
+ if in == nil {
+ return nil
+ }
+ out := new(CephxStatusWithKeyCount)
+ in.DeepCopyInto(out)
+ return out
+}
+
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *CleanupPolicySpec) DeepCopyInto(out *CleanupPolicySpec) {
*out = *in
@@ -2023,6 +2057,7 @@ func (in *ClientSpec) DeepCopy() *ClientSpec {
func (in *ClusterCephxConfig) DeepCopyInto(out *ClusterCephxConfig) {
*out = *in
out.Daemon = in.Daemon
+ out.CSI = in.CSI
return
}
@@ -2049,6 +2084,11 @@ func (in *ClusterCephxStatus) DeepCopyInto(out *ClusterCephxStatus) {
*out = new(CephxStatus)
**out = **in
}
+ if in.CSI != nil {
+ in, out := &in.CSI, &out.CSI
+ *out = new(CephxStatusWithKeyCount)
+ **out = **in
+ }
return
}
diff --git a/pkg/daemon/ceph/client/auth.go b/pkg/daemon/ceph/client/auth.go
index 2e9c6a184..ef7b3b908 100644
--- a/pkg/daemon/ceph/client/auth.go
+++ b/pkg/daemon/ceph/client/auth.go
@@ -24,6 +24,16 @@ import (
"github.com/rook/rook/pkg/util/exec"
)
+// AuthListOutput contains list of ceph user details contains entries, keys.
+type AuthListOutput struct {
+ AuthDump []AuthListEntry `json:"auth_dump"`
+}
+
+// AuthListEntry contains only entity field for each user.
+type AuthListEntry struct {
+ Entity string `json:"entity"`
+}
+
// AuthGetOrCreate will either get or create a user with the given capabilities. The keyring for the
// user will be written to the given keyring path.
func AuthGetOrCreate(context *clusterd.Context, clusterInfo *ClusterInfo, name, keyringPath string, caps []string) error {
@@ -155,3 +165,22 @@ func parseAuthKey(buf []byte) (string, error) {
}
return resp["key"].(string), nil
}
+
+// AuthList will list all the ceph user.
+func AuthList(context *clusterd.Context, clusterInfo *ClusterInfo) (AuthListOutput, error) {
+ authArgs := []string{"auth", "ls"}
+ output, err := NewCephCommand(context, clusterInfo, authArgs).Run()
+ if err != nil {
+ return AuthListOutput{}, errors.Wrap(err, "failed to list ceph auth ls")
+ }
+
+ var auth AuthListOutput
+ err = json.Unmarshal(output, &auth)
+ if err != nil {
+ // insecure trace logging will show the raw response if debugging required
+ logger.Tracef("failed to unmarshal auth ls response: %s", string(output))
+ return auth, errors.Wrap(err, "failed to unmarshal auth ls response")
+ }
+
+ return auth, err
+}
diff --git a/pkg/operator/ceph/cluster/cluster.go b/pkg/operator/ceph/cluster/cluster.go
index df5cd2153..760dd12a1 100755
--- a/pkg/operator/ceph/cluster/cluster.go
+++ b/pkg/operator/ceph/cluster/cluster.go
@@ -72,7 +72,7 @@ type cluster struct {
observedGeneration int64
}
-func newCluster(ctx context.Context, c *cephv1.CephCluster, context *clusterd.Context, ownerInfo *k8sutil.OwnerInfo) *cluster {
+func newCluster(ctx context.Context, c *cephv1.CephCluster, context *clusterd.Context, ownerInfo *k8sutil.OwnerInfo, rookImage string) *cluster {
return &cluster{
// at this phase of the cluster creation process, the identity components of the cluster are
// not yet established. we reserve this struct which is filled in as soon as the cluster's
@@ -461,7 +461,7 @@ func (c *cluster) preMonStartupActions(cephVersion cephver.CephVersion) error {
// Basically, it is executed between the monitors and the manager sequence
func (c *cluster) postMonStartupActions() error {
// Create CSI Kubernetes Secrets
- if err := csi.CreateCSISecrets(c.context, c.ClusterInfo); err != nil {
+ if err := csi.CreateCSISecrets(c.context, c.ClusterInfo, c.namespacedName); err != nil {
return errors.Wrap(err, "failed to create csi kubernetes secrets")
}
@@ -800,6 +800,9 @@ func initClusterCephxStatus(c *clusterd.Context, cluster *cephv1.CephCluster) er
cluster.Status.Cephx = &cephv1.ClusterCephxStatus{
RBDMirrorPeer: &uninitializedStatus,
Mgr: &uninitializedStatus,
+ CSI: &cephv1.CephxStatusWithKeyCount{
+ CephxStatus: uninitializedStatus,
+ },
}
if err := reporting.UpdateStatus(c.Client, cluster); err != nil {
diff --git a/pkg/operator/ceph/cluster/cluster_external.go b/pkg/operator/ceph/cluster/cluster_external.go
index 9045c9906..1347bb4cd 100644
--- a/pkg/operator/ceph/cluster/cluster_external.go
+++ b/pkg/operator/ceph/cluster/cluster_external.go
@@ -102,7 +102,7 @@ func (c *ClusterController) configureExternalCephCluster(cluster *cluster) error
// Create CSI Secrets only if the user has provided the admin key
if cluster.ClusterInfo.CephCred.Username == client.AdminUsername {
- err = csi.CreateCSISecrets(c.context, cluster.ClusterInfo)
+ err = csi.CreateCSISecrets(c.context, cluster.ClusterInfo, c.namespacedName)
if err != nil {
return errors.Wrap(err, "failed to create csi kubernetes secrets")
}
diff --git a/pkg/operator/ceph/cluster/controller.go b/pkg/operator/ceph/cluster/controller.go
index 0d3151a7a..bfae219d2 100644
--- a/pkg/operator/ceph/cluster/controller.go
+++ b/pkg/operator/ceph/cluster/controller.go
@@ -394,7 +394,7 @@ func (c *ClusterController) reconcileCephCluster(clusterObj *cephv1.CephCluster,
cluster, ok := c.clusterMap[clusterObj.Namespace]
if !ok {
// It's a new cluster so let's populate the struct
- cluster = newCluster(c.OpManagerCtx, clusterObj, c.context, ownerInfo)
+ cluster = newCluster(c.OpManagerCtx, clusterObj, c.context, ownerInfo, c.rookImage)
}
cluster.namespacedName = c.namespacedName
// updating observedGeneration in cluster if it's not the first reconcile
diff --git a/pkg/operator/ceph/csi/secrets.go b/pkg/operator/ceph/csi/secrets.go
index 0de1e2782..6bec80fc1 100644
--- a/pkg/operator/ceph/csi/secrets.go
+++ b/pkg/operator/ceph/csi/secrets.go
@@ -18,14 +18,23 @@ package csi
import (
"fmt"
+ "sort"
+ "strconv"
+ "strings"
"github.com/pkg/errors"
+ cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
"github.com/rook/rook/pkg/clusterd"
"github.com/rook/rook/pkg/daemon/ceph/client"
"github.com/rook/rook/pkg/operator/ceph/config/keyring"
+ "github.com/rook/rook/pkg/operator/ceph/reporting"
"github.com/rook/rook/pkg/operator/k8sutil"
+
v1 "k8s.io/api/core/v1"
+ kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "k8s.io/apimachinery/pkg/types"
+ "k8s.io/client-go/util/retry"
)
//nolint:gosec // because of the word `Secret`
@@ -44,40 +53,75 @@ const (
CsiCephFSProvisionerSecret = "rook-csi-cephfs-provisioner"
)
-func createCSIKeyringRBDNode(s *keyring.SecretStore) (string, error) {
- key, err := s.GenerateKey(csiKeyringRBDNodeUsername, cephCSIKeyringRBDNodeCaps())
- if err != nil {
- return "", err
- }
-
- return key, nil
+type csiCephUserStore struct {
+ Name string
+ Key string
}
-func createCSIKeyringRBDProvisioner(s *keyring.SecretStore) (string, error) {
- key, err := s.GenerateKey(csiKeyringRBDProvisionerUsername, cephCSIKeyringRBDProvisionerCaps())
+type csiSecretStore map[string]csiCephUserStore
+
+// createCSIKeyring returns four values: the cephClientID with the keyCount as a suffix,
+// the cephClient key value, a boolean indicating whether the key should be rotated, and an error.
+// It calls the method `getCsiKeyRotationInfo` to find any Ceph clients matching the CSI keyBase
+// and the maximum keyGen. If no matching Ceph clients are found, it returns keyGen as 0 and an
+// empty list. If keys are found, a new key is generated with an incremented keyGen as a suffix,
+// and the list of matching Ceph clients will be deleted later in the method.
+// It fetches the current `interpretedCephxStatus` and keyGen from the CephCluster,
+// and then calls the method `ShouldRotateCephxKeys` to determine if the old key should be rotated.
+// Based on this, it updates the cephxStatus, generates a new client name, and creates a new key.
+func createCSIKeyring(
+ context *clusterd.Context, clusterInfo *client.ClusterInfo, cephCluster *cephv1.CephCluster,
+ s *keyring.SecretStore, csiKeyrigName string, keyCaps []string,
+) (string, string, int, bool, error) {
+ logger.Debugf("starting CSI key generation for cluster in namespace %q", clusterInfo.Namespace)
+
+ currentMaxKeyGen, allKeyWithBaseName, err := getCsiKeyRotationInfo(context, clusterInfo, csiKeyrigName)
if err != nil {
- return "", err
+ return "", "", 0, false, errors.Wrapf(err, "failed to determine key rotation info for CSI key %s", csiKeyrigName)
}
- return key, nil
-}
+ // corner cases could have the status KeyGeneration out of sync with what was determined above
+ // apply the current max key gen to the current status to find the definitive current status
+ interpretedCephxStatus := cephCluster.Status.Cephx.CSI.DeepCopy()
+ interpretedCephxStatus.KeyGeneration = uint32(currentMaxKeyGen) //nolint:gosec // disable G115
-func createCSIKeyringCephFSNode(s *keyring.SecretStore) (string, error) {
- key, err := s.GenerateKey(csiKeyringCephFSNodeUsername, cephCSIKeyringCephFSNodeCaps())
+ // determine shouldRotate based on 'definitive' status
+ shouldRotate, err := keyring.ShouldRotateCephxKeys(
+ cephCluster.Spec.Security.CephX.CSI.CephxConfig,
+ clusterInfo.CephVersion, clusterInfo.CephVersion,
+ interpretedCephxStatus.CephxStatus,
+ )
if err != nil {
- return "", err
+ return "", "", 0, shouldRotate, errors.Wrap(err, "failed to call `shouldRotateCephxKeys` during CSI key rotation")
}
- return key, nil
-}
+ // generate the future cephx status to determine what the new key gen should be
+ desiredCephxStatus := keyring.UpdatedCephxStatus(shouldRotate,
+ cephCluster.Spec.Security.CephX.CSI.CephxConfig,
+ clusterInfo.CephVersion,
+ interpretedCephxStatus.CephxStatus)
-func createCSIKeyringCephFSProvisioner(s *keyring.SecretStore) (string, error) {
- key, err := s.GenerateKey(csiKeyringCephFSProvisionerUsername, cephCSIKeyringCephFSProvisionerCaps())
+ // determine the client ID that should exist as the latest entry
+ latestClientId := generateCsiUserIdWithGenerationSuffix(csiKeyrigName, desiredCephxStatus.KeyGeneration)
+
+ // ensure the client key exists
+ key, err := s.GenerateKey(latestClientId, keyCaps)
if err != nil {
- return "", err
+ return "", "", 0, shouldRotate, errors.Wrapf(err, "failed to check if keys should to be rotated for CSI key %s", csiKeyrigName)
}
- return key, nil
+ keysDeleted, err := deleteOldKeyGen(context, clusterInfo, allKeyWithBaseName, cephCluster.Spec.Security.CephX.CSI.KeepPriorKeyCountMax)
+ if err != nil {
+ logger.Errorf("failed to delete keys during CSI key rotation. %v. Continuing with key rotation", err)
+ }
+
+ // add the new key to the list of all keys
+ allKeyWithBaseName = append(allKeyWithBaseName, latestClientId)
+ allKeyWithBaseName = deduplicate(allKeyWithBaseName)
+
+ currentKeyCount := len(allKeyWithBaseName) - len(keysDeleted)
+
+ return latestClientId, key, currentKeyCount, shouldRotate, nil
}
func cephCSIKeyringRBDNodeCaps() []string {
@@ -115,29 +159,29 @@ func cephCSIKeyringCephFSProvisionerCaps() []string {
}
}
-func createOrUpdateCSISecret(clusterInfo *client.ClusterInfo, csiRBDProvisionerSecretKey, csiRBDNodeSecretKey, csiCephFSProvisionerSecretKey, csiCephFSNodeSecretKey string, k *keyring.SecretStore) error {
+func createOrUpdateCSISecret(clusterInfo *client.ClusterInfo, csiSecretContent csiSecretStore, k *keyring.SecretStore) error {
csiRBDProvisionerSecrets := map[string][]byte{
// userID is expected for the rbd provisioner driver
- "userID": []byte("csi-rbd-provisioner"),
- "userKey": []byte(csiRBDProvisionerSecretKey),
+ "userID": []byte(csiSecretContent[CsiRBDProvisionerSecret].Name),
+ "userKey": []byte(csiSecretContent[CsiRBDProvisionerSecret].Key),
}
csiRBDNodeSecrets := map[string][]byte{
// userID is expected for the rbd node driver
- "userID": []byte("csi-rbd-node"),
- "userKey": []byte(csiRBDNodeSecretKey),
+ "userID": []byte(csiSecretContent[CsiRBDNodeSecret].Name),
+ "userKey": []byte(csiSecretContent[CsiRBDNodeSecret].Key),
}
csiCephFSProvisionerSecrets := map[string][]byte{
// adminID is expected for the cephfs provisioner driver
- "adminID": []byte("csi-cephfs-provisioner"),
- "adminKey": []byte(csiCephFSProvisionerSecretKey),
+ "adminID": []byte(csiSecretContent[CsiCephFSProvisionerSecret].Name),
+ "adminKey": []byte(csiSecretContent[CsiCephFSProvisionerSecret].Key),
}
csiCephFSNodeSecrets := map[string][]byte{
// adminID is expected for the cephfs node driver
- "adminID": []byte("csi-cephfs-node"),
- "adminKey": []byte(csiCephFSNodeSecretKey),
+ "adminID": []byte(csiSecretContent[CsiCephFSNodeSecret].Name),
+ "adminKey": []byte(csiSecretContent[CsiCephFSNodeSecret].Key),
}
keyringSecretMap := make(map[string]map[string][]byte)
@@ -172,8 +216,17 @@ func createOrUpdateCSISecret(clusterInfo *client.ClusterInfo, csiRBDProvisionerS
return nil
}
+// generateCsiUserIdWithGenerationSuffix generate ceph client ID with suffix `.`
+// Example; client.csi-rbd-node.1
+func generateCsiUserIdWithGenerationSuffix(clientBaseName string, keyGeneration uint32) string {
+ if keyGeneration > 0 {
+ return fmt.Sprintf("%s.%d", clientBaseName, keyGeneration)
+ }
+ return clientBaseName
+}
+
// CreateCSISecrets creates all the Kubernetes CSI Secrets
-func CreateCSISecrets(context *clusterd.Context, clusterInfo *client.ClusterInfo) error {
+func CreateCSISecrets(context *clusterd.Context, clusterInfo *client.ClusterInfo, clusterNamespaced types.NamespacedName) error {
if clusterInfo.CSIDriverSpec.SkipUserCreation {
if err := deleteOwnedCSISecretsByCephCluster(context, clusterInfo); err != nil {
return err
@@ -183,38 +236,216 @@ func CreateCSISecrets(context *clusterd.Context, clusterInfo *client.ClusterInfo
}
k := keyring.GetSecretStore(context, clusterInfo, clusterInfo.OwnerInfo)
+ logger.Info("getting CephCluster %s during CSI key creation in namespace %s", clusterNamespaced.Name, clusterNamespaced.Namespace)
+ cephCluster := &cephv1.CephCluster{}
+
+ if err := context.Client.Get(clusterInfo.Context, clusterNamespaced, cephCluster); err != nil {
+ if kerrors.IsNotFound(err) {
+ logger.Debug("CephCluster resource not found. Ignoring since object must be deleted.")
+ return nil
+ }
+ return errors.Wrapf(err, "failed to retrieve cephCluster %q to generate CSICephx keys", clusterNamespaced.Namespace)
+ }
+
// Create CSI RBD Provisioner Ceph key
- csiRBDProvisionerSecretKey, err := createCSIKeyringRBDProvisioner(k)
+ rbdProvName, rbdProvKey, rbdProvKeyCount, didRotateRbdProvisioner, err := createCSIKeyring(context, clusterInfo, cephCluster, k, csiKeyringRBDProvisionerUsername, cephCSIKeyringRBDProvisionerCaps())
if err != nil {
return errors.Wrap(err, "failed to create csi rbd provisioner ceph keyring")
}
// Create CSI RBD Node Ceph key
- csiRBDNodeSecretKey, err := createCSIKeyringRBDNode(k)
+ rbdNodeName, rbdNodeKey, rbdNodeKeyCount, didRotateRbdNode, err := createCSIKeyring(context, clusterInfo, cephCluster, k, csiKeyringRBDNodeUsername, cephCSIKeyringRBDNodeCaps())
if err != nil {
return errors.Wrap(err, "failed to create csi rbd node ceph keyring")
}
// Create CSI Cephfs provisioner Ceph key
- csiCephFSProvisionerSecretKey, err := createCSIKeyringCephFSProvisioner(k)
+ cFSProvName, cFSProvKey, cFSProvKeyCount, didRotateCephFsProvisioner, err := createCSIKeyring(context, clusterInfo, cephCluster, k, csiKeyringCephFSProvisionerUsername, cephCSIKeyringCephFSProvisionerCaps())
if err != nil {
return errors.Wrap(err, "failed to create csi cephfs provisioner ceph keyring")
}
// Create CSI Cephfs node Ceph key
- csiCephFSNodeSecretKey, err := createCSIKeyringCephFSNode(k)
+ cFSNodeName, cFSNodeKey, cFSNodeKeyCount, didRotateCephFsNode, err := createCSIKeyring(context, clusterInfo, cephCluster, k, csiKeyringCephFSNodeUsername, cephCSIKeyringCephFSNodeCaps())
if err != nil {
return errors.Wrap(err, "failed to create csi cephfs node ceph keyring")
}
+ // The latestClientIdMap contains latestClientID without prefix `client.` in the format CSI requires in the secret created below.
+ // Ex for "client.csi-rbd-provisioner" values will `csi-rbd-provisioner.` that is latestClientID.
+ csiSecretContent := csiSecretStore{
+ CsiRBDProvisionerSecret: {Name: strings.TrimPrefix(rbdProvName, "client."), Key: rbdProvKey},
+ CsiRBDNodeSecret: {Name: strings.TrimPrefix(rbdNodeName, "client."), Key: rbdNodeKey},
+ CsiCephFSProvisionerSecret: {Name: strings.TrimPrefix(cFSProvName, "client."), Key: cFSProvKey},
+ CsiCephFSNodeSecret: {Name: strings.TrimPrefix(cFSNodeName, "client."), Key: cFSNodeKey},
+ }
+
// Create or update Kubernetes CSI secret
- if err := createOrUpdateCSISecret(clusterInfo, csiRBDProvisionerSecretKey, csiRBDNodeSecretKey, csiCephFSProvisionerSecretKey, csiCephFSNodeSecretKey, k); err != nil {
+ if err := createOrUpdateCSISecret(clusterInfo, csiSecretContent, k); err != nil {
return errors.Wrap(err, "failed to create kubernetes csi secret")
}
+ currentKeyCount := max(rbdProvKeyCount, rbdNodeKeyCount, cFSProvKeyCount, cFSNodeKeyCount)
+ didRotateAny := didRotateRbdProvisioner || didRotateRbdNode || didRotateCephFsProvisioner || didRotateCephFsNode
+ err = updateCephStatusWithCephxStatus(context, clusterInfo, cephCluster, clusterNamespaced, didRotateAny, currentKeyCount)
+ if err != nil {
+ return err
+ }
+
return nil
}
+// updateCephStatusWithCephxStatus updates the cephCluster status with CSI cephxStatus
+func updateCephStatusWithCephxStatus(context *clusterd.Context, clusterInfo *client.ClusterInfo, cephCluster *cephv1.CephCluster,
+ namespacedName types.NamespacedName, didRotate bool, currentKeyCount int,
+) error {
+ logger.Infof("updating cephCluster %s cephStatus with CSI cephxStatus in namespace %s", namespacedName.Name, namespacedName.Namespace)
+ cephxStatus := keyring.UpdatedCephxStatus(didRotate, cephCluster.Spec.Security.CephX.Daemon, clusterInfo.CephVersion, cephCluster.Status.Cephx.CSI.CephxStatus)
+
+ err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
+ cephCluster := &cephv1.CephCluster{}
+ if err := context.Client.Get(clusterInfo.Context, namespacedName, cephCluster); err != nil {
+ if kerrors.IsNotFound(err) {
+ logger.Debug("CephCluster resource not found. Ignoring since object must be deleted.")
+ return nil
+ }
+ return errors.Wrapf(err, "failed to retrieve cephCluster %q to update CSICephxStatus", namespacedName.Namespace)
+ }
+ cephCluster.Status.Cephx.CSI.CephxStatus = cephxStatus
+ cephCluster.Status.Cephx.CSI.PriorKeyCount = uint8(currentKeyCount) //nolint:gosec // disable G115
+
+ if err := reporting.UpdateStatus(context.Client, cephCluster); err != nil {
+ return errors.Wrapf(err, "failed to update cephCluster %q to update csi cephx status to %q in namespace %q", namespacedName.Name, cephxStatus, namespacedName.Namespace)
+ }
+ return nil
+ })
+ if err != nil {
+ return errors.Wrapf(err, "failed to get and update Ceph cluster %q status in namespace %q when updating csi cephx status", namespacedName.Name, namespacedName.Namespace)
+ }
+
+ logger.Debugf("successfully updated Ceph cluster %q status with CSI Cephx status in namespace %q", namespacedName.Name, namespacedName.Namespace)
+ return nil
+}
+
+// getCsiKeyRotationInfo runs the `ceph auth ls` command to fetch all the keys and filter out the keys with same base name. Example
+// for base name `client.csi-rbd-node`.
+// From the list of key name return from `getMatchingClient` we'll read the suffix index eg; for key `client.csi-rbd-node.3` we'll take `3` and compare with
+// KeyGeneration and basaed on the comparison we'll return bool to check if we should rotate the keys or not and returning list
+// of all the matching keys.
+func getCsiKeyRotationInfo(context *clusterd.Context, clusterInfo *client.ClusterInfo, keyBaseName string) (int, []string, error) {
+ authList, err := client.AuthList(context, clusterInfo)
+ if err != nil {
+ return 0, []string{}, err
+ }
+
+ keyWithBaseName, err := getMatchingClient(authList, keyBaseName)
+ if err != nil {
+ return 0, keyWithBaseName, err
+ }
+
+ // In fresh deployment `keyWithBaseName` length will be empty, so let's not return error.
+ if len(keyWithBaseName) == 0 {
+ logger.Debugf("no key matching with %s found in auth list must be fresh cluster", keyBaseName)
+ return 0, keyWithBaseName, nil
+ }
+
+ sortedClientList := sortCSIClientName(keyWithBaseName)
+
+ if len(sortedClientList) == 0 {
+ return 0, keyWithBaseName, fmt.Errorf("empty list found while fetching CSI key from")
+ }
+
+ _, currentMaxKeyGen, err := parseCsiClient(sortedClientList[len(sortedClientList)-1])
+ if err != nil {
+ return 0, keyWithBaseName, errors.Wrap(err, "failed to get currentMaxKeyCount from key entity")
+ }
+
+ return currentMaxKeyGen, keyWithBaseName, nil
+}
+
+// getMatchingClient return list of all the ceph key which contains `client.csi-rbd-node`, we will have keys like
+// `client.csi-rbd-node.1`, `client.csi-rbd-node.2`, `client.csi-rbd-node.3` so the list will have all these key name.
+// Return list of keys are expected to contain `client.`.
+func getMatchingClient(authList client.AuthListOutput, clientBaseName string) ([]string, error) {
+ keyWithBaseName := []string{}
+
+ for _, entry := range authList.AuthDump {
+ basename, _, err := parseCsiClient(entry.Entity)
+ if err != nil {
+ // We want to continue processing other keys even if one fails to parse.
+ logger.Debugf("no CSI client name found matching with %s. %v", clientBaseName, err)
+ }
+
+ if basename == clientBaseName {
+ keyWithBaseName = append(keyWithBaseName, entry.Entity)
+ }
+ }
+
+ return keyWithBaseName, nil
+}
+
+// parseCsiClient parses a CSI client name of the format "client.[.]"
+// Example valid formats: "client.csi-rbd-node", "client.csi-rbd-node.3"
+// Returns: basename ("client.csi-rbd-node"), generation (int, default 0 if absent), error if format is invalid.
+func parseCsiClient(c string) (string, int, error) {
+ cSplit := strings.Split(c, ".")
+ if len(cSplit) < 2 || len(cSplit) > 3 {
+ return "", 0, fmt.Errorf("unexpected CSI client name format: %q", c)
+ }
+ if cSplit[0] != "client" {
+ return "", 0, fmt.Errorf(`CSI client name %q does not begin with "client"`, c)
+ } else if strings.HasSuffix(cSplit[1], " ") {
+ return "", 0, errors.Errorf("no CSI client name found matching with %s contains space", c)
+ }
+
+ gen := 0
+ if len(cSplit) == 3 {
+ var err error
+ gen, err = strconv.Atoi(cSplit[2])
+ if err != nil {
+ return "", 0, errors.Wrapf(err, "failed to parse generation for CSI client name %q", c)
+ }
+ if gen < 0 {
+ return "", 0, fmt.Errorf("parsed generation for CSI client name %q is negative", c)
+ }
+ }
+
+ // return basename, generation, err
+ return cSplit[0] + "." + cSplit[1], gen, nil
+}
+
+// deleteOldKeyGen deletes CephX keys based on the highest key generation count (KeyGen).
+// It keeps the latest `count` keys by sorting the client keys by their numeric suffix.
+// Example: For `client.csi-rbd-node.3`, the generation is 3.
+// If `count` is 2 and there are 3 keys, one old key will be deleted.
+func deleteOldKeyGen(context *clusterd.Context, clusterInfo *client.ClusterInfo, allKeyWithBaseName []string, count uint8) ([]string, error) {
+ sortedClientList := sortCSIClientName(allKeyWithBaseName)
+
+ if len(sortedClientList) < 2 {
+ logger.Debug("not enough matching CSI keys to delete during rotation. Could be fresh deployment.")
+ return []string{}, nil
+ }
+
+ keyDeleteCount := max(0, len(sortedClientList)-int(count)) // can't delete negative count
+ if len(sortedClientList) == keyDeleteCount && keyDeleteCount > 0 {
+ // Above condition will delete all the keys related to specific CSI driver keys, this will break CSI and Ceph connection.
+ // To avoid above we'll delete `count-1`
+ logger.Warningf("current `keepPriorCountMax` value %d will delete all the related CSI driver key count %d. Deleting `keepPriorCountMax +1` keys", count, keyDeleteCount)
+ keyDeleteCount -= 1
+ }
+
+ listOfKeysDeleted := []string{}
+ for i := range keyDeleteCount {
+ err := client.AuthDelete(context, clusterInfo, sortedClientList[i])
+ if err != nil {
+ // in case of partial success, return successfully deleted list on error
+ return listOfKeysDeleted, errors.Wrapf(err, "failed to delete CSI key %s more than keepPriorCount %d", sortedClientList[i], count)
+ }
+ listOfKeysDeleted = append(listOfKeysDeleted, sortedClientList[i]) // Delete the lowest-numbered keys first
+ }
+ return listOfKeysDeleted, nil
+}
+
func deleteOwnedCSISecretsByCephCluster(context *clusterd.Context, clusterInfo *client.ClusterInfo) error {
ownerRef := metav1.OwnerReference{
APIVersion: "ceph.rook.io/v1",
@@ -237,3 +468,52 @@ func deleteOwnedCSISecretsByCephCluster(context *clusterd.Context, clusterInfo *
return nil
}
+
+func sortCSIClientName(clientList []string) []string {
+ type entry struct {
+ clientId string
+ clientIdSuffix int
+ }
+
+ var newKeyGenNameCounts []entry
+ for _, name := range clientList {
+ _, suffix, err := parseCsiClient(name)
+ if err != nil {
+ // We want to continue processing other keys even if one fails to parse.
+ logger.Debugf("client %s doesn't match with CSI client name. %v", name, err)
+ }
+
+ newKeyGenNameCounts = append(newKeyGenNameCounts, entry{
+ clientId: name,
+ clientIdSuffix: suffix,
+ })
+ }
+
+ if len(newKeyGenNameCounts) == 0 {
+ logger.Debugf("failed to generate list of sorted CSI client name no matching key found")
+ return []string{}
+ }
+
+ sort.Slice(newKeyGenNameCounts, func(i, j int) bool {
+ return newKeyGenNameCounts[i].clientIdSuffix < newKeyGenNameCounts[j].clientIdSuffix
+ })
+
+ sortedClientName := []string{}
+ for _, e := range newKeyGenNameCounts {
+ sortedClientName = append(sortedClientName, e.clientId)
+ }
+
+ return sortedClientName
+}
+
+func deduplicate(list []string) []string {
+ allKeys := make(map[string]bool)
+ uniqueList := []string{}
+ for _, v := range list {
+ if _, value := allKeys[v]; !value {
+ allKeys[v] = true
+ uniqueList = append(uniqueList, v)
+ }
+ }
+ return uniqueList
+}
diff --git a/pkg/operator/ceph/csi/secrets_test.go b/pkg/operator/ceph/csi/secrets_test.go
index 61f3e6cf0..d2893bd22 100644
--- a/pkg/operator/ceph/csi/secrets_test.go
+++ b/pkg/operator/ceph/csi/secrets_test.go
@@ -18,18 +18,32 @@ package csi
import (
"context"
+ "fmt"
+ "reflect"
"testing"
+ "github.com/pkg/errors"
+ cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
"github.com/rook/rook/pkg/clusterd"
"github.com/rook/rook/pkg/daemon/ceph/client"
"github.com/rook/rook/pkg/operator/ceph/config/keyring"
"github.com/rook/rook/pkg/operator/k8sutil"
+ exectest "github.com/rook/rook/pkg/util/exec/test"
"github.com/stretchr/testify/assert"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8sfake "k8s.io/client-go/kubernetes/fake"
)
+const (
+ mockAuthLs = `{"auth_dump":[
+ {"entity":"osd.0"},{"entity":"client.admin"},{"entity":"client.bootstrap-mds"},{"entity":"client.bootstrap-rbd-mirror"},{"entity":"client.csi-rbd-node.10"},
+ {"entity":"client.csi-rbd-node.4"},{"entity":"client.csi-rbd-node.2"},{"entity":"client.csi-rbd-node.1"},{"entity":"client.csi-cepfs-node"},
+ {"entity":"client.csi-rbd-node"},{"entity":"client.csi-rbd-provisioner"},{"entity":"client.rbd-mirror-peer"},{"entity":"mgr.a"},
+ {"entity":"client.csi-cepfs-node"},{"entity":"client.csi-cephfs-node.2"}
+ ]}`
+)
+
func TestCephCSIKeyringRBDNodeCaps(t *testing.T) {
caps := cephCSIKeyringRBDNodeCaps()
assert.Equal(t, caps, []string{"mon", "profile rbd", "mgr", "allow rw", "osd", "profile rbd"})
@@ -81,7 +95,7 @@ func Test_deleteOwnedCSISecretsByCephCluster(t *testing.T) {
k := keyring.GetSecretStore(ctx, clusterInfo, clusterInfo.OwnerInfo)
// create csi secrets
- err := createOrUpdateCSISecret(clusterInfo, "", "", "", "", k)
+ err := createOrUpdateCSISecret(clusterInfo, csiSecretStore{}, k)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -124,3 +138,387 @@ func Test_deleteOwnedCSISecretsByCephCluster(t *testing.T) {
t.Errorf("expected unowned secret %q to still exist", CsiCephFSProvisionerSecret)
}
}
+
+func TestSortCsiClientName(t *testing.T) {
+ tests := []struct {
+ args []string
+ want []string
+ }{
+ {
+ args: []string{"client.csi-rbd-node.10", "client.csi-rbd-node.1", "client.csi-rbd-node.4", "client.csi-rbd-node.2", "client.csi-rbd-node"},
+ want: []string{
+ "client.csi-rbd-node", "client.csi-rbd-node.1", "client.csi-rbd-node.2", "client.csi-rbd-node.4", "client.csi-rbd-node.10",
+ },
+ },
+ {
+ args: []string{"client.csi-rbd-node"},
+ want: []string{"client.csi-rbd-node"},
+ },
+ {
+ args: []string{},
+ want: []string{},
+ },
+ {
+ // JFYI, // We'll not have list of mixed client name as argument to `sortCsiClientName`
+ args: []string{"client.csi-cephfs-node.1", "client.csi-cephfs-node.2", "client.csi-rbd-node.1", "client.csi-cephfs-node", "client.csi-rbd-node"},
+ want: []string{"client.csi-cephfs-node", "client.csi-rbd-node", "client.csi-cephfs-node.1", "client.csi-rbd-node.1", "client.csi-cephfs-node.2"},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run("testCases", func(t *testing.T) {
+ got := sortCSIClientName(tt.args)
+ if !reflect.DeepEqual(got, tt.want) {
+ t.Errorf("sortCsiClientName() go = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestDeleteOldKeyGen(t *testing.T) {
+ ctx, clusterInfo, _ := loadTestClusterDetails()
+ ctx.Executor = &exectest.MockExecutor{}
+
+ keys := []string{
+ "client.csi-rbd-node.10", "client.csi-rbd-node.1", "client.csi-rbd-node.4", "client.csi-rbd-node.2", "client.csi-rbd-node",
+ }
+
+ // Only the oldest keys ("client.csi-rbd-node" and "client.csi-rbd-node.1") are deleted to retain the latest 3 generations.
+ keyDeleted, err := deleteOldKeyGen(ctx, clusterInfo, keys, 3)
+ assert.NoError(t, err)
+ assert.Equal(t, []string{"client.csi-rbd-node", "client.csi-rbd-node.1"}, keyDeleted)
+
+ // When keepCount is 1, only the most recent key ("client.csi-rbd-node.10") is kept; older keys ("client.csi-rbd-node.1", "client.csi-rbd-node.4") are deleted.
+ keys = []string{"client.csi-rbd-node.10", "client.csi-rbd-node.1", "client.csi-rbd-node.4"}
+ keyDeleted, err = deleteOldKeyGen(ctx, clusterInfo, keys, 1)
+ assert.NoError(t, err)
+ assert.Equal(t, []string{"client.csi-rbd-node.1", "client.csi-rbd-node.4"}, keyDeleted)
+
+ // No keys should be deleted when the input key list is empty.
+ keys = []string{}
+ keyDeleted, err = deleteOldKeyGen(ctx, clusterInfo, keys, 0)
+ assert.NoError(t, err)
+ assert.Equal(t, []string{}, keyDeleted)
+
+ // When only one key is present and keepCount is 0, no keys should be deleted.
+ keys = []string{"client.csi-rbd-node"}
+ keyDeleted, err = deleteOldKeyGen(ctx, clusterInfo, keys, 0)
+ assert.NoError(t, err)
+ assert.Equal(t, []string{}, keyDeleted)
+
+ // When only one key is present and keepCount is 1, no keys should be deleted.
+ keys = []string{"client.csi-rbd-node"}
+ keyDeleted, err = deleteOldKeyGen(ctx, clusterInfo, keys, 1)
+ assert.NoError(t, err)
+ assert.Equal(t, []string{}, keyDeleted)
+}
+
+func TestGetCsiKeyRotationInfo(t *testing.T) {
+ ctx, clusterInfo, _ := loadTestClusterDetails()
+
+ // Different mock auth responses for testing different currentMaxKeyGen values
+ mockAuthLsWithMaxGen10 := `{"auth_dump":[
+ {"entity":"osd.0"},{"entity":"client.admin"},{"entity":"client.bootstrap-mds"},{"entity":"client.bootstrap-rbd-mirror"},{"entity":"client.csi-rbd-node.10"},
+ {"entity":"client.csi-rbd-node.4"},{"entity":"client.csi-rbd-node.2"},{"entity":"client.csi-rbd-node.1"},{"entity":"client.csi-cepfs-node"},
+ {"entity":"client.csi-rbd-node"},{"entity":"client.csi-rbd-provisioner"},{"entity":"client.rbd-mirror-peer"},{"entity":"mgr.a"},
+ {"entity":"client.csi-cepfs-node"},{"entity":"client.csi-cephfs-node.2"}
+ ]}`
+
+ mockAuthLsWithMaxGen5 := `{"auth_dump":[
+ {"entity":"osd.0"},{"entity":"client.admin"},{"entity":"client.bootstrap-mds"},{"entity":"client.bootstrap-rbd-mirror"},
+ {"entity":"client.csi-rbd-node.5"},{"entity":"client.csi-rbd-node.3"},{"entity":"client.csi-rbd-node.1"},{"entity":"client.csi-cepfs-node"},
+ {"entity":"client.csi-rbd-node"},{"entity":"client.csi-rbd-provisioner"},{"entity":"client.rbd-mirror-peer"},{"entity":"mgr.a"}
+ ]}`
+
+ mockAuthLsWithMaxGen0 := `{"auth_dump":[
+ {"entity":"osd.0"},{"entity":"client.admin"},{"entity":"client.bootstrap-mds"},{"entity":"client.bootstrap-rbd-mirror"},
+ {"entity":"client.csi-cepfs-node"},{"entity":"client.csi-rbd-node"},{"entity":"client.csi-rbd-provisioner"},{"entity":"client.rbd-mirror-peer"},{"entity":"mgr.a"}
+ ]}`
+
+ mockAuthLsEmpty := `{"auth_dump":[]}`
+
+ mockAuthLsNoCSIKeys := `{"auth_dump":[
+ {"entity":"osd.0"},{"entity":"client.admin"},{"entity":"client.bootstrap-mds"},{"entity":"client.bootstrap-rbd-mirror"},
+ {"entity":"client.rbd-mirror-peer"},{"entity":"mgr.a"}
+ ]}`
+
+ tests := []struct {
+ name string
+ mockAuthResponse string
+ mockError error
+ expectedMaxKeyGen int
+ expectedKeyList []string
+ expectError bool
+ errorType string
+ }{
+ {
+ name: "currentMaxKeyGen 10 with multiple generations",
+ mockAuthResponse: mockAuthLsWithMaxGen10,
+ mockError: nil,
+ expectedMaxKeyGen: 10,
+ expectedKeyList: []string{"client.csi-rbd-node.10", "client.csi-rbd-node.4", "client.csi-rbd-node.2", "client.csi-rbd-node.1", "client.csi-rbd-node"},
+ expectError: false,
+ },
+ {
+ name: "currentMaxKeyGen 5 with fewer generations",
+ mockAuthResponse: mockAuthLsWithMaxGen5,
+ mockError: nil,
+ expectedMaxKeyGen: 5,
+ expectedKeyList: []string{"client.csi-rbd-node.5", "client.csi-rbd-node.3", "client.csi-rbd-node.1", "client.csi-rbd-node"},
+ expectError: false,
+ },
+ {
+ name: "currentMaxKeyGen 0 with only base name",
+ mockAuthResponse: mockAuthLsWithMaxGen0,
+ mockError: nil,
+ expectedMaxKeyGen: 0,
+ expectedKeyList: []string{"client.csi-rbd-node"},
+ expectError: false,
+ },
+ {
+ name: "empty auth list returns no keys",
+ mockAuthResponse: mockAuthLsEmpty,
+ mockError: nil,
+ expectedMaxKeyGen: 0,
+ expectedKeyList: []string{},
+ expectError: false,
+ },
+ {
+ name: "no CSI keys found returns empty list",
+ mockAuthResponse: mockAuthLsNoCSIKeys,
+ mockError: nil,
+ expectedMaxKeyGen: 0,
+ expectedKeyList: []string{},
+ expectError: false,
+ },
+ {
+ name: "auth list command fails with timeout error",
+ mockAuthResponse: "",
+ mockError: errors.New("timeout: command execution exceeded time limit"),
+ expectedMaxKeyGen: 0,
+ expectedKeyList: []string{},
+ expectError: true,
+ errorType: "timeout",
+ },
+ {
+ name: "invalid JSON response from auth list",
+ mockAuthResponse: `{"auth_dump":[invalid json}`,
+ mockError: nil,
+ expectedMaxKeyGen: 0,
+ expectedKeyList: []string{},
+ expectError: true,
+ errorType: "invalid_json",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ executor := &exectest.MockExecutor{}
+ executor.MockExecuteCommandWithOutput = func(command string, args ...string) (string, error) {
+ logger.Infof("Command: %s %v", command, args)
+ if args[0] == "auth" && args[1] == "ls" {
+ if tt.mockError != nil {
+ return "", tt.mockError
+ }
+ return tt.mockAuthResponse, nil
+ }
+ return "", errors.New("unknown command")
+ }
+ ctx.Executor = executor
+
+ currentMaxKeyGen, keysWithBaseName, err := getCsiKeyRotationInfo(ctx, clusterInfo, csiKeyringRBDNodeUsername)
+
+ if tt.expectError {
+ assert.Error(t, err, "Expected error for test case: %s", tt.name)
+ assert.Equal(t, tt.expectedMaxKeyGen, currentMaxKeyGen, "Max key generation should be 0 on error")
+ assert.Equal(t, tt.expectedKeyList, keysWithBaseName, "Key list should be empty on error")
+
+ if tt.errorType == "timeout" {
+ assert.Contains(t, err.Error(), "timeout", "Error should contain timeout message")
+ }
+ } else {
+ assert.NoError(t, err, "No error expected for test case: %s", tt.name)
+ assert.Equal(t, tt.expectedMaxKeyGen, currentMaxKeyGen, "Max key generation mismatch for test case: %s", tt.name)
+ assert.Equal(t, tt.expectedKeyList, keysWithBaseName, "Key list mismatch for test case: %s", tt.name)
+ }
+ })
+ }
+}
+
+func TestGetCSIKeyInfoAndDeleteOldKey(t *testing.T) {
+ ctx, clusterInfo, clusterSpec := loadTestClusterDetails()
+ clusterSpec.Security.CephX.CSI.KeyGeneration = 18
+ executor := &exectest.MockExecutor{}
+ ctx.Executor = executor
+
+ keyList := []string{"client.csi-rbd-node.10", "client.csi-rbd-node.4", "client.csi-rbd-node.2", "client.csi-rbd-node.1", "client.csi-rbd-node"}
+ executor.MockExecuteCommandWithOutput = func(command string, args ...string) (string, error) {
+ logger.Infof("Command: %s %v", command, args)
+ if args[0] == "auth" && args[1] == "ls" {
+ return mockAuthLs, nil
+ }
+ panic(fmt.Sprintf("unexpected command %s %v", command, args))
+ }
+ currentMaxKeyGen, keyWithBaseName, err := getCsiKeyRotationInfo(ctx, clusterInfo, csiKeyringRBDNodeUsername)
+ assert.NoError(t, err)
+ assert.Equal(t, 10, currentMaxKeyGen)
+ assert.Equal(t, keyList, keyWithBaseName)
+
+ tests := []struct {
+ name string
+ keyList []string
+ keepCount uint8
+ wantDeleted []string
+ }{
+ {"test deletion", keyWithBaseName, 3, []string{"client.csi-rbd-node", "client.csi-rbd-node.1"}},
+ {"keep count = to total key count", keyWithBaseName, 10, []string{}},
+ {"keep count > to total key count", keyWithBaseName, 11, []string{}},
+ {"keep count 0", keyWithBaseName, 0, []string{"client.csi-rbd-node", "client.csi-rbd-node.1", "client.csi-rbd-node.2", "client.csi-rbd-node.4"}},
+ {"keep count 1", keyWithBaseName, 1, []string{"client.csi-rbd-node", "client.csi-rbd-node.1", "client.csi-rbd-node.2", "client.csi-rbd-node.4"}},
+ {"key list empty, keep count 0", []string{}, 0, []string{}},
+ {"key list empty, keep count 1", []string{}, 1, []string{}},
+ {"key list empty, keep count 3", []string{}, 3, []string{}},
+ {"key list with 1 item, keep count 0", []string{"client.csi-rbd-node"}, 0, []string{}},
+ {"key list with 1 item, keep count 1", []string{"client.csi-rbd-node"}, 1, []string{}},
+ {"key list with 1 item, keep count 3", []string{"client.csi-rbd-node"}, 3, []string{}},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ delKeyArgList := []string{}
+ executor.MockExecuteCommandWithOutput = func(command string, args ...string) (string, error) {
+ logger.Infof("Command: %s %v", command, args)
+ if args[0] == "auth" && args[1] == "ls" {
+ return mockAuthLs, nil
+ } else if args[0] == "auth" && args[1] == "del" {
+ delKeyArgList = append(delKeyArgList, args[2])
+ return "", nil
+ }
+ panic(fmt.Sprintf("unexpected command %s %v", command, args))
+ }
+ keyDeleted, err := deleteOldKeyGen(ctx, clusterInfo, test.keyList, test.keepCount)
+ assert.NoError(t, err)
+ assert.Equal(t, test.wantDeleted, keyDeleted)
+ assert.Equal(t, test.wantDeleted, delKeyArgList)
+ })
+ }
+}
+
+func loadTestClusterDetails() (*clusterd.Context, *client.ClusterInfo, *cephv1.ClusterSpec) {
+ namespace := "rook-ceph"
+ cephCluster := "my-ceph-cluster"
+
+ clusterInfo := &client.ClusterInfo{
+ OwnerInfo: k8sutil.NewOwnerInfoWithOwnerRef(&metav1.OwnerReference{
+ APIVersion: "ceph.rook.io/v1",
+ Kind: "CephCluster",
+ Name: cephCluster,
+ }, namespace),
+ Context: context.TODO(),
+ CephVersion: keyring.CephAuthRotateSupportedVersion,
+ }
+ clusterInfo.Namespace = namespace
+ clusterInfo.SetName(cephCluster)
+
+ clusterSpec := &cephv1.ClusterSpec{
+ Security: cephv1.ClusterSecuritySpec{
+ CephX: cephv1.ClusterCephxConfig{
+ CSI: cephv1.CephXConfigWithPriorCount{
+ CephxConfig: cephv1.CephxConfig{
+ KeyRotationPolicy: "KeyGeneration",
+ },
+ },
+ },
+ },
+ }
+
+ clientset := k8sfake.NewSimpleClientset()
+
+ ctx := &clusterd.Context{
+ Clientset: clientset,
+ }
+
+ return ctx, clusterInfo, clusterSpec
+}
+
+func Test_getMatchingClient(t *testing.T) {
+ clientBaseName := csiKeyringRBDNodeUsername
+ want := []string{clientBaseName, clientBaseName + ".1", clientBaseName + ".2", clientBaseName + ".3"}
+
+ t.Run("auth list is valid", func(t *testing.T) {
+ authList := client.AuthListOutput{
+ AuthDump: []client.AuthListEntry{
+ {Entity: clientBaseName}, {Entity: clientBaseName + ".1"}, {Entity: clientBaseName + ".2"}, {Entity: clientBaseName + ".3"}, {Entity: csiKeyringRBDProvisionerUsername + ".4"},
+ },
+ }
+ got, err := getMatchingClient(authList, clientBaseName)
+ assert.NoError(t, err)
+ assert.Equal(t, want, got)
+ })
+
+ // When fresh cluster is deployed `authList` will be empty
+ t.Run("auth list empty", func(t *testing.T) {
+ authList := client.AuthListOutput{
+ AuthDump: []client.AuthListEntry{},
+ }
+ got, err := getMatchingClient(authList, clientBaseName)
+ assert.NoError(t, err)
+ assert.Equal(t, []string{}, got)
+ })
+
+ // When no matching key found in `authList` means key is created for first time
+ t.Run("auth list doesn't contain match", func(t *testing.T) {
+ authList := client.AuthListOutput{
+ AuthDump: []client.AuthListEntry{
+ {Entity: clientBaseName}, {Entity: clientBaseName + ".1"}, {Entity: clientBaseName + ".2"}, {Entity: clientBaseName + ".3"},
+ },
+ }
+ got, err := getMatchingClient(authList, csiKeyringRBDProvisionerUsername)
+ assert.NoError(t, err)
+ assert.Equal(t, []string{}, got)
+ })
+}
+
+func TestParseCsiClient(t *testing.T) {
+ tests := []struct {
+ args string
+ baseName string
+ keyGen int
+ wantErr bool
+ }{
+ {args: "client.csi-rbd-node", baseName: "client.csi-rbd-node", keyGen: 0, wantErr: false},
+ {args: "client.csi-rbd-node.10", baseName: "client.csi-rbd-node", keyGen: 10, wantErr: false},
+ {args: "client.csi-rbd-node.9", baseName: "client.csi-rbd-node", keyGen: 9, wantErr: false},
+ {args: "client.csi-rbd-node.", baseName: "", keyGen: 0, wantErr: true},
+ {args: "client.csi-rbd-node.1a", baseName: "", keyGen: 0, wantErr: true},
+ {args: "client.csi-rbd-node.a1", baseName: "", keyGen: 0, wantErr: true},
+ {args: "client.csi-rbd-node. ", baseName: "", keyGen: 0, wantErr: true},
+ {args: "client.csi-rbd-node. 1", baseName: "", keyGen: 0, wantErr: true},
+ {args: "client.csi-rbd-node .1", baseName: "", keyGen: 0, wantErr: true},
+ {args: "client.csi-rbd-node.1 ", baseName: "", keyGen: 0, wantErr: true},
+ {args: "client.csi-rbd-node. a", baseName: "", keyGen: 0, wantErr: true},
+ {args: "client.csi-rbd-node .a", baseName: "", keyGen: 0, wantErr: true},
+ {args: "client.csi-rbd-node.a ", baseName: "", keyGen: 0, wantErr: true},
+ {args: "client.csi-rbd-node. a1", baseName: "", keyGen: 0, wantErr: true},
+ {args: "client.csi-rbd-node.a1 ", baseName: "", keyGen: 0, wantErr: true},
+ {args: "client.csi-rbd-node. a1", baseName: "", keyGen: 0, wantErr: true},
+ {args: " client.csi-rbd-node. ", baseName: "", keyGen: 0, wantErr: true},
+ {args: "client.csi-rbd-node. 1a", baseName: "", keyGen: 0, wantErr: true},
+ {args: "client.csi-rbd-node .1a", baseName: "", keyGen: 0, wantErr: true},
+ }
+ for _, tt := range tests {
+ t.Run(tt.args, func(t *testing.T) {
+ got, got1, err := parseCsiClient(tt.args)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("parseCsiClient() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+ if got != tt.baseName {
+ t.Errorf("parseCsiClient() got = %v, want %v", got, tt.baseName)
+ }
+ if got1 != tt.keyGen {
+ t.Errorf("parseCsiClient() got1 = %v, want %v", got1, tt.keyGen)
+ }
+ })
+ }
+}
diff --git a/tests/scripts/collect-logs.sh b/tests/scripts/collect-logs.sh
index 783a42233..20a75ea15 100755
--- a/tests/scripts/collect-logs.sh
+++ b/tests/scripts/collect-logs.sh
@@ -16,6 +16,7 @@ CEPH_CMD="kubectl -n ${CLUSTER_NAMESPACE} exec deploy/rook-ceph-tools -- ceph --
$CEPH_CMD -s >"${LOG_DIR}"/ceph-status.txt
$CEPH_CMD osd dump >"${LOG_DIR}"/ceph-osd-dump.txt
$CEPH_CMD report >"${LOG_DIR}"/ceph-report.txt
+$CEPH_CMD auth ls >"${LOG_DIR}"/ceph-auth-ls.txt
NAMESPACES=("$CLUSTER_NAMESPACE")
if [[ "$OPERATOR_NAMESPACE" != "$CLUSTER_NAMESPACE" ]]; then