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