[OOM-K8S-CERT-EXTERNAL-PROVIDER] Add client for CertService API
[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/base64"
33         "encoding/pem"
34         "fmt"
35         "sync"
36
37         certmanager "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1"
38         "k8s.io/apimachinery/pkg/types"
39         ctrl "sigs.k8s.io/controller-runtime"
40
41         "onap.org/oom-certservice/k8s-external-provider/src/certserviceclient"
42         "onap.org/oom-certservice/k8s-external-provider/src/cmpv2api"
43 )
44
45 var collection = new(sync.Map)
46
47 type CertServiceCA struct {
48         name              string
49         url               string
50         caName            string
51         certServiceClient certserviceclient.CertServiceClient
52 }
53
54 func New(cmpv2Issuer *cmpv2api.CMPv2Issuer, certServiceClient certserviceclient.CertServiceClient) (*CertServiceCA, error) {
55
56         ca := CertServiceCA{}
57         ca.name = cmpv2Issuer.Name
58         ca.url = cmpv2Issuer.Spec.URL
59         ca.caName = cmpv2Issuer.Spec.CaName
60         ca.certServiceClient = certServiceClient
61
62         log := ctrl.Log.WithName("cmpv2-provisioner")
63         log.Info("Configuring CA: ", "name", ca.name, "url", ca.url, "caName", ca.caName)
64
65         return &ca, nil
66 }
67
68 func Load(namespacedName types.NamespacedName) (*CertServiceCA, bool) {
69         provisioner, ok := collection.Load(namespacedName)
70         if !ok {
71                 return nil, ok
72         }
73         certServiceCAprovisioner, ok := provisioner.(*CertServiceCA)
74         return certServiceCAprovisioner, ok
75 }
76
77 func Store(namespacedName types.NamespacedName, provisioner *CertServiceCA) {
78         collection.Store(namespacedName, provisioner)
79 }
80
81 func (ca *CertServiceCA) Sign(ctx context.Context, certificateRequest *certmanager.CertificateRequest, privateKeyBytes []byte) ([]byte, []byte, error) {
82         log := ctrl.Log.WithName("certservice-provisioner")
83         log.Info("Signing certificate: ", "cert-name", certificateRequest.Name)
84
85         log.Info("CA: ", "name", ca.name, "url", ca.url)
86
87         csrBytes := certificateRequest.Spec.Request
88         log.Info("Csr PEM: ", "bytes", csrBytes)
89
90         csr, err := decodeCSR(csrBytes)
91         if err != nil {
92                 return nil, nil, err
93         }
94
95         response, err := ca.certServiceClient.GetCertificates(csrBytes, privateKeyBytes)
96         if err != nil {
97                 return nil, nil, err
98         }
99         log.Info("Certificate Chain", "cert-chain", response.CertificateChain)
100         log.Info("Trusted Certificates", "trust-certs", response.TrustedCertificates)
101
102         cert := x509.Certificate{}
103         cert.Raw = csr.Raw
104
105         // TODO
106         // write here code which will call CertServiceCA and sign CSR
107         // END
108
109         encodedPEM, err := encodeX509(&cert)
110         if err != nil {
111                 return nil, nil, err
112         }
113
114         signedPEM := encodedPEM
115         trustedCA := encodedPEM
116
117         log.Info("Successfully signed: ", "cert-name", certificateRequest.Name)
118         log.Info("Signed cert PEM: ", "bytes", signedPEM)
119         log.Info("Trusted CA  PEM: ", "bytes", trustedCA)
120
121         return signedPEM, trustedCA, nil
122 }
123
124 // TODO JM utility methods - will be used in "real" implementation
125
126 // decodeCSR decodes a certificate request in PEM format and returns the
127 func decodeCSR(data []byte) (*x509.CertificateRequest, error) {
128         block, rest := pem.Decode(data)
129         if block == nil || len(rest) > 0 {
130                 return nil, fmt.Errorf("unexpected CSR PEM on sign request")
131         }
132         if block.Type != "CERTIFICATE REQUEST" {
133                 return nil, fmt.Errorf("PEM is not a certificate request")
134         }
135         csr, err := x509.ParseCertificateRequest(block.Bytes)
136         if err != nil {
137                 return nil, fmt.Errorf("error parsing certificate request: %v", err)
138         }
139         if err := csr.CheckSignature(); err != nil {
140                 return nil, fmt.Errorf("error checking certificate request signature: %v", err)
141         }
142         return csr, nil
143 }
144
145 // encodeX509 will encode a *x509.Certificate into PEM format.
146 func encodeX509(cert *x509.Certificate) ([]byte, error) {
147         caPem := bytes.NewBuffer([]byte{})
148         err := pem.Encode(caPem, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
149         if err != nil {
150                 return nil, err
151         }
152         return caPem.Bytes(), nil
153 }
154
155 // generateSubject returns the first SAN that is not 127.0.0.1 or localhost. The
156 // CSRs generated by the Certificate resource have always those SANs. If no SANs
157 // are available `certservice-issuer-certificate` will be used as a subject is always
158 // required.
159 func generateSubject(sans []string) string {
160         if len(sans) == 0 {
161                 return "certservice-issuer-certificate"
162         }
163         for _, s := range sans {
164                 if s != "127.0.0.1" && s != "localhost" {
165                         return s
166                 }
167         }
168         return sans[0]
169 }
170
171 func decode(cert string) []byte {
172         bytes, _ := base64.RawStdEncoding.DecodeString(cert)
173         return bytes
174 }