[OOM-K8S-CERT-EXTERNAL-PROVIDER] Mock implementaion enhanced (part III)
[oom/platform/cert-service.git] / certServiceK8sExternalProvider / src / cmpv2controller / cmpv2_issuer_controller.go
1 /*
2  * ============LICENSE_START=======================================================
3  * oom-certservice-k8s-external-provider
4  * ================================================================================
5  * Copyright (c) 2019 Smallstep Labs, Inc.
6  * Modifications copyright (C) 2020 Nokia. All rights reserved.
7  * ================================================================================
8  * This source code was copied from the following git repository:
9  * https://github.com/smallstep/step-issuer
10  * The source code was modified for usage in the ONAP project.
11  * ================================================================================
12  * Licensed under the Apache License, Version 2.0 (the "License");
13  * you may not use this file except in compliance with the License.
14  * You may obtain a copy of the License at
15  *
16  *      http://www.apache.org/licenses/LICENSE-2.0
17  *
18  * Unless required by applicable law or agreed to in writing, software
19  * distributed under the License is distributed on an "AS IS" BASIS,
20  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21  * See the License for the specific language governing permissions and
22  * limitations under the License.
23  * ============LICENSE_END=========================================================
24  */
25
26 package cmpv2controller
27
28 import (
29         "context"
30         "fmt"
31         "github.com/go-logr/logr"
32         core "k8s.io/api/core/v1"
33         apierrors "k8s.io/apimachinery/pkg/api/errors"
34         "k8s.io/apimachinery/pkg/runtime"
35         "k8s.io/apimachinery/pkg/types"
36         "k8s.io/client-go/tools/record"
37         "k8s.io/utils/clock"
38         "onap.org/oom-certservice/k8s-external-provider/src/cmpv2api"
39         provisioners "onap.org/oom-certservice/k8s-external-provider/src/cmpv2provisioner"
40         ctrl "sigs.k8s.io/controller-runtime"
41         "sigs.k8s.io/controller-runtime/pkg/client"
42 )
43
44 // CMPv2IssuerController reconciles a CMPv2Issuer object
45 type CMPv2IssuerController struct {
46         client.Client
47         Log      logr.Logger
48         Clock    clock.Clock
49         Recorder record.EventRecorder
50 }
51
52 // Reconcile will read and validate the CMPv2Issuer resources, it will set the
53 // status condition ready to true if everything is right.
54 func (controller *CMPv2IssuerController) Reconcile(req ctrl.Request) (ctrl.Result, error) {
55         ctx := context.Background()
56         log := controller.Log.WithValues("cmpv2-issuer-controller", req.NamespacedName)
57
58         // 1. Load CMPv2Issuer
59         issuer := new(cmpv2api.CMPv2Issuer)
60         if err := controller.loadResource(ctx, req.NamespacedName, issuer); err != nil {
61                 handleErrorLoadingCMPv2Issuer(log, err)
62                 return ctrl.Result{}, client.IgnoreNotFound(err)
63         }
64         log.Info("CMPv2Issuer loaded: ", "issuer", issuer)
65
66         // 2. Validate CMPv2Issuer
67         statusUpdater := newStatusUpdater(controller, issuer, log)
68         if err := validateCMPv2IssuerSpec(issuer.Spec, log); err != nil {
69                 handleErrorCMPv2IssuerValidation(ctx, log, err, statusUpdater)
70                 return ctrl.Result{}, err
71         }
72
73         // 3. Load keystore and truststore information form k8s secret
74         var secret core.Secret
75         secretNamespaceName := types.NamespacedName{
76                 Namespace: req.Namespace,
77                 Name:      issuer.Spec.KeyRef.Name,
78         }
79         if err := controller.loadResource(ctx, secretNamespaceName, &secret); err != nil {
80                 handleErrorInvalidSecret(ctx, log, err, statusUpdater, secretNamespaceName)
81                 return ctrl.Result{}, err
82         }
83         password, ok := secret.Data[issuer.Spec.KeyRef.Key]
84         if !ok {
85                 err := handleErrorSecretNotFound(ctx, log, issuer, statusUpdater, secretNamespaceName, secret)
86                 return ctrl.Result{}, err
87         }
88
89         // 4. Create CMPv2 provisioner and store the instance for further use
90         provisioner, err := provisioners.New(issuer, password)
91         if err != nil {
92                 handleErrorProvisionerInitialization(ctx, log, err, statusUpdater)
93                 return ctrl.Result{}, err
94         }
95         provisioners.Store(req.NamespacedName, provisioner)
96
97         // 5. Update the status of CMPv2Issuer to 'Validated'
98         if err := updateCMPv2IssuerStatusToVerified(statusUpdater, ctx, log); err != nil {
99                 handleErrorUpdatingCMPv2IssuerStatus(log, err)
100                 return ctrl.Result{}, err
101         }
102
103         return ctrl.Result{}, nil
104 }
105
106
107 func (controller *CMPv2IssuerController) SetupWithManager(manager ctrl.Manager) error {
108         return ctrl.NewControllerManagedBy(manager).
109                 For(&cmpv2api.CMPv2Issuer{}).
110                 Complete(controller)
111 }
112
113 func (controller *CMPv2IssuerController) loadResource(ctx context.Context, key client.ObjectKey, obj runtime.Object) error {
114         return controller.Client.Get(ctx, key, obj)
115 }
116
117
118 func validateCMPv2IssuerSpec(issuerSpec cmpv2api.CMPv2IssuerSpec, log logr.Logger) error {
119         switch {
120                 case issuerSpec.URL == "":
121                         return fmt.Errorf("spec.url cannot be empty")
122                 case issuerSpec.KeyRef.Name == "":
123                         return fmt.Errorf("spec.keyRef.name cannot be empty")
124                 case issuerSpec.KeyRef.Key == "":
125                         return fmt.Errorf("spec.keyRef.key cannot be empty")
126                 default:
127                         log.Info("CMPv2Issuer validated. ")
128                         return nil
129         }
130 }
131
132 func updateCMPv2IssuerStatusToVerified(statusUpdater *CMPv2IssuerStatusUpdater, ctx context.Context, log logr.Logger) error {
133         log.Info("CMPv2 provisioner created -> updating status to of CMPv2Issuer resource to: Verified")
134         return statusUpdater.Update(ctx, cmpv2api.ConditionTrue, Verified, "CMPv2Issuer verified and ready to sign certificates")
135 }
136
137
138 // Error handling
139
140 func handleErrorUpdatingCMPv2IssuerStatus(log logr.Logger, err error) {
141         log.Error(err, "Failed to update CMPv2Issuer status")
142 }
143
144
145 func handleErrorLoadingCMPv2Issuer(log logr.Logger, err error) {
146         log.Error(err, "Failed to retrieve CMPv2Issuer resource")
147 }
148
149
150 func handleErrorProvisionerInitialization(ctx context.Context, log logr.Logger, err error, statusUpdater *CMPv2IssuerStatusUpdater) {
151         log.Error(err, "Failed to initialize provisioner")
152         statusUpdater.UpdateNoError(ctx, cmpv2api.ConditionFalse, Error, "Failed initialize provisioner")
153 }
154
155 func handleErrorCMPv2IssuerValidation(ctx context.Context, log logr.Logger, err error, statusUpdater *CMPv2IssuerStatusUpdater) {
156         log.Error(err, "Failed to validate CMPv2Issuer resource")
157         statusUpdater.UpdateNoError(ctx, cmpv2api.ConditionFalse, ValidationFailed, "Failed to validate resource: %v", err)
158 }
159
160 func handleErrorSecretNotFound(ctx context.Context, log logr.Logger, issuer *cmpv2api.CMPv2Issuer, statusUpdater *CMPv2IssuerStatusUpdater, secretNamespaceName types.NamespacedName, secret core.Secret) error {
161         err := fmt.Errorf("secret %s does not contain key %s", secret.Name, issuer.Spec.KeyRef.Key)
162         log.Error(err, "Failed to retrieve CMPv2Issuer provisioner secret", "namespace", secretNamespaceName.Namespace, "name", secretNamespaceName.Name)
163         statusUpdater.UpdateNoError(ctx, cmpv2api.ConditionFalse, NotFound, "Failed to retrieve provisioner secret: %v", err)
164         return err
165 }
166
167 func handleErrorInvalidSecret(ctx context.Context, log logr.Logger, err error, statusUpdater *CMPv2IssuerStatusUpdater, secretNamespaceName types.NamespacedName) {
168         log.Error(err, "Failed to retrieve CMPv2Issuer provisioner secret", "namespace", secretNamespaceName.Namespace, "name", secretNamespaceName.Name)
169         if apierrors.IsNotFound(err) {
170                 statusUpdater.UpdateNoError(ctx, cmpv2api.ConditionFalse, NotFound, "Failed to retrieve provisioner secret: %v", err)
171         } else {
172                 statusUpdater.UpdateNoError(ctx, cmpv2api.ConditionFalse, Error, "Failed to retrieve provisioner secret: %v", err)
173         }
174 }