diff --git a/controllers/storagecluster/storageclient.go b/controllers/storagecluster/storageclient.go index f0ad97087f..6a550ed23d 100644 --- a/controllers/storagecluster/storageclient.go +++ b/controllers/storagecluster/storageclient.go @@ -17,8 +17,7 @@ import ( ) const ( - tokenLifetimeInHours = 48 - onboardingPrivateKeyFilePath = "/etc/private-key/key" + tokenLifetimeInHours = 48 ocsClientConfigMapName = "ocs-client-operator-config" manageNoobaaSubKey = "manageNoobaaSubscription" @@ -47,7 +46,11 @@ func (s *storageClient) ensureCreated(r *StorageClusterReconciler, storagecluste storageClient.Name = storagecluster.Name _, err := controllerutil.CreateOrUpdate(r.ctx, r.Client, storageClient, func() error { if storageClient.Status.ConsumerID == "" { - token, err := util.GenerateClientOnboardingToken(tokenLifetimeInHours, onboardingPrivateKeyFilePath, nil, storagecluster.UID) + privateKey, err := util.LoadOnboardingValidationPrivateKey(r.ctx, r.Client, r.OperatorNamespace) + if err != nil { + return fmt.Errorf("unable to get Parsed Private Key: %v", err) + } + token, err := util.GenerateClientOnboardingToken(tokenLifetimeInHours, privateKey, nil, storagecluster.UID) if err != nil { return fmt.Errorf("unable to generate onboarding token: %v", err) } diff --git a/controllers/storagecluster/storagecluster_controller.go b/controllers/storagecluster/storagecluster_controller.go index 9e7589fe7d..80a5c01d5d 100644 --- a/controllers/storagecluster/storagecluster_controller.go +++ b/controllers/storagecluster/storagecluster_controller.go @@ -225,7 +225,7 @@ func (r *StorageClusterReconciler) SetupWithManager(mgr ctrl.Manager) error { Owns(&appsv1.Deployment{}, builder.WithPredicates(predicate.GenerationChangedPredicate{})). Owns(&corev1.Service{}, builder.WithPredicates(predicate.GenerationChangedPredicate{})). Owns(&corev1.ConfigMap{}, builder.MatchEveryOwner, builder.WithPredicates(predicate.GenerationChangedPredicate{})). - Owns(&corev1.Secret{}, builder.WithPredicates(predicate.GenerationChangedPredicate{})). + Owns(&corev1.Secret{}, builder.MatchEveryOwner, builder.WithPredicates(predicate.GenerationChangedPredicate{})). Owns(&routev1.Route{}). Owns(&templatev1.Template{}). // Using builder.OnlyMetadata as we are only interested in the presence and not getting this resource anywhere diff --git a/controllers/util/provider.go b/controllers/util/provider.go index 231dfd8c13..0e3eab2627 100644 --- a/controllers/util/provider.go +++ b/controllers/util/provider.go @@ -1,6 +1,7 @@ package util import ( + "context" "crypto" "crypto/rand" "crypto/rsa" @@ -10,19 +11,22 @@ import ( "encoding/json" "encoding/pem" "fmt" - "os" "time" "github.com/red-hat-storage/ocs-operator/v4/services" "github.com/google/uuid" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" ) +const onboardingValidationPrivateKeySecretName = "onboarding-private-key" + // GenerateClientOnboardingToken generates a ocs-client token valid for a duration of "tokenLifetimeInHours". // The token content is predefined and signed by the private key which'll be read from supplied "privateKeyPath". // The storageQuotaInGiB is optional, and it is used to limit the storage of PVC in the application cluster. -func GenerateClientOnboardingToken(tokenLifetimeInHours int, privateKeyPath string, storageQuotainGib *uint, storageClusterUID types.UID) (string, error) { +func GenerateClientOnboardingToken(tokenLifetimeInHours int, privateKey *rsa.PrivateKey, storageQuotainGib *uint, storageClusterUID types.UID) (string, error) { tokenExpirationDate := time.Now(). Add(time.Duration(tokenLifetimeInHours) * time.Hour). Unix() @@ -35,7 +39,7 @@ func GenerateClientOnboardingToken(tokenLifetimeInHours int, privateKeyPath stri StorageCluster: storageClusterUID, } - token, err := encodeAndSignOnboardingToken(privateKeyPath, ticket) + token, err := encodeAndSignOnboardingToken(privateKey, ticket) if err != nil { return "", err } @@ -44,7 +48,7 @@ func GenerateClientOnboardingToken(tokenLifetimeInHours int, privateKeyPath stri // GeneratePeerOnboardingToken generates a ocs-peer token valid for a duration of "tokenLifetimeInHours". // The token content is predefined and signed by the private key which'll be read from supplied "privateKeyPath". -func GeneratePeerOnboardingToken(tokenLifetimeInHours int, privateKeyPath string, storageClusterUID types.UID) (string, error) { +func GeneratePeerOnboardingToken(tokenLifetimeInHours int, privateKey *rsa.PrivateKey, storageClusterUID types.UID) (string, error) { tokenExpirationDate := time.Now(). Add(time.Duration(tokenLifetimeInHours) * time.Hour). Unix() @@ -55,7 +59,7 @@ func GeneratePeerOnboardingToken(tokenLifetimeInHours int, privateKeyPath string SubjectRole: services.PeerRole, StorageCluster: storageClusterUID, } - token, err := encodeAndSignOnboardingToken(privateKeyPath, ticket) + token, err := encodeAndSignOnboardingToken(privateKey, ticket) if err != nil { return "", err } @@ -64,7 +68,7 @@ func GeneratePeerOnboardingToken(tokenLifetimeInHours int, privateKeyPath string // encodeAndSignOnboardingToken generates a token from the ticket. // The token content is predefined and signed by the private key which'll be read from supplied "privateKeyPath". -func encodeAndSignOnboardingToken(privateKeyPath string, ticket services.OnboardingTicket) (string, error) { +func encodeAndSignOnboardingToken(privateKey *rsa.PrivateKey, ticket services.OnboardingTicket) (string, error) { payload, err := json.Marshal(ticket) if err != nil { return "", fmt.Errorf("failed to marshal the payload: %v", err) @@ -79,11 +83,6 @@ func encodeAndSignOnboardingToken(privateKeyPath string, ticket services.Onboard return "", fmt.Errorf("failed to hash onboarding token payload: %v", err) } - privateKey, err := readAndDecodePrivateKey(privateKeyPath) - if err != nil { - return "", fmt.Errorf("failed to read and decode private key: %v", err) - } - msgHashSum := msgHash.Sum(nil) // In order to generate the signature, we provide a random number generator, // our private key, the hashing algorithm that we used, and the hash sum @@ -97,16 +96,26 @@ func encodeAndSignOnboardingToken(privateKeyPath string, ticket services.Onboard return fmt.Sprintf("%s.%s", encodedPayload, encodedSignature), nil } -func readAndDecodePrivateKey(privateKeyPath string) (*rsa.PrivateKey, error) { - pemString, err := os.ReadFile(privateKeyPath) +func LoadOnboardingValidationPrivateKey(ctx context.Context, cl client.Client, namespace string) (*rsa.PrivateKey, error) { + privateSecret := &corev1.Secret{} + privateSecret.Name = onboardingValidationPrivateKeySecretName + privateSecret.Namespace = namespace + + err := cl.Get(ctx, client.ObjectKeyFromObject(privateSecret), privateSecret) if err != nil { - return nil, fmt.Errorf("failed to read private key: %v", err) + return nil, fmt.Errorf("failed to get private secret: %v", err) } - Block, _ := pem.Decode(pemString) - privateKey, err := x509.ParsePKCS1PrivateKey(Block.Bytes) - if err != nil { - return nil, fmt.Errorf("failed to parse private key: %v", err) + if privateSecret.Data != nil { + if privateSecretKey, ok := privateSecret.Data["key"]; ok { + Block, _ := pem.Decode(privateSecretKey) + privateKey, err := x509.ParsePKCS1PrivateKey(Block.Bytes) + if err != nil { + return nil, fmt.Errorf("failed to parse private key: %v", err) + } + return privateKey, nil + } } - return privateKey, nil + + return nil, fmt.Errorf("No data found in secret") } diff --git a/deploy/ocs-operator/manifests/ocs-operator.clusterserviceversion.yaml b/deploy/ocs-operator/manifests/ocs-operator.clusterserviceversion.yaml index 9683139716..15c52f91b7 100644 --- a/deploy/ocs-operator/manifests/ocs-operator.clusterserviceversion.yaml +++ b/deploy/ocs-operator/manifests/ocs-operator.clusterserviceversion.yaml @@ -641,8 +641,6 @@ spec: readOnlyRootFilesystem: true runAsNonRoot: true volumeMounts: - - mountPath: /etc/private-key - name: onboarding-private-key - mountPath: /etc/tls/private name: ux-cert-secret - args: @@ -678,10 +676,6 @@ spec: operator: Equal value: "true" volumes: - - name: onboarding-private-key - secret: - optional: true - secretName: onboarding-private-key - name: ux-proxy-secret secret: secretName: ux-backend-proxy diff --git a/metrics/vendor/github.com/red-hat-storage/ocs-operator/v4/controllers/util/provider.go b/metrics/vendor/github.com/red-hat-storage/ocs-operator/v4/controllers/util/provider.go index 231dfd8c13..0e3eab2627 100644 --- a/metrics/vendor/github.com/red-hat-storage/ocs-operator/v4/controllers/util/provider.go +++ b/metrics/vendor/github.com/red-hat-storage/ocs-operator/v4/controllers/util/provider.go @@ -1,6 +1,7 @@ package util import ( + "context" "crypto" "crypto/rand" "crypto/rsa" @@ -10,19 +11,22 @@ import ( "encoding/json" "encoding/pem" "fmt" - "os" "time" "github.com/red-hat-storage/ocs-operator/v4/services" "github.com/google/uuid" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" ) +const onboardingValidationPrivateKeySecretName = "onboarding-private-key" + // GenerateClientOnboardingToken generates a ocs-client token valid for a duration of "tokenLifetimeInHours". // The token content is predefined and signed by the private key which'll be read from supplied "privateKeyPath". // The storageQuotaInGiB is optional, and it is used to limit the storage of PVC in the application cluster. -func GenerateClientOnboardingToken(tokenLifetimeInHours int, privateKeyPath string, storageQuotainGib *uint, storageClusterUID types.UID) (string, error) { +func GenerateClientOnboardingToken(tokenLifetimeInHours int, privateKey *rsa.PrivateKey, storageQuotainGib *uint, storageClusterUID types.UID) (string, error) { tokenExpirationDate := time.Now(). Add(time.Duration(tokenLifetimeInHours) * time.Hour). Unix() @@ -35,7 +39,7 @@ func GenerateClientOnboardingToken(tokenLifetimeInHours int, privateKeyPath stri StorageCluster: storageClusterUID, } - token, err := encodeAndSignOnboardingToken(privateKeyPath, ticket) + token, err := encodeAndSignOnboardingToken(privateKey, ticket) if err != nil { return "", err } @@ -44,7 +48,7 @@ func GenerateClientOnboardingToken(tokenLifetimeInHours int, privateKeyPath stri // GeneratePeerOnboardingToken generates a ocs-peer token valid for a duration of "tokenLifetimeInHours". // The token content is predefined and signed by the private key which'll be read from supplied "privateKeyPath". -func GeneratePeerOnboardingToken(tokenLifetimeInHours int, privateKeyPath string, storageClusterUID types.UID) (string, error) { +func GeneratePeerOnboardingToken(tokenLifetimeInHours int, privateKey *rsa.PrivateKey, storageClusterUID types.UID) (string, error) { tokenExpirationDate := time.Now(). Add(time.Duration(tokenLifetimeInHours) * time.Hour). Unix() @@ -55,7 +59,7 @@ func GeneratePeerOnboardingToken(tokenLifetimeInHours int, privateKeyPath string SubjectRole: services.PeerRole, StorageCluster: storageClusterUID, } - token, err := encodeAndSignOnboardingToken(privateKeyPath, ticket) + token, err := encodeAndSignOnboardingToken(privateKey, ticket) if err != nil { return "", err } @@ -64,7 +68,7 @@ func GeneratePeerOnboardingToken(tokenLifetimeInHours int, privateKeyPath string // encodeAndSignOnboardingToken generates a token from the ticket. // The token content is predefined and signed by the private key which'll be read from supplied "privateKeyPath". -func encodeAndSignOnboardingToken(privateKeyPath string, ticket services.OnboardingTicket) (string, error) { +func encodeAndSignOnboardingToken(privateKey *rsa.PrivateKey, ticket services.OnboardingTicket) (string, error) { payload, err := json.Marshal(ticket) if err != nil { return "", fmt.Errorf("failed to marshal the payload: %v", err) @@ -79,11 +83,6 @@ func encodeAndSignOnboardingToken(privateKeyPath string, ticket services.Onboard return "", fmt.Errorf("failed to hash onboarding token payload: %v", err) } - privateKey, err := readAndDecodePrivateKey(privateKeyPath) - if err != nil { - return "", fmt.Errorf("failed to read and decode private key: %v", err) - } - msgHashSum := msgHash.Sum(nil) // In order to generate the signature, we provide a random number generator, // our private key, the hashing algorithm that we used, and the hash sum @@ -97,16 +96,26 @@ func encodeAndSignOnboardingToken(privateKeyPath string, ticket services.Onboard return fmt.Sprintf("%s.%s", encodedPayload, encodedSignature), nil } -func readAndDecodePrivateKey(privateKeyPath string) (*rsa.PrivateKey, error) { - pemString, err := os.ReadFile(privateKeyPath) +func LoadOnboardingValidationPrivateKey(ctx context.Context, cl client.Client, namespace string) (*rsa.PrivateKey, error) { + privateSecret := &corev1.Secret{} + privateSecret.Name = onboardingValidationPrivateKeySecretName + privateSecret.Namespace = namespace + + err := cl.Get(ctx, client.ObjectKeyFromObject(privateSecret), privateSecret) if err != nil { - return nil, fmt.Errorf("failed to read private key: %v", err) + return nil, fmt.Errorf("failed to get private secret: %v", err) } - Block, _ := pem.Decode(pemString) - privateKey, err := x509.ParsePKCS1PrivateKey(Block.Bytes) - if err != nil { - return nil, fmt.Errorf("failed to parse private key: %v", err) + if privateSecret.Data != nil { + if privateSecretKey, ok := privateSecret.Data["key"]; ok { + Block, _ := pem.Decode(privateSecretKey) + privateKey, err := x509.ParsePKCS1PrivateKey(Block.Bytes) + if err != nil { + return nil, fmt.Errorf("failed to parse private key: %v", err) + } + return privateKey, nil + } } - return privateKey, nil + + return nil, fmt.Errorf("No data found in secret") } diff --git a/services/ux-backend/handlers/onboarding/clienttokens/handler.go b/services/ux-backend/handlers/onboarding/clienttokens/handler.go index 3d32567239..85f804a2f4 100644 --- a/services/ux-backend/handlers/onboarding/clienttokens/handler.go +++ b/services/ux-backend/handlers/onboarding/clienttokens/handler.go @@ -1,6 +1,7 @@ package clienttokens import ( + "context" "encoding/json" "fmt" "math" @@ -14,36 +15,32 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" ) -const ( - onboardingPrivateKeyFilePath = "/etc/private-key/key" -) - var unitToGib = map[string]uint{ "Gi": 1, "Ti": 1024, "Pi": 1024 * 1024, } -func HandleMessage(w http.ResponseWriter, r *http.Request, tokenLifetimeInHours int, cl client.Client, namespace string) { +func HandleMessage(ctx context.Context, w http.ResponseWriter, r *http.Request, tokenLifetimeInHours int, cl client.Client, namespace string) { switch r.Method { case "POST": - handlePost(w, r, tokenLifetimeInHours, cl, namespace) + handlePost(ctx, w, r, tokenLifetimeInHours, cl, namespace) default: handleUnsupportedMethod(w, r) } } -func handlePost(w http.ResponseWriter, r *http.Request, tokenLifetimeInHours int, cl client.Client, namespace string) { +func handlePost(ctx context.Context, w http.ResponseWriter, r *http.Request, tokenLifetimeInHours int, cl client.Client, namespace string) { var storageQuotaInGiB *uint // When ContentLength is 0 that means request body is empty and // storage quota is unlimited - var err error + if r.ContentLength != 0 { var quota = struct { Value uint `json:"value"` Unit string `json:"unit"` }{} - if err = json.NewDecoder(r.Body).Decode("a); err != nil { + if err := json.NewDecoder(r.Body).Decode("a); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } @@ -66,7 +63,14 @@ func handlePost(w http.ResponseWriter, r *http.Request, tokenLifetimeInHours int return } - if onboardingToken, err := util.GenerateClientOnboardingToken(tokenLifetimeInHours, onboardingPrivateKeyFilePath, storageQuotaInGiB, storageCluster.UID); err != nil { + privateKey, err := util.LoadOnboardingValidationPrivateKey(ctx, cl, namespace) + klog.Info("Getting the Pem key") + if err != nil { + http.Error(w, fmt.Sprintf("Failed to get private key: %v", err), http.StatusBadRequest) + return + } + + if onboardingToken, err := util.GenerateClientOnboardingToken(tokenLifetimeInHours, privateKey, storageQuotaInGiB, storageCluster.UID); err != nil { klog.Errorf("failed to get onboarding token: %v", err) w.WriteHeader(http.StatusInternalServerError) w.Header().Set("Content-Type", handlers.ContentTypeTextPlain) diff --git a/services/ux-backend/handlers/onboarding/peertokens/handler.go b/services/ux-backend/handlers/onboarding/peertokens/handler.go index 5d8f252872..482282541d 100644 --- a/services/ux-backend/handlers/onboarding/peertokens/handler.go +++ b/services/ux-backend/handlers/onboarding/peertokens/handler.go @@ -1,6 +1,7 @@ package peertokens import ( + "context" "fmt" "net/http" @@ -11,10 +12,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" ) -const ( - onboardingPrivateKeyFilePath = "/etc/private-key/key" -) - func HandleMessage(w http.ResponseWriter, r *http.Request, tokenLifetimeInHours int, cl client.Client, namespace string) { switch r.Method { case "POST": @@ -25,14 +22,21 @@ func HandleMessage(w http.ResponseWriter, r *http.Request, tokenLifetimeInHours } func handlePost(w http.ResponseWriter, r *http.Request, tokenLifetimeInHours int, cl client.Client, namespace string) { - storageCluster, err := util.GetStorageClusterInNamespace(r.Context(), cl, namespace) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } - if onboardingToken, err := util.GeneratePeerOnboardingToken(tokenLifetimeInHours, onboardingPrivateKeyFilePath, storageCluster.UID); err != nil { + ctx := context.TODO() + privateKey, err := util.LoadOnboardingValidationPrivateKey(ctx, cl, namespace) + klog.Info("Getting the Pem key") + if err != nil { + http.Error(w, fmt.Sprintf("Failed to get private key: %v", err), http.StatusBadRequest) + return + } + + if onboardingToken, err := util.GeneratePeerOnboardingToken(tokenLifetimeInHours, privateKey, storageCluster.UID); err != nil { klog.Errorf("failed to get onboarding token: %v", err) w.WriteHeader(http.StatusInternalServerError) w.Header().Set("Content-Type", handlers.ContentTypeTextPlain) diff --git a/services/ux-backend/main.go b/services/ux-backend/main.go index 42abc96137..8e13d462ed 100644 --- a/services/ux-backend/main.go +++ b/services/ux-backend/main.go @@ -11,9 +11,9 @@ import ( "github.com/red-hat-storage/ocs-operator/v4/controllers/util" "github.com/red-hat-storage/ocs-operator/v4/services/ux-backend/handlers/onboarding/clienttokens" "github.com/red-hat-storage/ocs-operator/v4/services/ux-backend/handlers/onboarding/peertokens" - corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/klog/v2" ) @@ -87,10 +87,10 @@ func main() { // Set the Deprecation header w.Header().Set("Deprecation", "true") // Standard "Deprecation" header w.Header().Set("Link", "/onboarding/client-tokens; rel=\"alternate\"") - clienttokens.HandleMessage(w, r, config.tokenLifetimeInHours, cl, namespace) + clienttokens.HandleMessage(r.Context(), w, r, config.tokenLifetimeInHours, cl, namespace) }) http.HandleFunc("/onboarding/client-tokens", func(w http.ResponseWriter, r *http.Request) { - clienttokens.HandleMessage(w, r, config.tokenLifetimeInHours, cl, namespace) + clienttokens.HandleMessage(r.Context(), w, r, config.tokenLifetimeInHours, cl, namespace) }) http.HandleFunc("/onboarding/peer-tokens", func(w http.ResponseWriter, r *http.Request) { peertokens.HandleMessage(w, r, config.tokenLifetimeInHours, cl, namespace) diff --git a/tools/csv-merger/csv-merger.go b/tools/csv-merger/csv-merger.go index 73fb87af0c..29acf6e5e3 100644 --- a/tools/csv-merger/csv-merger.go +++ b/tools/csv-merger/csv-merger.go @@ -644,10 +644,6 @@ func getUXBackendServerDeployment() appsv1.DeploymentSpec { { Name: "ux-backend-server", VolumeMounts: []corev1.VolumeMount{ - { - Name: "onboarding-private-key", - MountPath: "/etc/private-key", - }, { Name: "ux-cert-secret", MountPath: "/etc/tls/private", @@ -724,15 +720,6 @@ func getUXBackendServerDeployment() appsv1.DeploymentSpec { }, }, Volumes: []corev1.Volume{ - { - Name: "onboarding-private-key", - VolumeSource: corev1.VolumeSource{ - Secret: &corev1.SecretVolumeSource{ - SecretName: "onboarding-private-key", - Optional: ptr.To(true), - }, - }, - }, { Name: "ux-proxy-secret", VolumeSource: corev1.VolumeSource{