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 <srai@redhat.com>
This commit is contained in:
subhamkrai committed 2025-07-25 15:39:00 +05:30
1 parent d720f2ae6c
commit 6d5401c50d
12 files changed
+1078 -43

No files matched your search

+122 -2
View File
@@ -4502,10 +4502,60 @@ One of Always, Never, IfNotPresent.</p>
</tr>
</tbody>
</table>
<h3 id="ceph.rook.io/v1.CephXConfigWithPriorCount">CephXConfigWithPriorCount
</h3>
<p>
(<em>Appears on:</em><a href="#ceph.rook.io/v1.ClusterCephxConfig">ClusterCephxConfig</a>)
</p>
<div>
</div>
<table>
<thead>
<tr>
<th>Field</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<code>CephxConfig</code><br/>
<em>
<a href="#ceph.rook.io/v1.CephxConfig">
CephxConfig
</a>
</em>
</td>
<td>
<p>
(Members of <code>CephxConfig</code> are embedded into this type.)
</p>
</td>
</tr>
<tr>
<td>
<code>keepPriorKeyCountMax</code><br/>
<em>
byte
</em>
</td>
<td>
<em>(Optional)</em>
<p>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.</p>
</td>
</tr>
</tbody>
</table>
<h3 id="ceph.rook.io/v1.CephxConfig">CephxConfig
</h3>
<p>
(<em>Appears on:</em><a href="#ceph.rook.io/v1.ClientSecuritySpec">ClientSecuritySpec</a>, <a href="#ceph.rook.io/v1.ClusterCephxConfig">ClusterCephxConfig</a>)
(<em>Appears on:</em><a href="#ceph.rook.io/v1.CephXConfigWithPriorCount">CephXConfigWithPriorCount</a>, <a href="#ceph.rook.io/v1.ClientSecuritySpec">ClientSecuritySpec</a>, <a href="#ceph.rook.io/v1.ClusterCephxConfig">ClusterCephxConfig</a>)
</p>
<div>
</div>
@@ -4574,7 +4624,7 @@ are not rotated.</p>
<h3 id="ceph.rook.io/v1.CephxStatus">CephxStatus
</h3>
<p>
(<em>Appears on:</em><a href="#ceph.rook.io/v1.CephClientStatus">CephClientStatus</a>, <a href="#ceph.rook.io/v1.ClusterCephxStatus">ClusterCephxStatus</a>, <a href="#ceph.rook.io/v1.LocalCephxStatus">LocalCephxStatus</a>)
(<em>Appears on:</em><a href="#ceph.rook.io/v1.CephClientStatus">CephClientStatus</a>, <a href="#ceph.rook.io/v1.CephxStatusWithKeyCount">CephxStatusWithKeyCount</a>, <a href="#ceph.rook.io/v1.ClusterCephxStatus">ClusterCephxStatus</a>, <a href="#ceph.rook.io/v1.LocalCephxStatus">LocalCephxStatus</a>)
</p>
<div>
</div>
@@ -4619,6 +4669,49 @@ An empty string indicates that the version is unknown, as expected in brownfield
</tr>
</tbody>
</table>
<h3 id="ceph.rook.io/v1.CephxStatusWithKeyCount">CephxStatusWithKeyCount
</h3>
<p>
(<em>Appears on:</em><a href="#ceph.rook.io/v1.ClusterCephxStatus">ClusterCephxStatus</a>)
</p>
<div>
</div>
<table>
<thead>
<tr>
<th>Field</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<code>CephxStatus</code><br/>
<em>
<a href="#ceph.rook.io/v1.CephxStatus">
CephxStatus
</a>
</em>
</td>
<td>
<p>
(Members of <code>CephxStatus</code> are embedded into this type.)
</p>
</td>
</tr>
<tr>
<td>
<code>priorKeyCount</code><br/>
<em>
byte
</em>
</td>
<td>
<p>PriorKeyCount reports the number of prior-generation CephX keys that remain active for the related component</p>
</td>
</tr>
</tbody>
</table>
<h3 id="ceph.rook.io/v1.CleanupConfirmationProperty">CleanupConfirmationProperty
(<code>string</code> alias)</h3>
<p>
@@ -4850,6 +4943,20 @@ CephxConfig
Ceph cluster. Daemon CephX keys can be rotated without affecting client connections.</p>
</td>
</tr>
<tr>
<td>
<code>csi</code><br/>
<em>
<a href="#ceph.rook.io/v1.CephXConfigWithPriorCount">
CephXConfigWithPriorCount
</a>
</em>
</td>
<td>
<p>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.</p>
</td>
</tr>
</tbody>
</table>
<h3 id="ceph.rook.io/v1.ClusterCephxStatus">ClusterCephxStatus
@@ -4894,6 +5001,19 @@ CephxStatus
<p>RBDMirrorPeer represents the cephx key rotation status of the <code>rbd-mirror-peer</code> user</p>
</td>
</tr>
<tr>
<td>
<code>csi</code><br/>
<em>
<a href="#ceph.rook.io/v1.CephxStatusWithKeyCount">
CephxStatusWithKeyCount
</a>
</em>
</td>
<td>
<p>CSI shows the CephX key status for Ceph-CSI components.</p>
</td>
</tr>
</tbody>
</table>
<h3 id="ceph.rook.io/v1.ClusterSecuritySpec">ClusterSecuritySpec
@@ -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:
+67
View File
@@ -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:
+30
View File
@@ -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
@@ -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
}
+29
View File
@@ -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
}
+5 -2
View File
@@ -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 {
@@ -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")
}
+1 -1
View File
@@ -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
+316 -36
View File
@@ -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 `<baseName>.<keyGeneration>`
// 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.<keyGen>` 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.<baseName>[.<generation>]"
// 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
}
+399 -1
View File
@@ -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)
}
})
}
}
+1
View File
@@ -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