[OOM-K8S-CERT-EXTERNAL-PROVIDER] Mock implementaion enhanced
[oom/platform/cert-service.git] / certServiceK8sExternalProvider / src / certservice-controller / certservice_issuer_reconciler.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 certservice_controller
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/types"
35         "k8s.io/client-go/tools/record"
36         "k8s.io/utils/clock"
37         "onap.org/oom-certservice/k8s-external-provider/src/api"
38         provisioners "onap.org/oom-certservice/k8s-external-provider/src/certservice-provisioner"
39         ctrl "sigs.k8s.io/controller-runtime"
40         "sigs.k8s.io/controller-runtime/pkg/client"
41 )
42
43 // CertServiceIssuerReconciler reconciles a CertServiceIssuer object
44 type CertServiceIssuerReconciler struct {
45         client.Client
46         Log      logr.Logger
47         Clock    clock.Clock
48         Recorder record.EventRecorder
49 }
50
51 // Reconcile will read and validate the CertServiceIssuer resources, it will set the
52 // status condition ready to true if everything is right.
53 func (reconciler *CertServiceIssuerReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
54         ctx := context.Background()
55         log := reconciler.Log.WithValues("certservice-issuer-controller", req.NamespacedName)
56
57         issuer := new(api.CertServiceIssuer)
58         if err := reconciler.Client.Get(ctx, req.NamespacedName, issuer); err != nil {
59                 log.Error(err, "failed to retrieve CertServiceIssuer resource")
60                 return ctrl.Result{}, client.IgnoreNotFound(err)
61         }
62         log.Info("Issuer loaded: ", "issuer", issuer)
63
64         statusReconciler := newStatusReconciler(reconciler, issuer, log)
65         if err := validateCertServiceIssuerSpec(issuer.Spec); err != nil {
66                 log.Error(err, "failed to validate CertServiceIssuer resource")
67                 statusReconciler.UpdateNoError(ctx, api.ConditionFalse, "Validation", "Failed to validate resource: %v", err)
68                 return ctrl.Result{}, err
69         }
70         log.Info("Issuer validated. ")
71
72         // Fetch the provisioner password
73         var secret core.Secret
74         secretNamespaceName := types.NamespacedName{
75                 Namespace: req.Namespace,
76                 Name:      issuer.Spec.KeyRef.Name,
77         }
78         if err := reconciler.Client.Get(ctx, secretNamespaceName, &secret); err != nil {
79                 log.Error(err, "failed to retrieve CertServiceIssuer provisioner secret", "namespace", secretNamespaceName.Namespace, "name", secretNamespaceName.Name)
80                 if apierrors.IsNotFound(err) {
81                         statusReconciler.UpdateNoError(ctx, api.ConditionFalse, "NotFound", "Failed to retrieve provisioner secret: %v", err)
82                 } else {
83                         statusReconciler.UpdateNoError(ctx, api.ConditionFalse, "Error", "Failed to retrieve provisioner secret: %v", err)
84                 }
85                 return ctrl.Result{}, err
86         }
87         password, ok := secret.Data[issuer.Spec.KeyRef.Key]
88         if !ok {
89                 err := fmt.Errorf("secret %s does not contain key %s", secret.Name, issuer.Spec.KeyRef.Key)
90                 log.Error(err, "failed to retrieve CertServiceIssuer provisioner secret", "namespace", secretNamespaceName.Namespace, "name", secretNamespaceName.Name)
91                 statusReconciler.UpdateNoError(ctx, api.ConditionFalse, "NotFound", "Failed to retrieve provisioner secret: %v", err)
92                 return ctrl.Result{}, err
93         }
94
95         // Initialize and store the provisioner
96         provisioner, err := provisioners.New(issuer, password)
97         if err != nil {
98                 log.Error(err, "failed to initialize provisioner")
99                 statusReconciler.UpdateNoError(ctx, api.ConditionFalse, "Error", "failed initialize provisioner")
100                 return ctrl.Result{}, err
101         }
102         provisioners.Store(req.NamespacedName, provisioner)
103
104         log.Info( "CertServiceIssuer verified. Updating status to Verified...")
105         return ctrl.Result{}, statusReconciler.Update(ctx, api.ConditionTrue, "Verified", "CertServiceIssuer verified and ready to sign certificates")
106 }
107
108 // SetupWithManager initializes the CertServiceIssuer controller into the controller
109 // runtime.
110 func (reconciler *CertServiceIssuerReconciler) SetupWithManager(manager ctrl.Manager) error {
111         return ctrl.NewControllerManagedBy(manager).
112                 For(&api.CertServiceIssuer{}).
113                 Complete(reconciler)
114 }
115
116 func validateCertServiceIssuerSpec(issuerSpec api.CertServiceIssuerSpec) error {
117         switch {
118         case issuerSpec.URL == "":
119                 return fmt.Errorf("spec.url cannot be empty")
120         case issuerSpec.KeyRef.Name == "":
121                 return fmt.Errorf("spec.keyRef.name cannot be empty")
122         case issuerSpec.KeyRef.Key == "":
123                 return fmt.Errorf("spec.keyRef.key cannot be empty")
124         default:
125                 return nil
126         }
127 }