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