From 5f50e85a251a68b4066eeb7442aaea1be2cd3bb9 Mon Sep 17 00:00:00 2001 From: Blaine Gardner Date: Thu, 1 May 2025 15:51:39 -0600 Subject: [PATCH] object: implement cephx key rotation for rgw keys This is the first implementation of CephX key rotation in Rook. Adds key rotation API from design PR 15915. Also add helper methods for rotating keys, determining when keys need to be rotated, and for generating CephX key statuses. These will be reusable for other Rook reconciles beyond object/RGW. Signed-off-by: Blaine Gardner --- Documentation/CRDs/specification.md | 264 ++++++++++++- .../charts/rook-ceph/templates/resources.yaml | 61 ++- deploy/examples/crds.yaml | 61 ++- pkg/apis/ceph.rook.io/v1/types.go | 79 +++- .../ceph.rook.io/v1/zz_generated.deepcopy.go | 86 +++++ pkg/daemon/ceph/client/auth.go | 33 ++ pkg/daemon/ceph/osd/encryption.go | 2 +- pkg/daemon/ceph/osd/kms/envs_test.go | 18 +- pkg/operator/ceph/cluster/cephstatus.go | 2 +- pkg/operator/ceph/cluster/mgr/config.go | 2 +- pkg/operator/ceph/cluster/mon/mon.go | 2 +- .../ceph/cluster/nodedaemon/keyring.go | 4 +- pkg/operator/ceph/cluster/osd/volumes_test.go | 2 +- pkg/operator/ceph/cluster/rbd/config.go | 2 +- pkg/operator/ceph/config/keyring/admin.go | 2 +- pkg/operator/ceph/config/keyring/cephx.go | 186 +++++++++ .../ceph/config/keyring/cephx_test.go | 185 +++++++++ pkg/operator/ceph/config/keyring/store.go | 41 +- .../ceph/config/keyring/store_test.go | 10 +- pkg/operator/ceph/controller/label.go | 2 +- pkg/operator/ceph/controller/predicate.go | 10 +- pkg/operator/ceph/csi/secrets.go | 2 +- pkg/operator/ceph/file/mds/config.go | 2 +- pkg/operator/ceph/file/mirror/config.go | 2 +- pkg/operator/ceph/nfs/config.go | 3 +- pkg/operator/ceph/object/config.go | 12 +- pkg/operator/ceph/object/controller.go | 57 ++- pkg/operator/ceph/object/controller_test.go | 353 +++++++++++++++++- pkg/operator/ceph/object/rgw.go | 23 +- pkg/operator/ceph/object/rgw_test.go | 7 +- pkg/operator/ceph/object/status.go | 8 +- 31 files changed, 1439 insertions(+), 84 deletions(-) create mode 100644 pkg/operator/ceph/config/keyring/cephx.go create mode 100644 pkg/operator/ceph/config/keyring/cephx_test.go diff --git a/Documentation/CRDs/specification.md b/Documentation/CRDs/specification.md index a77799846..e85813766 100644 --- a/Documentation/CRDs/specification.md +++ b/Documentation/CRDs/specification.md @@ -998,8 +998,8 @@ CephClusterHealthCheckSpec security
- -SecuritySpec + +ClusterSecuritySpec @@ -4412,6 +4412,123 @@ One of Always, Never, IfNotPresent.

+

CephxConfig +

+

+(Appears on:ClusterCephxConfig) +

+
+
+ + + + + + + + + + + + + + + + + +
FieldDescription
+keyRotationPolicy
+ + +CephxKeyRotationPolicy + + +
+(Optional) +

KeyRotationPolicy controls if and when CephX keys are rotated after initial creation. +One of Disabled, or KeyGeneration. Default Disabled.

+
+keyGeneration
+ +uint32 + +
+(Optional) +

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.

+
+

CephxKeyRotationPolicy +(string alias)

+

+(Appears on:CephxConfig) +

+
+
+ + + + + + + + + + + + +
ValueDescription

"Disabled"

"KeyGeneration"

+

CephxStatus +

+

+(Appears on:LocalCephxStatus) +

+
+
+ + + + + + + + + + + + + + + + + +
FieldDescription
+keyGeneration
+ +uint32 + +
+

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.

+
+keyCephVersion
+ +string + +
+

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.

+

CleanupConfirmationProperty (string alias)

@@ -4529,6 +4646,97 @@ map[string]string +

ClusterCephxConfig +

+

+(Appears on:ClusterSecuritySpec) +

+
+
+ + + + + + + + + + + + + +
FieldDescription
+daemon
+ + +CephxConfig + + +
+

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.

+
+

ClusterSecuritySpec +

+

+(Appears on:ClusterSpec) +

+
+

ClusterSecuritySpec is the CephCluster security spec to include various security items such as kms

+
+ + + + + + + + + + + + + + + + + + + + + +
FieldDescription
+kms
+ + +KeyManagementServiceSpec + + +
+(Optional) +

KeyManagementService is the main Key Management option

+
+keyRotation
+ + +KeyRotationSpec + + +
+(Optional) +

KeyRotation defines options for rotation of OSD disk encryption keys.

+
+cephx
+ + +ClusterCephxConfig + + +
+(Optional) +

CephX configures CephX key settings. More: https://docs.ceph.com/en/latest/dev/cephx/

+

ClusterSpec

