c0304d7dd88b000f68fc8b2c73dd87cbd9c8adf7
[oom/platform/cert-service.git] / certServiceK8sExternalProvider / src / cmpv2provisioner / cmpv2_provisioner.go
1 /*
2  * ============LICENSE_START=======================================================
3  * oom-certservice-k8s-external-provider
4  * ================================================================================
5  * Copyright (c) 2019 Smallstep Labs, Inc.
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 cmpv2provisioner
27
28 import (
29         "bytes"
30         "context"
31         "crypto/x509"
32         "encoding/pem"
33         "fmt"
34         "sync"
35
36         certmanager "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1"
37         "k8s.io/apimachinery/pkg/types"
38         ctrl "sigs.k8s.io/controller-runtime"
39
40         "onap.org/oom-certservice/k8s-external-provider/src/certserviceclient"
41         "onap.org/oom-certservice/k8s-external-provider/src/cmpv2api"
42 )
43
44 var collection = new(sync.Map)
45
46 type CertServiceCA struct {
47         name              string
48         url               string
49         healthEndpoint    string
50         certEndpoint      string
51         caName            string
52         certServiceClient certserviceclient.CertServiceClient
53 }
54
55 func New(cmpv2Issuer *cmpv2api.CMPv2Issuer, certServiceClient certserviceclient.CertServiceClient) (*CertServiceCA, error) {
56
57         ca := CertServiceCA{}
58         ca.name = cmpv2Issuer.Name
59         ca.url = cmpv2Issuer.Spec.URL
60         ca.caName = cmpv2Issuer.Spec.CaName
61         ca.healthEndpoint = cmpv2Issuer.Spec.HealthEndpoint
62         ca.certEndpoint = cmpv2Issuer.Spec.CertEndpoint
63         ca.certServiceClient = certServiceClient
64
65         log := ctrl.Log.WithName("cmpv2-provisioner")
66         log.Info("Configuring CA: ", "name", ca.name, "url", ca.url, "caName", ca.caName, "healthEndpoint", ca.healthEndpoint, "certEndpoint", ca.certEndpoint)
67
68         return &ca, nil
69 }
70
71 func (ca *CertServiceCA) CheckHealth() error {
72         log := ctrl.Log.WithName("cmpv2-provisioner")
73         log.Info("Checking health of CMPv2 issuer: ", "name", ca.name)
74         return ca.certServiceClient.CheckHealth()
75 }
76
77 func Load(namespacedName types.NamespacedName) (*CertServiceCA, bool) {
78         provisioner, ok := collection.Load(namespacedName)
79         if !ok {
80                 return nil, ok
81         }
82         certServiceCAprovisioner, ok := provisioner.(*CertServiceCA)
83         return certServiceCAprovisioner, ok
84 }
85
86 func Store(namespacedName types.NamespacedName, provisioner *CertServiceCA) {
87         collection.Store(namespacedName, provisioner)
88 }
89
90 func (ca *CertServiceCA) Sign(ctx context.Context, certificateRequest *certmanager.CertificateRequest, privateKeyBytes []byte) ([]byte, []byte, error) {
91         log := ctrl.Log.WithName("certservice-provisioner")
92         log.Info("Signing certificate: ", "cert-name", certificateRequest.Name)
93
94         log.Info("CA: ", "name", ca.name, "url", ca.url)
95
96         csrBytes := certificateRequest.Spec.Request
97         log.Info("Csr PEM: ", "bytes", csrBytes)
98
99         csr, err := decodeCSR(csrBytes)
100         if err != nil {
101                 return nil, nil, err
102         }
103
104         response, err := ca.certServiceClient.GetCertificates(csrBytes, privateKeyBytes)
105         if err != nil {
106                 return nil, nil, err
107         }
108         log.Info("Certificate Chain", "cert-chain", response.CertificateChain)
109         log.Info("Trusted Certificates", "trust-certs", response.TrustedCertificates)
110
111
112         // TODO
113         // stored response as PEM
114         cert := x509.Certificate{}
115         cert.Raw = csr.Raw
116         encodedPEM, err := encodeX509(&cert)
117         if err != nil {
118                 return nil, nil, err
119         }
120         // END
121
122         signedPEM := encodedPEM
123         trustedCA := encodedPEM
124
125         log.Info("Signed cert PEM: ", "bytes", signedPEM)
126         log.Info("Trusted CA  PEM: ", "bytes", trustedCA)
127         log.Info("Successfully signed: ", "cert-name", certificateRequest.Name)
128
129         return signedPEM, trustedCA, nil
130 }
131
132 // decodeCSR decodes a certificate request in PEM format and returns the
133 func decodeCSR(data []byte) (*x509.CertificateRequest, error) {
134         block, rest := pem.Decode(data)
135         if block == nil || len(rest) > 0 {
136                 return nil, fmt.Errorf("unexpected CSR PEM on sign request")
137         }
138         if block.Type != "CERTIFICATE REQUEST" {
139                 return nil, fmt.Errorf("PEM is not a certificate request")
140         }
141         csr, err := x509.ParseCertificateRequest(block.Bytes)
142         if err != nil {
143                 return nil, fmt.Errorf("error parsing certificate request: %v", err)
144         }
145         if err := csr.CheckSignature(); err != nil {
146                 return nil, fmt.Errorf("error checking certificate request signature: %v", err)
147         }
148         return csr, nil
149 }
150
151 // encodeX509 will encode a *x509.Certificate into PEM format.
152 func encodeX509(cert *x509.Certificate) ([]byte, error) {
153         caPem := bytes.NewBuffer([]byte{})
154         err := pem.Encode(caPem, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
155         if err != nil {
156                 return nil, err
157         }
158         return caPem.Bytes(), nil
159 }