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