@@ -4867,8 +5075,8 @@ CephClusterHealthCheckSpec security
- -SecuritySpec + +ClusterSecuritySpec @@ -7762,7 +7970,7 @@ securely add the file via annotations on the CephNFS spec (passed to the NFS ser

KeyManagementServiceSpec

-(Appears on:ObjectStoreSecuritySpec, SecuritySpec) +(Appears on:ClusterSecuritySpec, ObjectStoreSecuritySpec, SecuritySpec)

KeyManagementServiceSpec represent various details of the KMS server

@@ -7804,7 +8012,7 @@ string

KeyRotationSpec

-(Appears on:SecuritySpec) +(Appears on:ClusterSecuritySpec, SecuritySpec)

KeyRotationSpec represents the settings for Key Rotation.

@@ -7992,6 +8200,36 @@ int

LabelsSpec is the main spec label for all daemons

+

LocalCephxStatus +

+

+(Appears on:ObjectStoreStatus) +

+
+
+ + + + + + + + + + + + + +
FieldDescription
+daemon
+ + +CephxStatus + + +
+

Daemon shows the CephX key status for local Ceph daemons associated with this resources.

+

LogCollectorSpec

@@ -10398,6 +10636,18 @@ map[string]string +cephx
+ + +LocalCephxStatus + + + + + + + + conditions
@@ -12601,7 +12851,7 @@ string

SecuritySpec

-(Appears on:ClusterSpec, ObjectStoreSecuritySpec) +(Appears on:ObjectStoreSecuritySpec)

SecuritySpec is security spec to include various security items such as kms

diff --git a/deploy/charts/rook-ceph/templates/resources.yaml b/deploy/charts/rook-ceph/templates/resources.yaml index 6be152d56..dfd725060 100644 --- a/deploy/charts/rook-ceph/templates/resources.yaml +++ b/deploy/charts/rook-ceph/templates/resources.yaml @@ -3461,8 +3461,42 @@ spec: description: Security represents security settings nullable: true properties: + cephx: + description: 'CephX configures CephX key settings. More: https://docs.ceph.com/en/latest/dev/cephx/' + properties: + daemon: + description: |- + 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. + properties: + 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 + type: object keyRotation: - description: KeyRotation defines options for Key Rotation. + description: KeyRotation defines options for rotation of OSD disk encryption keys. nullable: true properties: enabled: @@ -12890,6 +12924,31 @@ spec: status: description: ObjectStoreStatus represents the status of a Ceph Object Store resource properties: + cephx: + properties: + daemon: + description: Daemon shows the CephX key status for local Ceph daemons associated with this resources. + 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 + type: object + type: object conditions: items: description: Condition represents a status condition on any Rook-Ceph Custom Resource. diff --git a/deploy/examples/crds.yaml b/deploy/examples/crds.yaml index fdae3f1c1..dbb5a8383 100644 --- a/deploy/examples/crds.yaml +++ b/deploy/examples/crds.yaml @@ -3459,8 +3459,42 @@ spec: description: Security represents security settings nullable: true properties: + cephx: + description: 'CephX configures CephX key settings. More: https://docs.ceph.com/en/latest/dev/cephx/' + properties: + daemon: + description: |- + 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. + properties: + 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 + type: object keyRotation: - description: KeyRotation defines options for Key Rotation. + description: KeyRotation defines options for rotation of OSD disk encryption keys. nullable: true properties: enabled: @@ -12881,6 +12915,31 @@ spec: status: description: ObjectStoreStatus represents the status of a Ceph Object Store resource properties: + cephx: + properties: + daemon: + description: Daemon shows the CephX key status for local Ceph daemons associated with this resources. + 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 + type: object + type: object conditions: items: description: Condition represents a status condition on any Rook-Ceph Custom Resource. diff --git a/pkg/apis/ceph.rook.io/v1/types.go b/pkg/apis/ceph.rook.io/v1/types.go index 0d9cc90e9..5ea69c70e 100755 --- a/pkg/apis/ceph.rook.io/v1/types.go +++ b/pkg/apis/ceph.rook.io/v1/types.go @@ -224,7 +224,7 @@ type ClusterSpec struct { // Security represents security settings // +optional // +nullable - Security SecuritySpec `json:"security,omitempty"` + Security ClusterSecuritySpec `json:"security,omitempty"` // Logging represents loggings settings // +optional @@ -304,6 +304,55 @@ type SecuritySpec struct { KeyRotation KeyRotationSpec `json:"keyRotation,omitempty"` } +// ClusterSecuritySpec is the CephCluster security spec to include various security items such as kms +type ClusterSecuritySpec struct { + // KeyManagementService is the main Key Management option + // +optional + // +nullable + KeyManagementService KeyManagementServiceSpec `json:"kms,omitempty"` + // KeyRotation defines options for rotation of OSD disk encryption keys. + // +optional + // +nullable + KeyRotation KeyRotationSpec `json:"keyRotation,omitempty"` + + // CephX configures CephX key settings. More: https://docs.ceph.com/en/latest/dev/cephx/ + // +optional + CephX ClusterCephxConfig `json:"cephx,omitempty"` +} + +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"` +} + +type CephxConfig struct { + // KeyRotationPolicy controls if and when CephX keys are rotated after initial creation. + // One of Disabled, or KeyGeneration. Default Disabled. + // +optional + // +kubebuilder:validation:Enum="";Disabled;KeyGeneration + KeyRotationPolicy CephxKeyRotationPolicy `json:"keyRotationPolicy,omitempty"` + + // 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. + // +optional + // +kubebuilder:validation:Minimum=0 + // +kubebuilder:validation:Maximum=4294967295 + // +kubebuilder:validation:XValidation:message="keyGeneration cannot be decreased",rule="self >= oldSelf" + KeyGeneration uint32 `json:"keyGeneration,omitempty"` +} + +type CephxKeyRotationPolicy string + +const ( + DisabledCephxKeyRotationPolicy CephxKeyRotationPolicy = "Disabled" + KeyGenerationCephxKeyRotationPolicy CephxKeyRotationPolicy = "KeyGeneration" +) + // ObjectStoreSecuritySpec is spec to define security features like encryption type ObjectStoreSecuritySpec struct { // +optional @@ -609,6 +658,33 @@ const ( ClusterStateError ClusterState = "Error" ) +type CephxStatus struct { + // 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. + KeyGeneration uint32 `json:"keyGeneration,omitempty"` + + // 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. + KeyCephVersion string `json:"keyCephVersion,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. +const UninitializedCephxKeyCephVersion string = "Uninitialized" + +type LocalCephxStatus struct { + // Daemon shows the CephX key status for local Ceph daemons associated with this resources. + Daemon CephxStatus `json:"daemon,omitempty"` +} + // MonSpec represents the specification of the monitor // +kubebuilder:validation:XValidation:message="zones must be less than or equal to count",rule="!has(self.zones) || (has(self.zones) && (size(self.zones) <= self.count))" // +kubebuilder:validation:XValidation:message="stretchCluster zones must be equal to 3",rule="!has(self.stretchCluster) || (has(self.stretchCluster) && (size(self.stretchCluster.zones) > 0) && (size(self.stretchCluster.zones) == 3))" @@ -1924,6 +2000,7 @@ type ObjectStoreStatus struct { // +optional // +nullable Info map[string]string `json:"info,omitempty"` + Cephx LocalCephxStatus `json:"cephx,omitempty"` Conditions []Condition `json:"conditions,omitempty"` // ObservedGeneration is the latest generation observed by the controller. // +optional 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 5ad7a281d..4f81ea70e 100644 --- a/pkg/apis/ceph.rook.io/v1/zz_generated.deepcopy.go +++ b/pkg/apis/ceph.rook.io/v1/zz_generated.deepcopy.go @@ -1916,6 +1916,38 @@ 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 *CephxConfig) DeepCopyInto(out *CephxConfig) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CephxConfig. +func (in *CephxConfig) DeepCopy() *CephxConfig { + if in == nil { + return nil + } + out := new(CephxConfig) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CephxStatus) DeepCopyInto(out *CephxStatus) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CephxStatus. +func (in *CephxStatus) DeepCopy() *CephxStatus { + if in == nil { + return nil + } + out := new(CephxStatus) + 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 @@ -1956,6 +1988,42 @@ func (in *ClientSpec) DeepCopy() *ClientSpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterCephxConfig) DeepCopyInto(out *ClusterCephxConfig) { + *out = *in + out.Daemon = in.Daemon + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterCephxConfig. +func (in *ClusterCephxConfig) DeepCopy() *ClusterCephxConfig { + if in == nil { + return nil + } + out := new(ClusterCephxConfig) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterSecuritySpec) DeepCopyInto(out *ClusterSecuritySpec) { + *out = *in + in.KeyManagementService.DeepCopyInto(&out.KeyManagementService) + out.KeyRotation = in.KeyRotation + out.CephX = in.CephX + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterSecuritySpec. +func (in *ClusterSecuritySpec) DeepCopy() *ClusterSecuritySpec { + if in == nil { + return nil + } + out := new(ClusterSecuritySpec) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ClusterSpec) DeepCopyInto(out *ClusterSpec) { *out = *in @@ -3060,6 +3128,23 @@ func (in LabelsSpec) DeepCopy() LabelsSpec { return *out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *LocalCephxStatus) DeepCopyInto(out *LocalCephxStatus) { + *out = *in + out.Daemon = in.Daemon + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LocalCephxStatus. +func (in *LocalCephxStatus) DeepCopy() *LocalCephxStatus { + if in == nil { + return nil + } + out := new(LocalCephxStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *LogCollectorSpec) DeepCopyInto(out *LogCollectorSpec) { *out = *in @@ -3947,6 +4032,7 @@ func (in *ObjectStoreStatus) DeepCopyInto(out *ObjectStoreStatus) { (*out)[key] = val } } + out.Cephx = in.Cephx if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions *out = make([]Condition, len(*in)) diff --git a/pkg/daemon/ceph/client/auth.go b/pkg/daemon/ceph/client/auth.go index ab5eb7da5..2e9c6a184 100644 --- a/pkg/daemon/ceph/client/auth.go +++ b/pkg/daemon/ceph/client/auth.go @@ -17,9 +17,11 @@ package client import ( "encoding/json" + "syscall" "github.com/pkg/errors" "github.com/rook/rook/pkg/clusterd" + "github.com/rook/rook/pkg/util/exec" ) // AuthGetOrCreate will either get or create a user with the given capabilities. The keyring for the @@ -104,6 +106,37 @@ func AuthGetCaps(context *clusterd.Context, clusterInfo *ClusterInfo, name strin return caps, err } +// AuthRotate rotates a daemon's cephx auth key, retaining existing caps. +func AuthRotate(context *clusterd.Context, clusterInfo *ClusterInfo, name string) (string, error) { + logger.Infof("rotating ceph auth key %q", name) + args := []string{"auth", "rotate", name} + buf, err := NewCephCommand(context, clusterInfo, args).Run() + if err != nil { + if code, ok := exec.ExitStatus(err); ok && code == int(syscall.EINVAL) { + // `ceph auth rotate` is not yet present in all ceph versions. as long as the command + // invocation is correct, EINVAL means the ceph version doesn't have the rotate + // subcommand added in: https://github.com/ceph/ceph/pull/58121 + // all version of ceph v20 (tentacle) and higher should have the command present + return "", errors.Wrapf(err, "failed auth rotate %s. operator or cluster ceph version does not support ceph auth rotate", name) + } + return "", errors.Wrapf(err, "failed auth rotate %s", name) + } + + var data []map[string]interface{} + err = json.Unmarshal(buf, &data) + if err != nil { + return "", errors.Wrapf(err, "failed to unmarshal auth rotate %s response", name) + } + if len(data) < 1 { + return "", errors.Errorf("auth rotate %s returned no results", name) + } + if len(data) > 1 { + logger.Infof("auth rotate %s returned more than 1 result; continuing using the first result", name) + } + + return data[0]["key"].(string), nil +} + // AuthDelete will delete the given user. func AuthDelete(context *clusterd.Context, clusterInfo *ClusterInfo, name string) error { logger.Infof("deleting ceph auth %q", name) diff --git a/pkg/daemon/ceph/osd/encryption.go b/pkg/daemon/ceph/osd/encryption.go index 6d8f06c14..d3a26c445 100644 --- a/pkg/daemon/ceph/osd/encryption.go +++ b/pkg/daemon/ceph/osd/encryption.go @@ -68,7 +68,7 @@ func setKEKinEnv(context *clusterd.Context, clusterInfo *cephclient.ClusterInfo) // KMS details are passed by the Operator as env variables in the pod // The token if any is mounted in the provisioner pod as an env variable so the secrets lib will // pick it up - clusterSpec := &v1.ClusterSpec{Security: v1.SecuritySpec{KeyManagementService: v1.KeyManagementServiceSpec{ConnectionDetails: kms.ConfigEnvsToMapString()}}} + clusterSpec := &v1.ClusterSpec{Security: v1.ClusterSecuritySpec{KeyManagementService: v1.KeyManagementServiceSpec{ConnectionDetails: kms.ConfigEnvsToMapString()}}} // If KMS is not enabled this code does not need to run since we attach the KEK value from the // Kubernetes Secret in the provision pod spec (mounted as an environment variable) diff --git a/pkg/daemon/ceph/osd/kms/envs_test.go b/pkg/daemon/ceph/osd/kms/envs_test.go index 9ed54b607..2f9a16369 100644 --- a/pkg/daemon/ceph/osd/kms/envs_test.go +++ b/pkg/daemon/ceph/osd/kms/envs_test.go @@ -29,7 +29,7 @@ import ( func TestVaultTLSEnvVarFromSecret(t *testing.T) { t.Run("vault - no tls", func(t *testing.T) { spec := cephv1.ClusterSpec{ - Security: cephv1.SecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{ + Security: cephv1.ClusterSecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{ TokenSecretName: "vault-token", ConnectionDetails: map[string]string{"KMS_PROVIDER": "vault", "VAULT_ADDR": "http://1.1.1.1:8200"}, }}, @@ -47,7 +47,7 @@ func TestVaultTLSEnvVarFromSecret(t *testing.T) { }) t.Run("vault tls", func(t *testing.T) { spec := cephv1.ClusterSpec{ - Security: cephv1.SecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{ + Security: cephv1.ClusterSecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{ TokenSecretName: "vault-token", ConnectionDetails: map[string]string{"KMS_PROVIDER": "vault", "VAULT_ADDR": "http://1.1.1.1:8200", "VAULT_CACERT": "vault-ca-cert-secret"}, }}, @@ -65,7 +65,7 @@ func TestVaultTLSEnvVarFromSecret(t *testing.T) { }) t.Run("ibm kp", func(t *testing.T) { spec := cephv1.ClusterSpec{ - Security: cephv1.SecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{ + Security: cephv1.ClusterSecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{ TokenSecretName: "ibm-kp-token", ConnectionDetails: map[string]string{"KMS_PROVIDER": TypeIBM, "IBM_KP_SERVICE_INSTANCE_ID": "1"}, }}, @@ -100,7 +100,7 @@ func TestConfigEnvsToMapString(t *testing.T) { envs = ConfigEnvsToMapString() assert.Equal(t, 3, len(envs)) assert.True(t, envs["KMS_PROVIDER"] == "vault") - clusterSpec := &cephv1.ClusterSpec{Security: cephv1.SecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{ConnectionDetails: envs}}} + clusterSpec := &cephv1.ClusterSpec{Security: cephv1.ClusterSecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{ConnectionDetails: envs}}} assert.True(t, clusterSpec.Security.KeyManagementService.IsEnabled()) } @@ -115,7 +115,7 @@ func TestVaultConfigToEnvVar(t *testing.T) { }{ { "vault - no backend path", - args{spec: cephv1.ClusterSpec{Security: cephv1.SecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{ConnectionDetails: map[string]string{"KMS_PROVIDER": "vault"}}}}}, + args{spec: cephv1.ClusterSpec{Security: cephv1.ClusterSecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{ConnectionDetails: map[string]string{"KMS_PROVIDER": "vault"}}}}}, []v1.EnvVar{ {Name: "KMS_PROVIDER", Value: "vault"}, {Name: "VAULT_BACKEND_PATH", Value: "secret/"}, @@ -123,7 +123,7 @@ func TestVaultConfigToEnvVar(t *testing.T) { }, { "vault - with backend path", - args{spec: cephv1.ClusterSpec{Security: cephv1.SecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{ConnectionDetails: map[string]string{"KMS_PROVIDER": "vault", "VAULT_BACKEND_PATH": "foo/"}}}}}, + args{spec: cephv1.ClusterSpec{Security: cephv1.ClusterSecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{ConnectionDetails: map[string]string{"KMS_PROVIDER": "vault", "VAULT_BACKEND_PATH": "foo/"}}}}}, []v1.EnvVar{ {Name: "KMS_PROVIDER", Value: "vault"}, {Name: "VAULT_BACKEND_PATH", Value: "foo/"}, @@ -131,7 +131,7 @@ func TestVaultConfigToEnvVar(t *testing.T) { }, { "vault - test with tls config", - args{spec: cephv1.ClusterSpec{Security: cephv1.SecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{ConnectionDetails: map[string]string{"KMS_PROVIDER": "vault", "VAULT_CACERT": "my-secret-name"}}}}}, + args{spec: cephv1.ClusterSpec{Security: cephv1.ClusterSecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{ConnectionDetails: map[string]string{"KMS_PROVIDER": "vault", "VAULT_CACERT": "my-secret-name"}}}}}, []v1.EnvVar{ {Name: "KMS_PROVIDER", Value: "vault"}, {Name: "VAULT_BACKEND_PATH", Value: "secret/"}, @@ -140,7 +140,7 @@ func TestVaultConfigToEnvVar(t *testing.T) { }, { "ibm kp - IBM_KP_SERVICE_API_KEY is removed from the details", - args{spec: cephv1.ClusterSpec{Security: cephv1.SecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{ConnectionDetails: map[string]string{"KMS_PROVIDER": TypeIBM, "IBM_KP_SERVICE_API_KEY": "foo", "IBM_KP_SERVICE_INSTANCE_ID": "1"}, TokenSecretName: "ibm-kp-token"}}}}, + args{spec: cephv1.ClusterSpec{Security: cephv1.ClusterSecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{ConnectionDetails: map[string]string{"KMS_PROVIDER": TypeIBM, "IBM_KP_SERVICE_API_KEY": "foo", "IBM_KP_SERVICE_INSTANCE_ID": "1"}, TokenSecretName: "ibm-kp-token"}}}}, []v1.EnvVar{ {Name: "IBM_KP_SERVICE_API_KEY", ValueFrom: &v1.EnvVarSource{SecretKeyRef: &v1.SecretKeySelector{LocalObjectReference: v1.LocalObjectReference{Name: "ibm-kp-token"}, Key: "IBM_KP_SERVICE_API_KEY"}}}, {Name: "IBM_KP_SERVICE_INSTANCE_ID", Value: "1"}, @@ -149,7 +149,7 @@ func TestVaultConfigToEnvVar(t *testing.T) { }, { "kmip - token details is removed from the details", - args{spec: cephv1.ClusterSpec{Security: cephv1.SecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{ConnectionDetails: map[string]string{"KMS_PROVIDER": TypeKMIP, "CLIENT_KEY": "foo", "CLIENT_CERT": "foo", "CA_CERT": "foo", "TLS_SERVER_NAME": "pykmip"}, TokenSecretName: "kmip-token"}}}}, + args{spec: cephv1.ClusterSpec{Security: cephv1.ClusterSecuritySpec{KeyManagementService: cephv1.KeyManagementServiceSpec{ConnectionDetails: map[string]string{"KMS_PROVIDER": TypeKMIP, "CLIENT_KEY": "foo", "CLIENT_CERT": "foo", "CA_CERT": "foo", "TLS_SERVER_NAME": "pykmip"}, TokenSecretName: "kmip-token"}}}}, []v1.EnvVar{ {Name: "KMIP_KMS_PROVIDER", Value: TypeKMIP}, {Name: "KMIP_TLS_SERVER_NAME", Value: "pykmip"}, diff --git a/pkg/operator/ceph/cluster/cephstatus.go b/pkg/operator/ceph/cluster/cephstatus.go index 4234d3c02..a44d4290b 100644 --- a/pkg/operator/ceph/cluster/cephstatus.go +++ b/pkg/operator/ceph/cluster/cephstatus.go @@ -258,7 +258,7 @@ func (c *ClusterController) updateClusterCephVersion(image string, cephVersion c cephClusterVersion := &cephv1.ClusterVersion{ Image: image, - Version: opcontroller.GetCephVersionLabel(cephVersion), + Version: opcontroller.GetCephVersionLabel(cephVersion), // DO NOT CHANGE FORMAT FROM "Maj.Min.Ext-Bld" } // update the Ceph version on the retrieved cluster object // do not overwrite the ceph status that is updated in a separate goroutine diff --git a/pkg/operator/ceph/cluster/mgr/config.go b/pkg/operator/ceph/cluster/mgr/config.go index a7e28e355..886acf0e5 100644 --- a/pkg/operator/ceph/cluster/mgr/config.go +++ b/pkg/operator/ceph/cluster/mgr/config.go @@ -98,5 +98,5 @@ func (c *Cluster) generateKeyring(m *mgrConfig) (string, error) { } keyring := fmt.Sprintf(keyringTemplate, m.DaemonID, key) - return keyring, s.CreateOrUpdate(m.ResourceName, keyring) + return s.CreateOrUpdate(m.ResourceName, keyring) } diff --git a/pkg/operator/ceph/cluster/mon/mon.go b/pkg/operator/ceph/cluster/mon/mon.go index 99f305592..0bdb58006 100644 --- a/pkg/operator/ceph/cluster/mon/mon.go +++ b/pkg/operator/ceph/cluster/mon/mon.go @@ -551,7 +551,7 @@ func (c *Cluster) initClusterInfo(cephVersion cephver.CephVersion, clusterName s k := keyring.GetSecretStore(c.context, c.ClusterInfo, c.ownerInfo) // store the keyring which all mons share - if err := k.CreateOrUpdate(keyringStoreName, c.genMonSharedKeyring()); err != nil { + if _, err := k.CreateOrUpdate(keyringStoreName, c.genMonSharedKeyring()); err != nil { return errors.Wrap(err, "failed to save mon keyring secret") } // also store the admin keyring for other daemons that might need it during init diff --git a/pkg/operator/ceph/cluster/nodedaemon/keyring.go b/pkg/operator/ceph/cluster/nodedaemon/keyring.go index 3cd69de57..c2e30f380 100644 --- a/pkg/operator/ceph/cluster/nodedaemon/keyring.go +++ b/pkg/operator/ceph/cluster/nodedaemon/keyring.go @@ -102,7 +102,7 @@ func createOrUpdateCrashCollectorSecret(clusterInfo *client.ClusterInfo, crashCo } // Create Kubernetes Secret - err = k.CreateSecret(s) + _, err = k.CreateSecret(s) if err != nil { return errors.Wrapf(err, "failed to create kubernetes secret %q for cluster %q", s.Name, clusterInfo.Namespace) } @@ -167,7 +167,7 @@ func createOrUpdateExporterSecret(clusterInfo *client.ClusterInfo, exporterSecre } // Create Kubernetes Secret - err = k.CreateSecret(s) + _, err = k.CreateSecret(s) if err != nil { return errors.Wrapf(err, "failed to create kubernetes secret %q for cluster %q", s.Name, clusterInfo.Namespace) } diff --git a/pkg/operator/ceph/cluster/osd/volumes_test.go b/pkg/operator/ceph/cluster/osd/volumes_test.go index 0114202e1..abb788dac 100644 --- a/pkg/operator/ceph/cluster/osd/volumes_test.go +++ b/pkg/operator/ceph/cluster/osd/volumes_test.go @@ -36,7 +36,7 @@ func TestGetEncryptionVolume(t *testing.T) { assert.Equal(t, v1.VolumeMount{Name: "osd-encryption-key", ReadOnly: true, MountPath: "/etc/ceph"}, vM) // With KMS - c.spec.Security = cephv1.SecuritySpec{ + c.spec.Security = cephv1.ClusterSecuritySpec{ KeyManagementService: cephv1.KeyManagementServiceSpec{ ConnectionDetails: map[string]string{"KMS_PROVIDER": "vault"}, }, diff --git a/pkg/operator/ceph/cluster/rbd/config.go b/pkg/operator/ceph/cluster/rbd/config.go index fe6678789..b34eb1837 100644 --- a/pkg/operator/ceph/cluster/rbd/config.go +++ b/pkg/operator/ceph/cluster/rbd/config.go @@ -70,7 +70,7 @@ func (r *ReconcileCephRBDMirror) generateKeyring(clusterInfo *client.ClusterInfo } keyring := fmt.Sprintf(keyringTemplate, daemonConfig.DaemonID, key) - return keyring, s.CreateOrUpdate(daemonConfig.ResourceName, keyring) + return s.CreateOrUpdate(daemonConfig.ResourceName, keyring) } func fullDaemonName(daemonID string) string { diff --git a/pkg/operator/ceph/config/keyring/admin.go b/pkg/operator/ceph/config/keyring/admin.go index d202d5dfd..571f6827c 100644 --- a/pkg/operator/ceph/config/keyring/admin.go +++ b/pkg/operator/ceph/config/keyring/admin.go @@ -55,7 +55,7 @@ func (s *SecretStore) Admin() *AdminStore { // CreateOrUpdate creates or updates the admin keyring secret with cluster information. func (a *AdminStore) CreateOrUpdate(c *cephclient.ClusterInfo, context *clusterd.Context, annotation v1.AnnotationsSpec) error { keyring := fmt.Sprintf(adminKeyringTemplate, c.CephCred.Secret) - err := a.secretStore.CreateOrUpdate(adminKeyringResourceName, keyring) + _, err := a.secretStore.CreateOrUpdate(adminKeyringResourceName, keyring) if err != nil { return err } diff --git a/pkg/operator/ceph/config/keyring/cephx.go b/pkg/operator/ceph/config/keyring/cephx.go new file mode 100644 index 000000000..f78fba504 --- /dev/null +++ b/pkg/operator/ceph/config/keyring/cephx.go @@ -0,0 +1,186 @@ +/* +Copyright 2025 The Rook Authors. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package keyring + +import ( + "fmt" + "strconv" + "strings" + + "github.com/pkg/errors" + v1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1" + "github.com/rook/rook/pkg/operator/ceph/version" +) + +var CephAuthRotateSupportedVersion = version.CephVersion{Major: 20, Minor: 2, Extra: 0} + +// CephxKeyIdentifierAnnotation is the annotation that should be applied to pod specs to +// ensure that pods restart after keys are rotated (and not restarted when keys are not rotated). +// The keyring secret resourceVersion is suggested but not always available. +// +//nolint:gosec // G101: this is not hardcoded credentials +const CephxKeyIdentifierAnnotation = "cephx-key-identifier" + +// ShouldRotateCephxKeys determines whether CephX keys should be rotated based on the CephX key +// rotation config, the version of Ceph present in the image being deployed (desiredCephVersion), +// and the last-reconciled CephX key status. +// runningCephVersion is used to determine if the cluster is capable of rotating CephX keys. +// Intended to use running/desired ceph version from CurrentAndDesiredCephVersion(). +func ShouldRotateCephxKeys(cfg v1.CephxConfig, runningCephVersion, desiredCephVersion version.CephVersion, status v1.CephxStatus) (bool, error) { + if !runningCephVersion.IsAtLeast(CephAuthRotateSupportedVersion) { + logger.Debugf("should not rotate cephx keys using unsupported ceph version %#v", runningCephVersion) + return false, nil + } + + if status.KeyCephVersion == v1.UninitializedCephxKeyCephVersion { + return false, nil // no need to rotate key when key isn't yet initialized + } + + switch cfg.KeyRotationPolicy { + case v1.CephxKeyRotationPolicy(""), v1.DisabledCephxKeyRotationPolicy: + return false, nil + case v1.KeyGenerationCephxKeyRotationPolicy: + return cfg.KeyGeneration > status.KeyGeneration, nil + case "WithCephVersionUpdate": // TODO: use types.go value when allowed by user input + // basic functionality for this policy is implemented here, but this is disabled as a user + // selectable option. code and tests are retained for when we can validate this more deeply + + if version.IsIdentical(desiredCephVersion, version.CephVersion{}) { + // likely cause of this is developer error. if that makes it to release, it's probably + // best to not cause unrecoverable error for users + logger.Info("ShouldRotateCephxKeys(): desiredCephVersion is unspecified") + return false, nil + } + + if status.KeyCephVersion == "" { + return true, nil // when previous version is unknown, assume rotation + } + + statusVer, err := parseCephVersionFromStatusVersion(status.KeyCephVersion) + if err != nil { + return false, errors.Wrapf(err, "failed to determine if cephx keys need to be rotated under %q rotation policy; failed to parse key ceph version from status %q", cfg.KeyRotationPolicy, status.KeyCephVersion) + } + // by API spec, commit ID is not part of CephCluster.status.version.version or + // keyCephVersion, so strip it from version found in ceph image + desiredCephVersion.CommitID = "" + if version.IsSuperior(desiredCephVersion, statusVer) { + return true, nil + } + return false, nil + default: + return false, errors.Errorf("unknown cephx key rotation policy %q", cfg.KeyRotationPolicy) + } +} + +// CephVersionToCephxStatusVersion renders a CephVersion struct into status.KeyCephVersion format. +// This is expected to be the same format used by CephCluster.status.version.version. +func CephVersionToCephxStatusVersion(v version.CephVersion) string { + return fmt.Sprintf("%d.%d.%d-%d", // DO NOT CHANGE FORMAT FROM "Maj.Min.Ext-Bld" + v.Major, v.Minor, v.Extra, v.Build) +} + +func parseCephVersionFromStatusVersion(inVer string) (version.CephVersion, error) { + cephVer := version.CephVersion{} + var err error + + semvBuild := strings.Split(inVer, "-") + if len(semvBuild) != 2 { + return version.CephVersion{}, errors.Errorf("failed to parse %q (expected format \"X.Y.Z-B\") into a ceph version at build split", inVer) + } + semv := semvBuild[0] + build := semvBuild[1] + + cephVer.Build, err = strconv.Atoi(build) + if err != nil { + return version.CephVersion{}, errors.Wrapf(err, "failed to parse build version from %q", inVer) + } + + mme := strings.Split(semv, ".") + if len(mme) != 3 { + return version.CephVersion{}, errors.Errorf("failed to parse %q (expected format \"X.Y.Z-B\") into a ceph version at Major-Minor-Extra split", inVer) + } + + cephVer.Major, err = strconv.Atoi(mme[0]) + if err != nil { + return version.CephVersion{}, errors.Wrapf(err, "failed to parse major version from %q", inVer) + } + + cephVer.Minor, err = strconv.Atoi(mme[1]) + if err != nil { + return version.CephVersion{}, errors.Wrapf(err, "failed to parse minor version from %q", inVer) + } + + cephVer.Extra, err = strconv.Atoi(mme[2]) + if err != nil { + return version.CephVersion{}, errors.Wrapf(err, "failed to parse extra version from %q", inVer) + } + + return cephVer, nil +} + +// UninitializedCephxStatus provides the initial status that indicates CephX keys haven't been +// initialized. This should be applied when a resource status is first set to a non-nil status. +// Together with UpdatedCephxStatus() below, this helps ensure that Rook only applies key generation +// and ceph version info to the status when a resource is first being provisioned. +// Resources that were provisioned before CephX key rotation and version tracking were implemented +// will be identified by KeyCephVersion="", the empty string. +func UninitializedCephxStatus() v1.CephxStatus { + return v1.CephxStatus{ + KeyGeneration: 0, + KeyCephVersion: v1.UninitializedCephxKeyCephVersion, + } +} + +// UpdatedCephxStatus returns the updated CephxStatus based on rotation config and status from +// before rotation occurred. +func UpdatedCephxStatus(didRotate bool, cfg v1.CephxConfig, runningCephVersion version.CephVersion, status v1.CephxStatus) v1.CephxStatus { + newStatus := status.DeepCopy() + + // uninitialized key ceph version indicates that the key was newly been created + // this is true regardless of whether the key was rotated or not + if status.KeyCephVersion == v1.UninitializedCephxKeyCephVersion { + newStatus.KeyCephVersion = CephVersionToCephxStatusVersion(runningCephVersion) + newStatus.KeyGeneration = 1 + + // corner case: user sets KeyGeneration policy with KeyGeneration > 1 to the spec of a CR + // that is being newly provisioned. in this case, rotation isn't relevant, but Rook should + // make sure status doesn't report that rotation is in progress when it isn't + if cfg.KeyRotationPolicy == v1.KeyGenerationCephxKeyRotationPolicy && cfg.KeyGeneration > 1 { + newStatus.KeyGeneration = cfg.KeyGeneration + } + + return *newStatus + } + + if !didRotate { + // preserve previous status when keys not rotated. importantly, retains KeyCephVersion + // status as an empty string in brownfield resources where the version is unknown + return status + } + + newStatus.KeyCephVersion = CephVersionToCephxStatusVersion(runningCephVersion) + newStatus.KeyGeneration++ + + if cfg.KeyRotationPolicy == v1.KeyGenerationCephxKeyRotationPolicy { + if cfg.KeyGeneration > newStatus.KeyGeneration { + // do not allow the status key gen to be reduced, no matter what input config says + newStatus.KeyGeneration = cfg.KeyGeneration + } + } + + return *newStatus +} diff --git a/pkg/operator/ceph/config/keyring/cephx_test.go b/pkg/operator/ceph/config/keyring/cephx_test.go new file mode 100644 index 000000000..3ffa85913 --- /dev/null +++ b/pkg/operator/ceph/config/keyring/cephx_test.go @@ -0,0 +1,185 @@ +/* +Copyright 2025 The Rook Authors. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package keyring + +import ( + "reflect" + "testing" + + v1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1" + "github.com/rook/rook/pkg/operator/ceph/version" + "github.com/stretchr/testify/assert" +) + +func TestShouldRotateCephxKeys(t *testing.T) { + // commit IDs will ensure they are being ignored as part of comparison to keyCephVersion status + v20_2_0 := version.CephVersion{Major: 20, Minor: 2, Extra: 0, CommitID: "ababababababa"} + v20_2_2 := version.CephVersion{Major: 20, Minor: 2, Extra: 2, CommitID: "ababababababa"} + + tests := []struct { + name string + cfg v1.CephxConfig + imageCephVersion version.CephVersion + status v1.CephxStatus + want bool + wantErr bool + }{ + {"policy unset", v1.CephxConfig{KeyRotationPolicy: "", KeyGeneration: 5}, version.CephVersion{}, v1.CephxStatus{KeyGeneration: 0, KeyCephVersion: "20.2.0-0"}, false, false}, + {"policy disabled", v1.CephxConfig{KeyRotationPolicy: "Disabled", KeyGeneration: 5}, v20_2_2, v1.CephxStatus{KeyGeneration: 6, KeyCephVersion: "20.2.0-0"}, false, false}, + {"policy disabled", v1.CephxConfig{KeyRotationPolicy: "Disabled", KeyGeneration: 5}, v20_2_2, v1.CephxStatus{KeyGeneration: 6, KeyCephVersion: "20.2.0-0"}, false, false}, + // + {"policy generation, 3<4", v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 3}, version.CephVersion{}, v1.CephxStatus{KeyGeneration: 4, KeyCephVersion: "20.2.0-0"}, false, false}, + {"policy generation, 5>4", v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 5}, v20_2_0, v1.CephxStatus{KeyGeneration: 4, KeyCephVersion: "20.2.2-0"}, true, false}, + {"policy generation, 4=4", v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 4}, v20_2_2, v1.CephxStatus{KeyGeneration: 4, KeyCephVersion: "20.2.0-0"}, false, false}, + {"policy generation, 5>0", v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 5}, v20_2_0, v1.CephxStatus{KeyGeneration: 0, KeyCephVersion: "20.2.2-0"}, true, false}, + {"policy generation, 0=0", v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 0}, v20_2_2, v1.CephxStatus{KeyGeneration: 0, KeyCephVersion: "20.2.0-0"}, false, false}, + {"policy generation, 1>0, uninit", v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 0}, v20_2_2, v1.CephxStatus{KeyGeneration: 0, KeyCephVersion: "Uninitialized"}, false, false}, + {"policy generation, 2>0, uninit", v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 0}, v20_2_2, v1.CephxStatus{KeyGeneration: 0, KeyCephVersion: "Uninitialized"}, false, false}, + // + // in unlikely event ceph version in image is unknown, do nothing, even if existing key version is unknown + {"policy ceph update, unk vs unk", v1.CephxConfig{KeyRotationPolicy: "WithCephVersionUpdate", KeyGeneration: 0}, version.CephVersion{}, v1.CephxStatus{KeyGeneration: 4, KeyCephVersion: ""}, false, false}, + {"policy ceph update, unk vs uninit", v1.CephxConfig{KeyRotationPolicy: "WithCephVersionUpdate", KeyGeneration: 0}, version.CephVersion{}, v1.CephxStatus{KeyGeneration: 4, KeyCephVersion: "Uninitialized"}, false, false}, + {"policy ceph update, 20.2.0 vs unk", v1.CephxConfig{KeyRotationPolicy: "WithCephVersionUpdate", KeyGeneration: 0}, v20_2_0, v1.CephxStatus{KeyGeneration: 4, KeyCephVersion: ""}, true, false}, + {"policy ceph update, 20.2.2 vs unk", v1.CephxConfig{KeyRotationPolicy: "WithCephVersionUpdate", KeyGeneration: 0}, v20_2_2, v1.CephxStatus{KeyGeneration: 4, KeyCephVersion: ""}, true, false}, + {"policy ceph update, 20.2.0 vs uninit", v1.CephxConfig{KeyRotationPolicy: "WithCephVersionUpdate", KeyGeneration: 0}, v20_2_0, v1.CephxStatus{KeyGeneration: 4, KeyCephVersion: "Uninitialized"}, false, false}, + {"policy ceph update, unk vs 20.20.0", v1.CephxConfig{KeyRotationPolicy: "WithCephVersionUpdate", KeyGeneration: 0}, version.CephVersion{}, v1.CephxStatus{KeyGeneration: 4, KeyCephVersion: "20.2.0-0"}, false, false}, + {"policy ceph update, 20.2.2 vs 20.2.0", v1.CephxConfig{KeyRotationPolicy: "WithCephVersionUpdate", KeyGeneration: 0}, v20_2_2, v1.CephxStatus{KeyGeneration: 4, KeyCephVersion: "20.2.0-0"}, true, false}, + {"policy ceph update, 20.2.0 vs 20.2.2", v1.CephxConfig{KeyRotationPolicy: "WithCephVersionUpdate", KeyGeneration: 0}, v20_2_0, v1.CephxStatus{KeyGeneration: 4, KeyCephVersion: "20.2.2-0"}, false, false}, + {"policy ceph update, 20.2.2 vs 20.2.2", v1.CephxConfig{KeyRotationPolicy: "WithCephVersionUpdate", KeyGeneration: 0}, v20_2_2, v1.CephxStatus{KeyGeneration: 4, KeyCephVersion: "20.2.2-0"}, false, false}, + // + {"invalid policy", v1.CephxConfig{KeyRotationPolicy: "InVaLiD", KeyGeneration: 0}, v20_2_2, v1.CephxStatus{KeyGeneration: 4, KeyCephVersion: "20.2.0-0"}, false, true}, + } + t.Run("can support", func(t *testing.T) { + for _, tt := range tests { + // run all tests for case where ceph version does support rotation + t.Run(tt.name, func(t *testing.T) { + got, err := ShouldRotateCephxKeys(tt.cfg, v20_2_2, tt.imageCephVersion, tt.status) + if (err != nil) != tt.wantErr { + t.Errorf("ShouldRotateCephxKeys() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("ShouldRotateCephxKeys() = %v, want %v", got, tt.want) + } + }) + } + }) + + t.Run("cannot support", func(t *testing.T) { + for _, tt := range tests { + // and run all tests for case where ceph version does not support rotation + t.Run(tt.name, func(t *testing.T) { + got, err := ShouldRotateCephxKeys(tt.cfg, version.CephVersion{Major: 19, Minor: 2, Extra: 4}, tt.imageCephVersion, tt.status) + assert.NoError(t, err) + assert.False(t, got) + }) + } + }) +} + +func Test_parseCephVersionFromStatusVersion(t *testing.T) { + cephVer := version.CephVersion{Major: 21, Minor: 3, Extra: 0, Build: 664, CommitID: "abababababbababababa"} + cephVerNoCommitID := cephVer + cephVerNoCommitID.CommitID = "" + + tests := []struct { + ver string + want version.CephVersion + wantErr bool + }{ + {"20.2.1-5", version.CephVersion{Major: 20, Minor: 2, Extra: 1, Build: 5}, false}, + {"v20.2.1-5", version.CephVersion{}, true}, + {"20.2.1", version.CephVersion{}, true}, + {"20.2", version.CephVersion{}, true}, + {"20", version.CephVersion{}, true}, + {"20.2-5", version.CephVersion{}, true}, + + // test round trip CephVersionToCephxStatusVersion() with comparison here + {CephVersionToCephxStatusVersion(cephVer), cephVerNoCommitID, false}, + } + for _, tt := range tests { + t.Run(tt.ver, func(t *testing.T) { + got, err := parseCephVersionFromStatusVersion(tt.ver) + if (err != nil) != tt.wantErr { + t.Errorf("parseCephVersionFromStatusVersion() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("parseCephVersionFromStatusVersion() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestUpdatedCephxStatus(t *testing.T) { + cephVer := version.CephVersion{Major: 20, Minor: 2, Extra: 0} + verStr := "20.2.0-0" + + tests := []struct { + name string + didRotate bool + cfg v1.CephxConfig + runningCephVersion version.CephVersion + status v1.CephxStatus + want v1.CephxStatus + }{ + // brownfield: unset remains unset when no rotation + {"norotate, nopolicy - unset -> unset", false, v1.CephxConfig{KeyRotationPolicy: ""}, cephVer, v1.CephxStatus{}, v1.CephxStatus{}}, + {"norotate, disabled - unset -> unset", false, v1.CephxConfig{KeyRotationPolicy: "Disabled"}, cephVer, v1.CephxStatus{}, v1.CephxStatus{}}, + {"norotate, keygen - unset -> unset", false, v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 2}, cephVer, v1.CephxStatus{}, v1.CephxStatus{}}, + {"norotate, cephver - unset -> unset", false, v1.CephxConfig{KeyRotationPolicy: "WithCephVersionUpdate"}, cephVer, v1.CephxStatus{}, v1.CephxStatus{}}, + + // brownfield: unset gets set when rotation happened + {"rotate, nopolicy - unset -> set", true, v1.CephxConfig{KeyRotationPolicy: ""}, cephVer, v1.CephxStatus{}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}}, + {"rotate, disabled - unset -> set", true, v1.CephxConfig{KeyRotationPolicy: "Disabled"}, cephVer, v1.CephxStatus{}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}}, + {"rotate, keygen 0 - unset -> set", true, v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 0}, cephVer, v1.CephxStatus{}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}}, + {"rotate, keygen 1 - unset -> set", true, v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 1}, cephVer, v1.CephxStatus{}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}}, + {"rotate, keygen 3 - unset -> set", true, v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 3}, cephVer, v1.CephxStatus{}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 3}}, + {"rotate, cephver - unset -> set", true, v1.CephxConfig{KeyRotationPolicy: "WithCephVersionUpdate"}, cephVer, v1.CephxStatus{}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}}, + + // greenfield: uninit gets initialized + {"greenfield, nopolicy", false, v1.CephxConfig{KeyRotationPolicy: ""}, cephVer, v1.CephxStatus{KeyCephVersion: "Uninitialized"}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}}, + {"greenfield, disabled", false, v1.CephxConfig{KeyRotationPolicy: "Disabled"}, cephVer, v1.CephxStatus{KeyCephVersion: "Uninitialized"}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}}, + {"greenfield, keygen 0", false, v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 0}, cephVer, v1.CephxStatus{KeyCephVersion: "Uninitialized"}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}}, + {"greenfield, keygen 1", false, v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 1}, cephVer, v1.CephxStatus{KeyCephVersion: "Uninitialized"}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}}, + {"greenfield, keygen 3", false, v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 3}, cephVer, v1.CephxStatus{KeyCephVersion: "Uninitialized"}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 3}}, + {"greenfield, cephver", false, v1.CephxConfig{KeyRotationPolicy: "WithCephVersionUpdate"}, cephVer, v1.CephxStatus{KeyCephVersion: "Uninitialized"}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}}, + + // norotate: status retained + {"norotate, nopolicy - retain status", false, v1.CephxConfig{KeyRotationPolicy: ""}, cephVer, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}}, + {"norotate, disabled - retain status", false, v1.CephxConfig{KeyRotationPolicy: "Disabled"}, cephVer, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}}, + {"norotate, keygen 0 - retain status", false, v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 0}, cephVer, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}}, + {"norotate, keygen 1 - retain status", false, v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 1}, cephVer, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}}, + {"norotate, keygen 3 - retain status", false, v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 3}, cephVer, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}}, + {"norotate, cephver - retain status", false, v1.CephxConfig{KeyRotationPolicy: "WithCephVersionUpdate"}, cephVer, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}}, + + // rotate: status updated + {"rotate, nopolicy - status 1 -> 2", true, v1.CephxConfig{KeyRotationPolicy: ""}, cephVer, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 2}}, + {"rotate, disabled - status 1 -> 2", true, v1.CephxConfig{KeyRotationPolicy: "Disabled"}, cephVer, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 2}}, + {"rotate, keygen 0 - status 1 -> 2", true, v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 0}, cephVer, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 2}}, + {"rotate, keygen 1 - status 1 -> 2", true, v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 1}, cephVer, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 2}}, + {"rotate, keygen 3 - status 1 -> 3", true, v1.CephxConfig{KeyRotationPolicy: "KeyGeneration", KeyGeneration: 3}, cephVer, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 1}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 3}}, + {"rotate, cephver - status 1 -> 2", true, v1.CephxConfig{KeyRotationPolicy: "WithCephVersionUpdate"}, cephVer, v1.CephxStatus{KeyCephVersion: "20.3.0-0", KeyGeneration: 1}, v1.CephxStatus{KeyCephVersion: verStr, KeyGeneration: 2}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := UpdatedCephxStatus(tt.didRotate, tt.cfg, tt.runningCephVersion, tt.status); !reflect.DeepEqual(got, tt.want) { + t.Errorf("UpdatedCephxStatus() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/pkg/operator/ceph/config/keyring/store.go b/pkg/operator/ceph/config/keyring/store.go index a8d39ee09..8691019bb 100644 --- a/pkg/operator/ceph/config/keyring/store.go +++ b/pkg/operator/ceph/config/keyring/store.go @@ -34,6 +34,9 @@ var logger = capnslog.NewPackageLogger("github.com/rook/rook", "op-cfg-keyring") const ( keyringFileName = "keyring" + + // KeyringAnnotation identifies a Kubernetes Secret as a cephx keyring file + KeyringAnnotation = "cephx-keyring" ) // SecretStore is a helper to store Ceph daemon keyrings as Kubernetes secrets. @@ -77,13 +80,26 @@ func (k *SecretStore) GenerateKey(user string, access []string) (string, error) return key, nil } +// RotateKey rotates a key for a Ceph user without modifying permissions. It returns the new key on success. +func (k *SecretStore) RotateKey(user string) (string, error) { + key, err := client.AuthRotate(k.context, k.clusterInfo, user) + if err != nil { + return "", errors.Wrapf(err, "failed to rotate key for %q", user) + } + return key, nil +} + // CreateOrUpdate creates or updates the keyring secret for the resource with the keyring specified. +// Returns the secret resource version. // WARNING: Do not use "rook-ceph-admin" as the resource name; conflicts with the AdminStore. -func (k *SecretStore) CreateOrUpdate(resourceName string, keyring string) error { +func (k *SecretStore) CreateOrUpdate(resourceName string, keyring string) (string, error) { secret := &v1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: keyringSecretName(resourceName), Namespace: k.clusterInfo.Namespace, + Annotations: map[string]string{ + KeyringAnnotation: "", + }, }, StringData: map[string]string{ keyringFileName: keyring, @@ -92,7 +108,7 @@ func (k *SecretStore) CreateOrUpdate(resourceName string, keyring string) error } err := k.ownerInfo.SetControllerReference(secret) if err != nil { - return errors.Wrapf(err, "failed to set owner reference to keyring secret %q", secret.Name) + return "", errors.Wrapf(err, "failed to set owner reference to keyring secret %q", secret.Name) } return k.CreateSecret(secret) @@ -109,24 +125,27 @@ func (k *SecretStore) Delete(resourceName string) error { return nil } -// CreateSecret creates or update a kubernetes secret -func (k *SecretStore) CreateSecret(secret *v1.Secret) error { +// CreateSecret creates or update a kubernetes secret. +// Returns the resource version of the secret. +func (k *SecretStore) CreateSecret(secret *v1.Secret) (string, error) { secretName := secret.ObjectMeta.Name _, err := k.context.Clientset.CoreV1().Secrets(k.clusterInfo.Namespace).Get(k.clusterInfo.Context, secretName, metav1.GetOptions{}) if err != nil { if kerrors.IsNotFound(err) { logger.Debugf("creating secret for %s", secretName) - if _, err := k.context.Clientset.CoreV1().Secrets(k.clusterInfo.Namespace).Create(k.clusterInfo.Context, secret, metav1.CreateOptions{}); err != nil { - return errors.Wrapf(err, "failed to create secret for %s", secretName) + s, err := k.context.Clientset.CoreV1().Secrets(k.clusterInfo.Namespace).Create(k.clusterInfo.Context, secret, metav1.CreateOptions{}) + if err != nil { + return "", errors.Wrapf(err, "failed to create secret for %s", secretName) } - return nil + return s.ResourceVersion, nil } - return errors.Wrapf(err, "failed to get secret for %s", secretName) + return "", errors.Wrapf(err, "failed to get secret for %s", secretName) } logger.Debugf("updating secret for %s", secretName) - if _, err := k.context.Clientset.CoreV1().Secrets(k.clusterInfo.Namespace).Update(k.clusterInfo.Context, secret, metav1.UpdateOptions{}); err != nil { - return errors.Wrapf(err, "failed to update secret for %s", secretName) + s, err := k.context.Clientset.CoreV1().Secrets(k.clusterInfo.Namespace).Update(k.clusterInfo.Context, secret, metav1.UpdateOptions{}) + if err != nil { + return "", errors.Wrapf(err, "failed to update secret for %s", secretName) } - return nil + return s.ResourceVersion, nil } diff --git a/pkg/operator/ceph/config/keyring/store_test.go b/pkg/operator/ceph/config/keyring/store_test.go index bdb014199..6c3f604e1 100644 --- a/pkg/operator/ceph/config/keyring/store_test.go +++ b/pkg/operator/ceph/config/keyring/store_test.go @@ -95,18 +95,18 @@ func TestKeyringStore(t *testing.T) { } // create first key - err := k.CreateOrUpdate("test-resource", "qwertyuiop") + _, err := k.CreateOrUpdate("test-resource", "qwertyuiop") assert.NoError(t, err) assertKeyringData("test-resource-keyring", "qwertyuiop") // create second key - err = k.CreateOrUpdate("second-resource", "asdfghjkl") + _, err = k.CreateOrUpdate("second-resource", "asdfghjkl") assert.NoError(t, err) assertKeyringData("test-resource-keyring", "qwertyuiop") assertKeyringData("second-resource-keyring", "asdfghjkl") // update a key - err = k.CreateOrUpdate("second-resource", "lkjhgfdsa") + _, err = k.CreateOrUpdate("second-resource", "lkjhgfdsa") assert.NoError(t, err) assertKeyringData("test-resource-keyring", "qwertyuiop") assertKeyringData("second-resource-keyring", "lkjhgfdsa") @@ -125,9 +125,9 @@ func TestResourceVolumeAndMount(t *testing.T) { } ownerInfo := cephclient.NewMinimumOwnerInfoWithOwnerRef() k := GetSecretStore(ctx, &cephclient.ClusterInfo{Namespace: "ns"}, ownerInfo) - err := k.CreateOrUpdate("test-resource", "qwertyuiop") + _, err := k.CreateOrUpdate("test-resource", "qwertyuiop") assert.NoError(t, err) - err = k.CreateOrUpdate("second-resource", "asdfgyhujkl") + _, err = k.CreateOrUpdate("second-resource", "asdfgyhujkl") assert.NoError(t, err) v := Volume().Resource("test-resource") diff --git a/pkg/operator/ceph/controller/label.go b/pkg/operator/ceph/controller/label.go index 360a4b511..cfe07ece2 100644 --- a/pkg/operator/ceph/controller/label.go +++ b/pkg/operator/ceph/controller/label.go @@ -43,7 +43,7 @@ func addCephVersionLabel(cephVersion version.CephVersion, labels map[string]stri // GetCephVersionLabel returns a formatted serialization of a provided CephVersion for use in resource labels. func GetCephVersionLabel(cephVersion version.CephVersion) string { - return fmt.Sprintf("%d.%d.%d-%d", + return fmt.Sprintf("%d.%d.%d-%d", // DO NOT CHANGE FORMAT FROM "Maj.Min.Ext-Bld" cephVersion.Major, cephVersion.Minor, cephVersion.Extra, cephVersion.Build) } diff --git a/pkg/operator/ceph/controller/predicate.go b/pkg/operator/ceph/controller/predicate.go index 25971fc40..3e25d3d0e 100644 --- a/pkg/operator/ceph/controller/predicate.go +++ b/pkg/operator/ceph/controller/predicate.go @@ -29,6 +29,7 @@ import ( "github.com/pkg/errors" cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1" "github.com/rook/rook/pkg/operator/ceph/config" + "github.com/rook/rook/pkg/operator/ceph/config/keyring" "github.com/rook/rook/pkg/operator/k8sutil" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" @@ -150,9 +151,16 @@ func objectChanged(oldObj, newObj runtime.Object, objectName string) (bool, erro // Do not leak details of diff if the object contains sensitive data (e.g., it is a Secret) isSensitive := false - if _, ok := new.(*corev1.Secret); ok { + if s, ok := new.(*corev1.Secret); ok { logger.Debugf("object %q diff is [redacted for Secrets]", objectName) isSensitive = true + + // keyring secrets are a special case. rook updates these during reconciliation as needed, + // and daemon pods automatically get updated keys with no need for another reconcile + if _, ok := s.ObjectMeta.Annotations[keyring.KeyringAnnotation]; ok { + logger.Debugf("not reconciling update to cephx keyring secret %q", objectName) + return false, nil + } } else { logger.Debugf("object %q diff is %s", objectName, diff.String()) isSensitive = false diff --git a/pkg/operator/ceph/csi/secrets.go b/pkg/operator/ceph/csi/secrets.go index 86739101f..1f534dc4e 100644 --- a/pkg/operator/ceph/csi/secrets.go +++ b/pkg/operator/ceph/csi/secrets.go @@ -159,7 +159,7 @@ func createOrUpdateCSISecret(clusterInfo *client.ClusterInfo, csiRBDProvisionerS } // Create Kubernetes Secret - err = k.CreateSecret(s) + _, err = k.CreateSecret(s) if err != nil { return errors.Wrapf(err, "failed to create kubernetes secret %q for cluster %q", s.Name, clusterInfo.Namespace) } diff --git a/pkg/operator/ceph/file/mds/config.go b/pkg/operator/ceph/file/mds/config.go index 5511f2658..49e94e334 100644 --- a/pkg/operator/ceph/file/mds/config.go +++ b/pkg/operator/ceph/file/mds/config.go @@ -60,7 +60,7 @@ func (c *Cluster) generateKeyring(m *mdsConfig) (string, error) { } keyring := fmt.Sprintf(keyringTemplate, m.DaemonID, key) - return keyring, s.CreateOrUpdate(m.ResourceName, keyring) + return s.CreateOrUpdate(m.ResourceName, keyring) } func (c *Cluster) setDefaultFlagsMonConfigStore(mdsID string) error { diff --git a/pkg/operator/ceph/file/mirror/config.go b/pkg/operator/ceph/file/mirror/config.go index 77817a04c..ff708096b 100644 --- a/pkg/operator/ceph/file/mirror/config.go +++ b/pkg/operator/ceph/file/mirror/config.go @@ -59,5 +59,5 @@ func (r *ReconcileFilesystemMirror) generateKeyring(daemonConfig *daemonConfig) } keyring := fmt.Sprintf(keyringTemplate, key) - return keyring, s.CreateOrUpdate(daemonConfig.ResourceName, keyring) + return s.CreateOrUpdate(daemonConfig.ResourceName, keyring) } diff --git a/pkg/operator/ceph/nfs/config.go b/pkg/operator/ceph/nfs/config.go index a252b63b7..55986bcfe 100644 --- a/pkg/operator/ceph/nfs/config.go +++ b/pkg/operator/ceph/nfs/config.go @@ -89,7 +89,8 @@ func (r *ReconcileCephNFS) generateKeyring(n *cephv1.CephNFS, name string) error } keyring := fmt.Sprintf(keyringTemplate, user, key, osdCaps) - return s.CreateOrUpdate(instanceName(n, name), keyring) + _, err = s.CreateOrUpdate(instanceName(n, name), keyring) + return err } func getGaneshaConfig(n *cephv1.CephNFS, version cephver.CephVersion, name string) string { diff --git a/pkg/operator/ceph/object/config.go b/pkg/operator/ceph/object/config.go index 2e83f5ed0..7538e01cb 100644 --- a/pkg/operator/ceph/object/config.go +++ b/pkg/operator/ceph/object/config.go @@ -105,8 +105,18 @@ func (c *clusterConfig) generateKeyring(rgwConfig *rgwConfig) (string, error) { return "", err } + if c.shouldRotateCephxKeys { + logger.Infof("rotating cephx key for CephObjectStore %q", c.store.Name) + newKey, err := s.RotateKey(user) + if err != nil { + logger.Infof("failed to rotate cephx key for CephObjectStore %q; continuing without key rotation %v", c.store.Name, err) + } else { + key = newKey + } + } + keyring := fmt.Sprintf(keyringTemplate, user, key) - return keyring, s.CreateOrUpdate(rgwConfig.ResourceName, keyring) + return s.CreateOrUpdate(rgwConfig.ResourceName, keyring) } func mapKeystoneSecretToConfig(cfg map[string]string, secret *v1.Secret) (map[string]string, error) { diff --git a/pkg/operator/ceph/object/controller.go b/pkg/operator/ceph/object/controller.go index e81899926..cdfe5968a 100644 --- a/pkg/operator/ceph/object/controller.go +++ b/pkg/operator/ceph/object/controller.go @@ -31,6 +31,7 @@ import ( "github.com/rook/rook/pkg/clusterd" cephclient "github.com/rook/rook/pkg/daemon/ceph/client" "github.com/rook/rook/pkg/operator/ceph/config" + "github.com/rook/rook/pkg/operator/ceph/config/keyring" opcontroller "github.com/rook/rook/pkg/operator/ceph/controller" "github.com/rook/rook/pkg/operator/ceph/reporting" "github.com/rook/rook/pkg/operator/k8sutil" @@ -305,9 +306,16 @@ func (r *ReconcileCephObjectStore) reconcile(request reconcile.Request) (reconci // The CR was just created, initializing status fields if cephObjectStore.Status == nil { // The store is not available so let's not build the status Info yet - updateStatus(r.opManagerContext, k8sutil.ObservedGenerationNotAvailable, r.client, request.NamespacedName, cephv1.ConditionProgressing, map[string]string{}) + cephxUninitialized := keyring.UninitializedCephxStatus() + updateStatus(r.opManagerContext, k8sutil.ObservedGenerationNotAvailable, r.client, request.NamespacedName, cephv1.ConditionProgressing, map[string]string{}, &cephxUninitialized) + cephObjectStore.Status = &cephv1.ObjectStoreStatus{ + Cephx: cephv1.LocalCephxStatus{ + Daemon: cephxUninitialized, + }, + } } else { - updateStatus(r.opManagerContext, k8sutil.ObservedGenerationNotAvailable, r.client, request.NamespacedName, cephv1.ConditionProgressing, buildStatusInfo(cephObjectStore)) + var nilCephxStatus *cephv1.CephxStatus = nil // leave cephx status as-is + updateStatus(r.opManagerContext, k8sutil.ObservedGenerationNotAvailable, r.client, request.NamespacedName, cephv1.ConditionProgressing, buildStatusInfo(cephObjectStore), nilCephxStatus) } // Make sure a CephCluster is present otherwise do nothing @@ -342,7 +350,7 @@ func (r *ReconcileCephObjectStore) reconcile(request reconcile.Request) (reconci // DELETE: the CR was deleted if !cephObjectStore.GetDeletionTimestamp().IsZero() { - updateStatus(r.opManagerContext, k8sutil.ObservedGenerationNotAvailable, r.client, request.NamespacedName, cephv1.ConditionDeleting, buildStatusInfo(cephObjectStore)) + updateStatus(r.opManagerContext, k8sutil.ObservedGenerationNotAvailable, r.client, request.NamespacedName, cephv1.ConditionDeleting, buildStatusInfo(cephObjectStore), nil) // Detect running Ceph version runningCephVersion, err := cephclient.LeastUptodateDaemonVersion(r.context, r.clusterInfo, config.MonType) @@ -393,6 +401,7 @@ func (r *ReconcileCephObjectStore) reconcile(request reconcile.Request) (reconci return reconcile.Result{}, *cephObjectStore, nil } + shouldRotateCephxKeys := false if cephObjectStore.Spec.IsExternal() { // Check the ceph version of the running monitors desiredCephVersion, err := cephclient.LeastUptodateDaemonVersion(r.context, r.clusterInfo, config.MonType) @@ -430,7 +439,16 @@ func (r *ReconcileCephObjectStore) reconcile(request reconcile.Request) (reconci *cephObjectStore, opcontroller.ErrorCephUpgradingRequeue(desiredCephVersion, runningCephVersion) } - r.clusterInfo.CephVersion = *desiredCephVersion + r.clusterInfo.CephVersion = *runningCephVersion + + shouldRotateCephxKeys, err = keyring.ShouldRotateCephxKeys( + cephCluster.Spec.Security.CephX.Daemon, *runningCephVersion, *desiredCephVersion, cephObjectStore.Status.Cephx.Daemon) + if err != nil { + return reconcile.Result{}, *cephObjectStore, errors.Wrap(err, "failed to determine if cephx keys should be rotated") + } + if shouldRotateCephxKeys { + logger.Infof("cephx keys for CephObjectStore %q will be rotated", request.NamespacedName) + } } // validate the store settings @@ -438,8 +456,21 @@ func (r *ReconcileCephObjectStore) reconcile(request reconcile.Request) (reconci return reconcile.Result{}, *cephObjectStore, errors.Wrapf(err, "invalid object store %q arguments", cephObjectStore.Name) } + ownerInfo := k8sutil.NewOwnerInfo(cephObjectStore, r.scheme) + cfg := clusterConfig{ + context: r.context, + clusterInfo: r.clusterInfo, + store: cephObjectStore, + rookVersion: r.clusterSpec.CephVersion.Image, + clusterSpec: r.clusterSpec, + DataPathMap: config.NewStatelessDaemonDataPathMap(config.RgwType, cephObjectStore.Name, cephObjectStore.Namespace, r.clusterSpec.DataDirHostPath), + client: r.client, + ownerInfo: ownerInfo, + shouldRotateCephxKeys: shouldRotateCephxKeys, + } + // CREATE/UPDATE - _, err = r.reconcileCreateObjectStore(cephObjectStore, request.NamespacedName, cephCluster.Spec) + _, err = r.reconcileCreateObjectStore(cephObjectStore, request.NamespacedName, cfg) if err != nil && kerrors.IsNotFound(err) { // A not found error may mean ceph is still initializing, but there might be some other error // so we log the error and requeue @@ -452,25 +483,15 @@ func (r *ReconcileCephObjectStore) reconcile(request reconcile.Request) (reconci // update ObservedGeneration in status at the end of reconcile // Set Progressing status, we are done reconciling, the health check go routine will update the status - updateStatus(r.opManagerContext, observedGeneration, r.client, request.NamespacedName, cephv1.ConditionReady, buildStatusInfo(cephObjectStore)) + cephxStatus := keyring.UpdatedCephxStatus(shouldRotateCephxKeys, cephCluster.Spec.Security.CephX.Daemon, r.clusterInfo.CephVersion, cephObjectStore.Status.Cephx.Daemon) + updateStatus(r.opManagerContext, observedGeneration, r.client, request.NamespacedName, cephv1.ConditionReady, buildStatusInfo(cephObjectStore), &cephxStatus) // Return and do not requeue logger.Debug("done reconciling") return reconcile.Result{}, *cephObjectStore, nil } -func (r *ReconcileCephObjectStore) reconcileCreateObjectStore(cephObjectStore *cephv1.CephObjectStore, namespacedName types.NamespacedName, cluster cephv1.ClusterSpec) (reconcile.Result, error) { - ownerInfo := k8sutil.NewOwnerInfo(cephObjectStore, r.scheme) - cfg := clusterConfig{ - context: r.context, - clusterInfo: r.clusterInfo, - store: cephObjectStore, - rookVersion: r.clusterSpec.CephVersion.Image, - clusterSpec: r.clusterSpec, - DataPathMap: config.NewStatelessDaemonDataPathMap(config.RgwType, cephObjectStore.Name, cephObjectStore.Namespace, r.clusterSpec.DataDirHostPath), - client: r.client, - ownerInfo: ownerInfo, - } +func (r *ReconcileCephObjectStore) reconcileCreateObjectStore(cephObjectStore *cephv1.CephObjectStore, namespacedName types.NamespacedName, cfg clusterConfig) (reconcile.Result, error) { objContext, err := NewMultisiteContext(r.context, r.clusterInfo, cephObjectStore) if err != nil { return r.setFailedStatus(k8sutil.ObservedGenerationNotAvailable, namespacedName, "failed to setup object store context", err) diff --git a/pkg/operator/ceph/object/controller_test.go b/pkg/operator/ceph/object/controller_test.go index fe67e64c7..eb1f55a3f 100644 --- a/pkg/operator/ceph/object/controller_test.go +++ b/pkg/operator/ceph/object/controller_test.go @@ -31,6 +31,7 @@ import ( "github.com/rook/rook/pkg/client/clientset/versioned/scheme" "github.com/rook/rook/pkg/clusterd" "github.com/rook/rook/pkg/daemon/ceph/client" + "github.com/rook/rook/pkg/operator/ceph/config/keyring" cephver "github.com/rook/rook/pkg/operator/ceph/version" "github.com/rook/rook/pkg/operator/k8sutil" testopk8s "github.com/rook/rook/pkg/operator/k8sutil/test" @@ -144,7 +145,7 @@ const ( dummyVersionsRaw = ` { "mon": { - "ceph version 19.2.1 (0000000000000000) squid (stable)": 3 + "ceph version 20.2.0 (0000000000000000) tentacle (stable)": 3 } }` //nolint:gosec // only test values, not a real secret @@ -1143,3 +1144,353 @@ func Test_mapSecretToCR(t *testing.T) { assert.Empty(t, got, "empty: wrong secret ns") }) } + +func TestKeyRotation(t *testing.T) { + // test key rotation end-to-end + + ctx := context.TODO() + capnslog.SetGlobalLogLevel(capnslog.DEBUG) + os.Setenv("ROOK_LOG_LEVEL", "DEBUG") + var deploymentsUpdated *[]*apps.Deployment + updateDeploymentAndWait, deploymentsUpdated = testopk8s.UpdateDeploymentAndWaitStub() + testopk8s.ClearDeploymentsUpdated(deploymentsUpdated) + + zoneName := "zone-a" + zoneGroupName := "zonegroup-a" + realmName := "realm-a" + + metadataPool := cephv1.PoolSpec{} + dataPool := cephv1.PoolSpec{} + + cephCluster := &cephv1.CephCluster{ + ObjectMeta: metav1.ObjectMeta{ + Name: namespace, + Namespace: namespace, + }, + Status: cephv1.ClusterStatus{ + Phase: k8sutil.ReadyStatus, + CephStatus: &cephv1.CephStatus{ + Health: "HEALTH_OK", + }, + }, + } + + secrets := map[string][]byte{ + "fsid": []byte(name), + "mon-secret": []byte("monsecret"), + "admin-secret": []byte("adminsecret"), + } + secret := &v1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: "rook-ceph-mon", + Namespace: namespace, + }, + Data: secrets, + Type: k8sutil.RookType, + } + + objectZone := &cephv1.CephObjectZone{ + ObjectMeta: metav1.ObjectMeta{ + Name: zoneName, + Namespace: namespace, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "CephObjectZone", + }, + Spec: cephv1.ObjectZoneSpec{ + ZoneGroup: zoneGroupName, + MetadataPool: metadataPool, + DataPool: dataPool, + }, + } + + objectZoneGroup := &cephv1.CephObjectZoneGroup{ + ObjectMeta: metav1.ObjectMeta{ + Name: zoneGroupName, + Namespace: namespace, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "CephObjectZoneGroup", + }, + Spec: cephv1.ObjectZoneGroupSpec{}, + } + + objectZoneGroup.Spec.Realm = realmName + + objectRealm := &cephv1.CephObjectRealm{ + ObjectMeta: metav1.ObjectMeta{ + Name: realmName, + Namespace: namespace, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "CephObjectRealm", + }, + Spec: cephv1.ObjectRealmSpec{}, + } + + objectStore := &cephv1.CephObjectStore{ + ObjectMeta: metav1.ObjectMeta{ + Name: store, + Namespace: namespace, + Finalizers: []string{"cephobjectstore.ceph.rook.io"}, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "CephObjectStore", + }, + Spec: cephv1.ObjectStoreSpec{}, + } + + objectStore.Spec.Zone.Name = zoneName + objectStore.Spec.Gateway.Port = 80 + zoneGroupGetMultisiteJSON := zoneGroupGetMultisiteJSONWithoutEndpoint + object := []runtime.Object{ + objectZone, + objectStore, + objectZoneGroup, + objectRealm, + cephCluster, + } + + // auth rotate returns an array instead of a single object + rotatedKeyJson := `[{"key":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="}]` + + executor := &exectest.MockExecutor{ + MockExecuteCommandWithOutput: func(command string, args ...string) (string, error) { + if args[0] == "status" { + return `{"fsid":"c47cac40-9bee-4d52-823b-ccd803ba5bfe","health":{"checks":{},"status":"HEALTH_OK"},"pgmap":{"num_pgs":100,"pgs_by_state":[{"state_name":"active+clean","count":100}]}}`, nil + } + if args[0] == "auth" && args[1] == "get-or-create-key" { + return rgwCephAuthGetOrCreateKey, nil + } + if args[0] == "auth" && args[1] == "rotate" { + t.Logf("rotating key and returning: %s", rotatedKeyJson) + return rotatedKeyJson, nil + } + if args[0] == "osd" && args[1] == "pool" && args[2] == "get" { + return "", errors.New("test pool does not exit yet") + } + if args[0] == "versions" { + return dummyVersionsRaw, nil + } + return "", nil + }, + MockExecuteCommandWithTimeout: func(timeout time.Duration, command string, args ...string) (string, error) { + if args[0] == "realm" && args[1] == "list" { + return realmListMultisiteJSON, nil + } + if args[0] == "realm" && args[1] == "get" { + return realmGetMultisiteJSON, nil + } + if args[0] == "zonegroup" { + switch args[1] { + case "get": + return zoneGroupGetMultisiteJSON, nil + case "modify": + zoneGroupGetMultisiteJSON = zoneGroupGetMultisiteJSONWithEndpoint + return zoneGroupGetMultisiteJSON, nil + } + } + if args[0] == "zone" && args[1] == "get" { + return zoneGetMultisiteJSON, nil + } + if args[0] == "user" && args[1] == "create" { + return userCreateJSON, nil + } + return "", nil + }, + } + + commitConfigChangesOrig := commitConfigChanges + defer func() { commitConfigChanges = commitConfigChangesOrig }() + + // make sure joining multisite calls to commit config changes + calledCommitConfigChanges := false + commitConfigChanges = func(c *Context) error { + calledCommitConfigChanges = true + return nil + } + + clientset := test.New(t, 3) + c := &clusterd.Context{ + Executor: executor, + RookClientset: rookfake.NewSimpleClientset( + objectRealm, + objectZoneGroup, + objectZone, + objectStore, + ), + Clientset: clientset, + } + + // Register operator types with the runtime scheme. + s := scheme.Scheme + s.AddKnownTypes(cephv1.SchemeGroupVersion, &cephv1.CephObjectZone{}, &cephv1.CephObjectZoneList{}, &cephv1.CephCluster{}, &cephv1.CephClusterList{}, &cephv1.CephObjectStore{}, &cephv1.CephObjectStoreList{}) + + // Create a fake client to mock API calls. + cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(object...).Build() + + r := &ReconcileCephObjectStore{ + client: cl, + scheme: s, + context: c, + recorder: record.NewFakeRecorder(10), + opManagerContext: ctx, + } + + _, err := r.context.Clientset.CoreV1().Secrets(namespace).Create(ctx, secret, metav1.CreateOptions{}) + assert.NoError(t, err) + + req := reconcile.Request{ + NamespacedName: types.NamespacedName{ + Name: store, + Namespace: namespace, + }, + } + + currentAndDesiredCephVersion = func(ctx context.Context, rookImage string, namespace string, jobName string, ownerInfo *k8sutil.OwnerInfo, context *clusterd.Context, cephClusterSpec *cephv1.ClusterSpec, clusterInfo *client.ClusterInfo) (*cephver.CephVersion, *cephver.CephVersion, error) { + rotateSupportedVer := cephver.CephVersion{Major: 20, Minor: 2, Extra: 0} + return &rotateSupportedVer, &rotateSupportedVer, nil + } + + // NOTE: these unit subtests are not independent. they share state between tests + + // Rotation is not tested exhaustively for every config. The tests are most concerned with + // ensuring rotation does happen based on inputs and that outputs are updated as expected, for + // both brownfield and greenfield cases. Cephx helper functions for determining when to rotate + // and how to update the status are well tested, so we use good-faith assumption that the + // reconcile implementation uses those, allowing tests here to focus on only the UX aspects + + t.Run("first reconcile", func(t *testing.T) { + res, err := r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.False(t, res.Requeue) + assert.True(t, calledCommitConfigChanges) + + oStore := cephv1.CephObjectStore{} + err = cl.Get(ctx, req.NamespacedName, &oStore) + assert.NoError(t, err) + assert.Equal(t, uint32(1), oStore.Status.Cephx.Daemon.KeyGeneration) + assert.Equal(t, "20.2.0-0", oStore.Status.Cephx.Daemon.KeyCephVersion) + + // ensure ceph identifier annotation applied to pod, resulting in daemon restart + deploy, err := clientset.AppsV1().Deployments(namespace).Get(ctx, "rook-ceph-rgw-"+store+"-a", metav1.GetOptions{}) + assert.NoError(t, err) + // mock contexts preserve the secret's resource version, so we can't test in unit that + // resource ver is applied exactly. However, presence of the cephx identifier annotation + // should be good enough to assume the code is updating and applying it in good faith + _, ok := deploy.Spec.Template.Annotations[keyring.CephxKeyIdentifierAnnotation] + assert.True(t, ok) + }) + + t.Run("subsequent reconcile - retain cephx status", func(t *testing.T) { + res, err := r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.False(t, res.Requeue) + assert.True(t, calledCommitConfigChanges) + + oStore := cephv1.CephObjectStore{} + err = cl.Get(ctx, req.NamespacedName, &oStore) + assert.NoError(t, err) + assert.Equal(t, uint32(1), oStore.Status.Cephx.Daemon.KeyGeneration) + assert.Equal(t, "20.2.0-0", oStore.Status.Cephx.Daemon.KeyCephVersion) + }) + + t.Run("brownfield reconcile - retain unknown cephx status", func(t *testing.T) { + // mimic brownfield oStore from before cephx tracking by setting cephx status empty + oStore := cephv1.CephObjectStore{} + err = cl.Get(ctx, req.NamespacedName, &oStore) + assert.NoError(t, err) + oStore.Status.Cephx.Daemon = cephv1.CephxStatus{} + err = cl.Update(ctx, &oStore) + assert.NoError(t, err) + + res, err := r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.False(t, res.Requeue) + assert.True(t, calledCommitConfigChanges) + + oStore = cephv1.CephObjectStore{} + err = cl.Get(ctx, req.NamespacedName, &oStore) + assert.NoError(t, err) + assert.Equal(t, cephv1.CephxStatus{}, oStore.Status.Cephx.Daemon) + }) + + t.Run("rotate key - brownfield unknown status becomes known", func(t *testing.T) { + cluster := cephv1.CephCluster{} + err = cl.Get(ctx, types.NamespacedName{Namespace: namespace, Name: namespace}, &cluster) + assert.NoError(t, err) + cluster.Spec.Security.CephX.Daemon = cephv1.CephxConfig{ + KeyRotationPolicy: "KeyGeneration", + KeyGeneration: 2, + } + err = cl.Update(ctx, &cluster) + assert.NoError(t, err) + + rotatedKeyJson = `[{"key":"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=="}]` + + res, err := r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.False(t, res.Requeue) + assert.True(t, calledCommitConfigChanges) + + oStore := cephv1.CephObjectStore{} + err = cl.Get(ctx, req.NamespacedName, &oStore) + assert.NoError(t, err) + assert.Equal(t, uint32(2), oStore.Status.Cephx.Daemon.KeyGeneration) + assert.Equal(t, "20.2.0-0", oStore.Status.Cephx.Daemon.KeyCephVersion) + + secret, err = clientset.CoreV1().Secrets(namespace).Get(ctx, "rook-ceph-rgw-"+store+"-a-keyring", metav1.GetOptions{}) + assert.NoError(t, err) + assert.Contains(t, secret.StringData["keyring"], "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB==") + }) + + t.Run("brownfield reconcile - no further rotation happens", func(t *testing.T) { + // if rotation happens when it shouldn't, this will let us know by later comparison + rotatedKeyJson = `[{"key":"CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC=="}]` + + res, err := r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.False(t, res.Requeue) + assert.True(t, calledCommitConfigChanges) + + oStore := cephv1.CephObjectStore{} + err = cl.Get(ctx, req.NamespacedName, &oStore) + assert.NoError(t, err) + assert.Equal(t, uint32(2), oStore.Status.Cephx.Daemon.KeyGeneration) + assert.Equal(t, "20.2.0-0", oStore.Status.Cephx.Daemon.KeyCephVersion) + + secret, err = clientset.CoreV1().Secrets(namespace).Get(ctx, "rook-ceph-rgw-"+store+"-a-keyring", metav1.GetOptions{}) + assert.NoError(t, err) + // code path should use 'auth get-or-create' which doesn't return BBBB... or CCCC..., so just ensure it's not CCCC... + assert.NotContains(t, secret.StringData["keyring"], "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC==") + }) + + t.Run("rotate key - cephx status updated", func(t *testing.T) { + cluster := cephv1.CephCluster{} + err = cl.Get(ctx, types.NamespacedName{Namespace: namespace, Name: namespace}, &cluster) + assert.NoError(t, err) + cluster.Spec.Security.CephX.Daemon = cephv1.CephxConfig{ + KeyRotationPolicy: "KeyGeneration", + KeyGeneration: 4, + } + err = cl.Update(ctx, &cluster) + assert.NoError(t, err) + + rotatedKeyJson = `[{"key":"CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC=="}]` + + res, err := r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.False(t, res.Requeue) + assert.True(t, calledCommitConfigChanges) + + oStore := cephv1.CephObjectStore{} + err = cl.Get(ctx, req.NamespacedName, &oStore) + assert.NoError(t, err) + assert.Equal(t, uint32(4), oStore.Status.Cephx.Daemon.KeyGeneration) + assert.Equal(t, "20.2.0-0", oStore.Status.Cephx.Daemon.KeyCephVersion) + + secret, err = clientset.CoreV1().Secrets(namespace).Get(ctx, "rook-ceph-rgw-"+store+"-a-keyring", metav1.GetOptions{}) + assert.NoError(t, err) + assert.Contains(t, secret.StringData["keyring"], "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC==") + }) +} diff --git a/pkg/operator/ceph/object/rgw.go b/pkg/operator/ceph/object/rgw.go index 5c0786c49..88da57043 100644 --- a/pkg/operator/ceph/object/rgw.go +++ b/pkg/operator/ceph/object/rgw.go @@ -33,6 +33,7 @@ import ( cephclient "github.com/rook/rook/pkg/daemon/ceph/client" "github.com/rook/rook/pkg/operator/ceph/cluster/mon" "github.com/rook/rook/pkg/operator/ceph/config" + "github.com/rook/rook/pkg/operator/ceph/config/keyring" "github.com/rook/rook/pkg/operator/ceph/controller" "github.com/rook/rook/pkg/operator/ceph/pool" "github.com/rook/rook/pkg/operator/k8sutil" @@ -45,14 +46,15 @@ import ( ) type clusterConfig struct { - context *clusterd.Context - clusterInfo *cephclient.ClusterInfo - store *cephv1.CephObjectStore - rookVersion string - clusterSpec *cephv1.ClusterSpec - ownerInfo *k8sutil.OwnerInfo - DataPathMap *config.DataPathMap - client client.Client + context *clusterd.Context + clusterInfo *cephclient.ClusterInfo + store *cephv1.CephObjectStore + rookVersion string + clusterSpec *cephv1.ClusterSpec + ownerInfo *k8sutil.OwnerInfo + DataPathMap *config.DataPathMap + client client.Client + shouldRotateCephxKeys bool } type rgwConfig struct { @@ -140,7 +142,7 @@ func (c *clusterConfig) startRGWPods(realmName, zoneGroupName, zoneName string, // We set the owner reference of the Secret to the Object controller instead of the replicaset // because we watch for that resource and reconcile if anything happens to it - _, err = c.generateKeyring(rgwConfig) + secretResourceVersion, err := c.generateKeyring(rgwConfig) if err != nil { return errors.Wrap(err, "failed to create rgw keyring") } @@ -180,6 +182,9 @@ func (c *clusterConfig) startRGWPods(realmName, zoneGroupName, zoneName string, return errors.Wrapf(err, "failed to set annotation for deployment %q", deployment.Name) } + // apply cephx secret resource version to pod to ensure it restarts when keyring updates + deployment.Spec.Template.Annotations[keyring.CephxKeyIdentifierAnnotation] = secretResourceVersion + _, createErr := c.context.Clientset.AppsV1().Deployments(c.store.Namespace).Create(c.clusterInfo.Context, deployment, metav1.CreateOptions{}) if createErr != nil { if !kerrors.IsAlreadyExists(createErr) { diff --git a/pkg/operator/ceph/object/rgw_test.go b/pkg/operator/ceph/object/rgw_test.go index 588612f73..8030e82e9 100644 --- a/pkg/operator/ceph/object/rgw_test.go +++ b/pkg/operator/ceph/object/rgw_test.go @@ -79,7 +79,7 @@ func TestStartRGW(t *testing.T) { // start a basic cluster ownerInfo := client.NewMinimumOwnerInfoWithOwnerRef() - c := &clusterConfig{context, info, store, version, &cephv1.ClusterSpec{}, ownerInfo, data, r.client} + c := &clusterConfig{context, info, store, version, &cephv1.ClusterSpec{}, ownerInfo, data, r.client, false} t.Run("Deployment is created", func(t *testing.T) { store.Spec.Gateway.Instances = 1 @@ -140,7 +140,7 @@ func TestCreateObjectStore(t *testing.T) { cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(object...).Build() r := &ReconcileCephObjectStore{client: cl, scheme: s} ownerInfo := client.NewMinimumOwnerInfoWithOwnerRef() - c := &clusterConfig{context, info, store, "1.2.3.4", &cephv1.ClusterSpec{}, ownerInfo, data, r.client} + c := &clusterConfig{context, info, store, "1.2.3.4", &cephv1.ClusterSpec{}, ownerInfo, data, r.client, false} err := c.createOrUpdateStore(store.Name, store.Name, store.Name, nil) assert.Nil(t, err) } @@ -188,7 +188,7 @@ func TestCreateObjectStoreWithKeystoneAndS3(t *testing.T) { cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(object...).Build() r := &ReconcileCephObjectStore{client: cl, scheme: s} ownerInfo := client.NewMinimumOwnerInfoWithOwnerRef() - c := &clusterConfig{context, info, store, "1.2.3.4", &cephv1.ClusterSpec{}, ownerInfo, data, r.client} + c := &clusterConfig{context, info, store, "1.2.3.4", &cephv1.ClusterSpec{}, ownerInfo, data, r.client, false} err := c.createOrUpdateStore(store.Name, store.Name, store.Name, nil) assert.Nil(t, err) } @@ -220,6 +220,7 @@ func TestGenerateSecretName(t *testing.T) { &k8sutil.OwnerInfo{}, &config.DataPathMap{}, cl, + false, } secret := c.generateSecretName("a") assert.Equal(t, "rook-ceph-rgw-default-a-keyring", secret) diff --git a/pkg/operator/ceph/object/status.go b/pkg/operator/ceph/object/status.go index d6d1c0e0f..1f6c3435f 100644 --- a/pkg/operator/ceph/object/status.go +++ b/pkg/operator/ceph/object/status.go @@ -32,12 +32,12 @@ import ( ) func (r *ReconcileCephObjectStore) setFailedStatus(observedGeneration int64, name types.NamespacedName, errMessage string, err error) (reconcile.Result, error) { - updateStatus(r.opManagerContext, observedGeneration, r.client, name, cephv1.ConditionFailure, map[string]string{}) + updateStatus(r.opManagerContext, observedGeneration, r.client, name, cephv1.ConditionFailure, map[string]string{}, nil) return reconcile.Result{}, errors.Wrapf(err, "%s", errMessage) } // updateStatus updates an object with a given status -func updateStatus(ctx context.Context, observedGeneration int64, client client.Client, namespacedName types.NamespacedName, status cephv1.ConditionType, info map[string]string) { +func updateStatus(ctx context.Context, observedGeneration int64, client client.Client, namespacedName types.NamespacedName, status cephv1.ConditionType, info map[string]string, cephx *cephv1.CephxStatus) { // Updating the status is important to users, but we can still keep operating if there is a // failure. Retry a few times to give it our best effort attempt. err := retry.RetryOnConflict(retry.DefaultRetry, func() error { @@ -78,6 +78,10 @@ func updateStatus(ctx context.Context, observedGeneration int64, client client.C objectStore.Status.Endpoints.Secure = getAllDNSEndpoints(objectStore, securePort, true) } + if cephx != nil { + objectStore.Status.Cephx.Daemon = *cephx + } + if err := reporting.UpdateStatus(client, objectStore); err != nil { return errors.Wrapf(err, "failed to set object store %q status to %q", namespacedName.String(), status) }