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
16 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
26 package cmpv2controller
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"
43 "onap.org/oom-certservice/k8s-external-provider/src/cmpv2api"
44 "onap.org/oom-certservice/k8s-external-provider/src/cmpv2controller/logger"
45 provisioners "onap.org/oom-certservice/k8s-external-provider/src/cmpv2provisioner"
49 privateKeySecretNameAnnotation = "cert-manager.io/private-key-secret-name"
50 privateKeySecretKey = "tls.key"
53 // CertificateRequestController reconciles a CMPv2Issuer object.
54 type CertificateRequestController struct {
57 Recorder record.EventRecorder
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 := controller.Log.WithValues("certificate-request-controller", k8sRequest.NamespacedName)
67 // 1. Fetch the CertificateRequest resource being reconciled.
68 certificateRequest := new(cmapi.CertificateRequest)
69 log.Info("Registered new certificate sign request: ", "cert-name", certificateRequest.Name)
70 if err := controller.Client.Get(ctx, k8sRequest.NamespacedName, certificateRequest); err != nil {
71 err = handleErrorResourceNotFound(log, err)
72 return ctrl.Result{}, err
75 // 2. Check if CertificateRequest is meant for CMPv2Issuer (if not ignore)
76 if !isCMPv2CertificateRequest(certificateRequest) {
77 log.Info("Certificate request is not meant for CMPv2Issuer (ignoring)",
78 "group", certificateRequest.Spec.IssuerRef.Group,
79 "kind", certificateRequest.Spec.IssuerRef.Kind)
80 return ctrl.Result{}, nil
83 // 3. If the certificate data is already set then we skip this request as it
84 // has already been completed in the past.
85 if len(certificateRequest.Status.Certificate) > 0 {
86 log.Info("Existing certificate data found in status, skipping already completed CertificateRequest")
87 return ctrl.Result{}, nil
90 // 4. Fetch the CMPv2Issuer resource
91 issuer := cmpv2api.CMPv2Issuer{}
92 issuerNamespaceName := types.NamespacedName{
93 Namespace: k8sRequest.Namespace,
94 Name: certificateRequest.Spec.IssuerRef.Name,
96 if err := controller.Client.Get(ctx, issuerNamespaceName, &issuer); err != nil {
97 controller.handleErrorGettingCMPv2Issuer(ctx, log, err, certificateRequest, issuerNamespaceName, k8sRequest)
98 return ctrl.Result{}, err
101 // 5. Check if CMPv2Issuer is ready to sing certificates
102 if !isCMPv2IssuerReady(issuer) {
103 err := controller.handleErrorCMPv2IssuerIsNotReady(ctx, log, issuerNamespaceName, certificateRequest, k8sRequest)
104 return ctrl.Result{}, err
107 // 6. Load the provisioner that will sign the CertificateRequest
108 provisioner, ok := provisioners.Load(issuerNamespaceName)
110 err := controller.handleErrorCouldNotLoadCMPv2Provisioner(ctx, log, issuerNamespaceName, certificateRequest)
111 return ctrl.Result{}, err
114 // 7. Get private key matching CertificateRequest
115 privateKeySecretName := certificateRequest.ObjectMeta.Annotations[privateKeySecretNameAnnotation]
116 privateKeySecretNamespaceName := types.NamespacedName{
117 Namespace: k8sRequest.Namespace,
118 Name: privateKeySecretName,
120 var privateKeySecret core.Secret
121 if err := controller.Client.Get(ctx, privateKeySecretNamespaceName, &privateKeySecret); err != nil {
122 controller.handleErrorGettingPrivateKey(ctx, log, err, certificateRequest, privateKeySecretNamespaceName)
123 return ctrl.Result{}, err
125 privateKeyBytes := privateKeySecret.Data[privateKeySecretKey]
127 // 8. Log Certificate Request properties not supported or overridden by CertService API
128 logger.LogCertRequestProperties(ctrl.Log.WithName("CSR details"), certificateRequest)
130 // 9. Sign CertificateRequest
131 signedPEM, trustedCAs, err := provisioner.Sign(ctx, certificateRequest, privateKeyBytes)
133 controller.handleErrorFailedToSignCertificate(ctx, log, err, certificateRequest)
134 return ctrl.Result{}, err
137 // 10. Store signed certificates in CertificateRequest
138 certificateRequest.Status.Certificate = signedPEM
139 certificateRequest.Status.CA = trustedCAs
140 if err := controller.updateCertificateRequestWithSignedCerficates(ctx, certificateRequest); err != nil {
141 return ctrl.Result{}, err
144 return ctrl.Result{}, nil
147 func (controller *CertificateRequestController) updateCertificateRequestWithSignedCerficates(ctx context.Context, certificateRequest *cmapi.CertificateRequest) error {
148 return controller.setStatus(ctx, certificateRequest, cmmeta.ConditionTrue, cmapi.CertificateRequestReasonIssued, "Certificate issued")
151 func (controller *CertificateRequestController) SetupWithManager(manager ctrl.Manager) error {
152 return ctrl.NewControllerManagedBy(manager).
153 For(&cmapi.CertificateRequest{}).
157 func (controller *CertificateRequestController) setStatus(ctx context.Context, certificateRequest *cmapi.CertificateRequest, status cmmeta.ConditionStatus, reason, message string, args ...interface{}) error {
158 completeMessage := fmt.Sprintf(message, args...)
159 apiutil.SetCertificateRequestCondition(certificateRequest, cmapi.CertificateRequestConditionReady, status, reason, completeMessage)
161 // Fire an Event to additionally inform users of the change
162 eventType := core.EventTypeNormal
163 if status == cmmeta.ConditionFalse {
164 eventType = core.EventTypeWarning
166 controller.Recorder.Event(certificateRequest, eventType, reason, completeMessage)
168 return controller.Client.Status().Update(ctx, certificateRequest)
171 func isCMPv2IssuerReady(issuer cmpv2api.CMPv2Issuer) bool {
172 condition := cmpv2api.CMPv2IssuerCondition{Type: cmpv2api.ConditionReady, Status: cmpv2api.ConditionTrue}
173 return hasCondition(issuer, condition)
176 func hasCondition(issuer cmpv2api.CMPv2Issuer, condition cmpv2api.CMPv2IssuerCondition) bool {
177 existingConditions := issuer.Status.Conditions
178 for _, cond := range existingConditions {
179 if condition.Type == cond.Type && condition.Status == cond.Status {
186 func isCMPv2CertificateRequest(certificateRequest *cmapi.CertificateRequest) bool {
187 return certificateRequest.Spec.IssuerRef.Group != "" &&
188 certificateRequest.Spec.IssuerRef.Group == cmpv2api.GroupVersion.Group &&
189 certificateRequest.Spec.IssuerRef.Kind == cmpv2api.CMPv2IssuerKind
195 func (controller *CertificateRequestController) handleErrorCouldNotLoadCMPv2Provisioner(ctx context.Context, log logr.Logger, issuerNamespaceName types.NamespacedName, certificateRequest *cmapi.CertificateRequest) error {
196 err := fmt.Errorf("provisioner %s not found", issuerNamespaceName)
197 log.Error(err, "Failed to load CMPv2 Provisioner resource")
198 _ = controller.setStatus(ctx, certificateRequest, cmmeta.ConditionFalse, cmapi.CertificateRequestReasonPending, "Failed to load provisioner for CMPv2Issuer resource %s", issuerNamespaceName)
202 func (controller *CertificateRequestController) handleErrorCMPv2IssuerIsNotReady(ctx context.Context, log logr.Logger, issuerNamespaceName types.NamespacedName, certificateRequest *cmapi.CertificateRequest, req ctrl.Request) error {
203 err := fmt.Errorf("resource %s is not ready", issuerNamespaceName)
204 log.Error(err, "CMPv2Issuer not ready", "namespace", req.Namespace, "name", certificateRequest.Spec.IssuerRef.Name)
205 _ = controller.setStatus(ctx, certificateRequest, cmmeta.ConditionFalse, cmapi.CertificateRequestReasonPending, "CMPv2Issuer resource %s is not Ready", issuerNamespaceName)
209 func (controller *CertificateRequestController) handleErrorGettingCMPv2Issuer(ctx context.Context, log logr.Logger, err error, certificateRequest *cmapi.CertificateRequest, issuerNamespaceName types.NamespacedName, req ctrl.Request) {
210 log.Error(err, "Failed to retrieve CMPv2Issuer resource", "namespace", req.Namespace, "name", certificateRequest.Spec.IssuerRef.Name)
211 _ = controller.setStatus(ctx, certificateRequest, cmmeta.ConditionFalse, cmapi.CertificateRequestReasonPending, "Failed to retrieve CMPv2Issuer resource %s: %v", issuerNamespaceName, err)
214 func (controller *CertificateRequestController) handleErrorGettingPrivateKey(ctx context.Context, log logr.Logger, err error, certificateRequest *cmapi.CertificateRequest, pkSecretNamespacedName types.NamespacedName) {
215 log.Error(err, "Failed to retrieve private key secret for certificate request", "namespace", pkSecretNamespacedName.Namespace, "name", pkSecretNamespacedName.Name)
216 _ = controller.setStatus(ctx, certificateRequest, cmmeta.ConditionFalse, cmapi.CertificateRequestReasonPending, "Failed to retrieve private key secret: %v", err)
219 func (controller *CertificateRequestController) handleErrorFailedToSignCertificate(ctx context.Context, log logr.Logger, err error, certificateRequest *cmapi.CertificateRequest) {
220 log.Error(err, "Failed to sign certificate request")
221 _ = controller.setStatus(ctx, certificateRequest, cmmeta.ConditionFalse, cmapi.CertificateRequestReasonFailed, "Failed to sign certificate request: %v", err)
224 func handleErrorResourceNotFound(log logr.Logger, err error) error {
225 if apierrors.IsNotFound(err) {
226 log.Error(err, "CertificateRequest resource not found")
228 log.Error(err, "Failed to retrieve CertificateRequest resource")