[OOM-K8S-CERT-EXTERNAL-PROVIDER] Add client for CertService API
[oom/platform/cert-service.git] / certServiceK8sExternalProvider / src / cmpv2controller / certificate_request_controller.go
1 /*
2  * ============LICENSE_START=======================================================
3  * oom-certservice-k8s-external-provider
4  * ================================================================================
5  * Copyright 2019 The cert-manager authors.
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
32         "github.com/go-logr/logr"
33         apiutil "github.com/jetstack/cert-manager/pkg/api/util"
34         cmapi "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1"
35         cmmeta "github.com/jetstack/cert-manager/pkg/apis/meta/v1"
36         core "k8s.io/api/core/v1"
37         apierrors "k8s.io/apimachinery/pkg/api/errors"
38         "k8s.io/apimachinery/pkg/types"
39         "k8s.io/client-go/tools/record"
40         ctrl "sigs.k8s.io/controller-runtime"
41         "sigs.k8s.io/controller-runtime/pkg/client"
42
43         "onap.org/oom-certservice/k8s-external-provider/src/cmpv2api"
44         provisioners "onap.org/oom-certservice/k8s-external-provider/src/cmpv2provisioner"
45 )
46
47 const (
48         privateKeySecretNameAnnotation = "cert-manager.io/private-key-secret-name"
49         privateKeySecretKey = "tls.key"
50 )
51
52 // CertificateRequestController reconciles a CMPv2Issuer object.
53 type CertificateRequestController struct {
54         client.Client
55         Log      logr.Logger
56         Recorder record.EventRecorder
57 }
58
59 // Reconcile will read and validate a CMPv2Issuer resource associated to the
60 // CertificateRequest resource, and it will sign the CertificateRequest with the
61 // provisioner in the CMPv2Issuer.
62 func (controller *CertificateRequestController) Reconcile(k8sRequest ctrl.Request) (ctrl.Result, error) {
63         ctx := context.Background()
64         log := controller.Log.WithValues("certificate-request-controller", k8sRequest.NamespacedName)
65
66         // 1. Fetch the CertificateRequest resource being reconciled.
67         certificateRequest := new(cmapi.CertificateRequest)
68         if err := controller.Client.Get(ctx, k8sRequest.NamespacedName, certificateRequest); err != nil {
69                 err = handleErrorResourceNotFound(log, err)
70                 return ctrl.Result{}, err
71         }
72
73         // 2. Check if CertificateRequest is meant for CMPv2Issuer (if not ignore)
74         if !isCMPv2CertificateRequest(certificateRequest) {
75                 log.V(4).Info("Certificate request is not meant for CMPv2Issuer (ignoring)",
76                         "group", certificateRequest.Spec.IssuerRef.Group,
77                         "kind", certificateRequest.Spec.IssuerRef.Kind)
78                 return ctrl.Result{}, nil
79         }
80
81         // 3. If the certificate data is already set then we skip this request as it
82         // has already been completed in the past.
83         if len(certificateRequest.Status.Certificate) > 0 {
84                 log.V(4).Info("Existing certificate data found in status, skipping already completed CertificateRequest")
85                 return ctrl.Result{}, nil
86         }
87
88         // 4. Fetch the CMPv2Issuer resource
89         issuer := cmpv2api.CMPv2Issuer{}
90         issuerNamespaceName := types.NamespacedName{
91                 Namespace: k8sRequest.Namespace,
92                 Name:      certificateRequest.Spec.IssuerRef.Name,
93         }
94         if err := controller.Client.Get(ctx, issuerNamespaceName, &issuer); err != nil {
95                 controller.handleErrorGettingCMPv2Issuer(ctx, log, err, certificateRequest, issuerNamespaceName, k8sRequest)
96                 return ctrl.Result{}, err
97         }
98
99         // 5. Check if CMPv2Issuer is ready to sing certificates
100         if !isCMPv2IssuerReady(issuer) {
101                 err := controller.handleErrorCMPv2IssuerIsNotReady(ctx, log, issuerNamespaceName, certificateRequest, k8sRequest)
102                 return ctrl.Result{}, err
103         }
104
105         // 6. Load the provisioner that will sign the CertificateRequest
106         provisioner, ok := provisioners.Load(issuerNamespaceName)
107         if !ok {
108                 err := controller.handleErrorCouldNotLoadCMPv2Provisioner(ctx, log, issuerNamespaceName, certificateRequest)
109                 return ctrl.Result{}, err
110         }
111
112         // 7. Get private key matching CertificateRequest
113         privateKeySecretName := certificateRequest.ObjectMeta.Annotations[privateKeySecretNameAnnotation]
114         privateKeySecretNamespaceName := types.NamespacedName{
115                 Namespace: k8sRequest.Namespace,
116                 Name:      privateKeySecretName,
117         }
118         var privateKeySecret core.Secret
119         if err := controller.Client.Get(ctx, privateKeySecretNamespaceName, &privateKeySecret); err != nil {
120                 controller.handleErrorGettingPrivateKey(ctx, log, err, certificateRequest, privateKeySecretNamespaceName)
121                 return ctrl.Result{}, err
122         }
123         privateKeyBytes := privateKeySecret.Data[privateKeySecretKey]
124
125         // 8. Sign CertificateRequest
126         signedPEM, trustedCAs, err := provisioner.Sign(ctx, certificateRequest, privateKeyBytes)
127         if err != nil {
128                 controller.handleErrorFailedToSignCertificate(ctx, log, err, certificateRequest)
129                 return ctrl.Result{}, err
130         }
131
132         // 9. Store signed certificates in CertificateRequest
133         certificateRequest.Status.Certificate = signedPEM
134         certificateRequest.Status.CA = trustedCAs
135         if err := controller.updateCertificateRequestWithSignedCerficates(ctx, certificateRequest); err != nil {
136                 return ctrl.Result{}, err
137         }
138
139         return ctrl.Result{}, nil
140 }
141
142 func (controller *CertificateRequestController) updateCertificateRequestWithSignedCerficates(ctx context.Context, certificateRequest *cmapi.CertificateRequest) error {
143         return controller.setStatus(ctx, certificateRequest, cmmeta.ConditionTrue, cmapi.CertificateRequestReasonIssued, "Certificate issued")
144 }
145
146 func (controller *CertificateRequestController) SetupWithManager(manager ctrl.Manager) error {
147         return ctrl.NewControllerManagedBy(manager).
148                 For(&cmapi.CertificateRequest{}).
149                 Complete(controller)
150 }
151
152 func (controller *CertificateRequestController) setStatus(ctx context.Context, certificateRequest *cmapi.CertificateRequest, status cmmeta.ConditionStatus, reason, message string, args ...interface{}) error {
153         completeMessage := fmt.Sprintf(message, args...)
154         apiutil.SetCertificateRequestCondition(certificateRequest, cmapi.CertificateRequestConditionReady, status, reason, completeMessage)
155
156         // Fire an Event to additionally inform users of the change
157         eventType := core.EventTypeNormal
158         if status == cmmeta.ConditionFalse {
159                 eventType = core.EventTypeWarning
160         }
161         controller.Recorder.Event(certificateRequest, eventType, reason, completeMessage)
162
163         return controller.Client.Status().Update(ctx, certificateRequest)
164 }
165
166 func isCMPv2IssuerReady(issuer cmpv2api.CMPv2Issuer) bool {
167         condition := cmpv2api.CMPv2IssuerCondition{Type: cmpv2api.ConditionReady, Status: cmpv2api.ConditionTrue}
168         return hasCondition(issuer, condition)
169 }
170
171 func hasCondition(issuer cmpv2api.CMPv2Issuer, condition cmpv2api.CMPv2IssuerCondition) bool {
172         existingConditions := issuer.Status.Conditions
173         for _, cond := range existingConditions {
174                 if condition.Type == cond.Type && condition.Status == cond.Status {
175                         return true
176                 }
177         }
178         return false
179 }
180
181 func isCMPv2CertificateRequest(certificateRequest *cmapi.CertificateRequest) bool {
182         return certificateRequest.Spec.IssuerRef.Group != "" &&
183                 certificateRequest.Spec.IssuerRef.Group == cmpv2api.GroupVersion.Group &&
184                 certificateRequest.Spec.IssuerRef.Kind == cmpv2api.CMPv2IssuerKind
185
186 }
187
188 // Error handling
189
190 func (controller *CertificateRequestController) handleErrorCouldNotLoadCMPv2Provisioner(ctx context.Context, log logr.Logger, issuerNamespaceName types.NamespacedName, certificateRequest *cmapi.CertificateRequest) error {
191         err := fmt.Errorf("provisioner %s not found", issuerNamespaceName)
192         log.Error(err, "Failed to load CMPv2 Provisioner resource")
193         _ = controller.setStatus(ctx, certificateRequest, cmmeta.ConditionFalse, cmapi.CertificateRequestReasonPending, "Failed to load provisioner for CMPv2Issuer resource %s", issuerNamespaceName)
194         return err
195 }
196
197 func (controller *CertificateRequestController) handleErrorCMPv2IssuerIsNotReady(ctx context.Context, log logr.Logger, issuerNamespaceName types.NamespacedName, certificateRequest *cmapi.CertificateRequest, req ctrl.Request) error {
198         err := fmt.Errorf("resource %s is not ready", issuerNamespaceName)
199         log.Error(err, "CMPv2Issuer not ready", "namespace", req.Namespace, "name", certificateRequest.Spec.IssuerRef.Name)
200         _ = controller.setStatus(ctx, certificateRequest, cmmeta.ConditionFalse, cmapi.CertificateRequestReasonPending, "CMPv2Issuer resource %s is not Ready", issuerNamespaceName)
201         return err
202 }
203
204 func (controller *CertificateRequestController) handleErrorGettingCMPv2Issuer(ctx context.Context, log logr.Logger, err error, certificateRequest *cmapi.CertificateRequest, issuerNamespaceName types.NamespacedName, req ctrl.Request) {
205         log.Error(err, "Failed to retrieve CMPv2Issuer resource", "namespace", req.Namespace, "name", certificateRequest.Spec.IssuerRef.Name)
206         _ = controller.setStatus(ctx, certificateRequest, cmmeta.ConditionFalse, cmapi.CertificateRequestReasonPending, "Failed to retrieve CMPv2Issuer resource %s: %v", issuerNamespaceName, err)
207 }
208
209 func (controller *CertificateRequestController) handleErrorGettingPrivateKey(ctx context.Context, log logr.Logger, err error, certificateRequest *cmapi.CertificateRequest, pkSecretNamespacedName types.NamespacedName) {
210         log.Error(err, "Failed to retrieve private key secret for certificate request", "namespace", pkSecretNamespacedName.Namespace, "name", pkSecretNamespacedName.Name)
211         _ = controller.setStatus(ctx, certificateRequest, cmmeta.ConditionFalse, cmapi.CertificateRequestReasonPending, "Failed to retrieve private key secret: %v", err)
212 }
213
214 func (controller *CertificateRequestController) handleErrorFailedToSignCertificate(ctx context.Context, log logr.Logger, err error, certificateRequest *cmapi.CertificateRequest) {
215         log.Error(err, "Failed to sign certificate request")
216         _ = controller.setStatus(ctx, certificateRequest, cmmeta.ConditionFalse, cmapi.CertificateRequestReasonFailed, "Failed to sign certificate request: %v", err)
217 }
218
219 func handleErrorResourceNotFound(log logr.Logger, err error) error {
220         if apierrors.IsNotFound(err) {
221                 log.Error(err, "CertificateRequest resource not found")
222         } else {
223                 log.Error(err, "Failed to retrieve CertificateRequest resource")
224         }
225         return err
226 }