31f2bc265cf8c41018a9586bfcf0f0b75f4e07ba
[oom/platform/cert-service.git] / certServiceK8sExternalProvider / src / cmpv2provisioner / cmpv2_provisioner_test.go
1 /*
2  * ============LICENSE_START=======================================================
3  * oom-certservice-k8s-external-provider
4  * ================================================================================
5  * Copyright (C) 2020 Nokia. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package cmpv2provisioner
22
23 import (
24         "bytes"
25         "context"
26         "io/ioutil"
27         "log"
28         "testing"
29         "time"
30
31         cmapi "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1"
32         "github.com/stretchr/testify/assert"
33         apimach "k8s.io/apimachinery/pkg/apis/meta/v1"
34         "k8s.io/apimachinery/pkg/types"
35
36         "onap.org/oom-certservice/k8s-external-provider/src/certserviceclient"
37         "onap.org/oom-certservice/k8s-external-provider/src/cmpv2api"
38 )
39
40 const ISSUER_NAME = "cmpv2-issuer"
41 const ISSUER_URL = "issuer/url"
42 const ISSUER_NAMESPACE = "onap"
43
44 func Test_shouldCreateCorrectCertServiceCA(t *testing.T) {
45         issuer := createIssuerAndCerts(ISSUER_NAME, ISSUER_URL)
46         provisioner, err := New(&issuer, &certServiceClientMock{})
47
48         assert.Nil(t, err)
49         assert.Equal(t, provisioner.name, issuer.Name, "Unexpected provisioner name.")
50         assert.Equal(t, provisioner.url, issuer.Spec.URL, "Unexpected provisioner url.")
51 }
52
53 func Test_shouldSuccessfullyLoadPreviouslyStoredProvisioner(t *testing.T) {
54         issuer := createIssuerAndCerts(ISSUER_NAME, ISSUER_URL)
55         provisioner, err := New(&issuer, &certServiceClientMock{})
56
57         assert.Nil(t, err)
58
59         issuerNamespaceName := createIssuerNamespaceName(ISSUER_NAMESPACE, ISSUER_NAME)
60
61         Store(issuerNamespaceName, provisioner)
62         provisioner, ok := Load(issuerNamespaceName)
63
64         verifyThatConditionIsTrue(ok, "Provisioner could not be loaded.", t)
65         assert.Equal(t, provisioner.name, issuer.Name, "Unexpected provisioner name.")
66         assert.Equal(t, provisioner.url, issuer.Spec.URL, "Unexpected provisioner url.")
67 }
68
69 func Test_shouldReturnCorrectSignedPemsWhenParametersAreCorrect(t *testing.T) {
70         const EXPECTED_SIGNED_FILENAME = "testdata/expected_signed.pem"
71         const EXPECTED_TRUSTED_FILENAME = "testdata/expected_trusted.pem"
72
73         issuer := createIssuerAndCerts(ISSUER_NAME, ISSUER_URL)
74         provisioner, err := New(&issuer, &certServiceClientMock{
75                 getCertificatesFunc: func(csr []byte, pk []byte) (response *certserviceclient.CertificatesResponse, e error) {
76                         mockResponse:= &certserviceclient.CertificatesResponse{
77                                 CertificateChain:    []string{"cert-0", "cert-1"},
78                                 TrustedCertificates: []string{"trusted-cert-0", "trusted-cert-1"},
79                         } //TODO: mock real certServiceClient response
80                         return mockResponse, nil
81                 },
82         })
83
84         issuerNamespaceName := createIssuerNamespaceName(ISSUER_NAMESPACE, ISSUER_NAME)
85         Store(issuerNamespaceName, provisioner)
86
87         provisioner, ok := Load(issuerNamespaceName)
88
89         verifyThatConditionIsTrue(ok, "Provisioner could not be loaded", t)
90
91         ctx := context.Background()
92         request := createCertificateRequest()
93
94         signedPEM, trustedCAs, err := provisioner.Sign(ctx, request, nil)
95
96         assert.Nil(t, err)
97
98         verifyThatConditionIsTrue(areSlicesEqual(signedPEM, readFile(EXPECTED_SIGNED_FILENAME)), "Signed pem is different than expected.", t)
99         verifyThatConditionIsTrue(areSlicesEqual(trustedCAs, readFile(EXPECTED_TRUSTED_FILENAME)), "Trusted CAs pem is different than expected.", t)
100 }
101
102 func verifyThatConditionIsTrue(cond bool, message string, t *testing.T) {
103         if !cond {
104                 t.Fatal(message)
105         }
106 }
107
108 func createIssuerNamespaceName(namespace string, name string) types.NamespacedName {
109         return types.NamespacedName{
110                 Namespace: namespace,
111                 Name:      name,
112         }
113 }
114
115 func createIssuerAndCerts(name string, url string) cmpv2api.CMPv2Issuer {
116         issuer := cmpv2api.CMPv2Issuer{}
117         issuer.Name = name
118         issuer.Spec.URL = url
119         return issuer
120 }
121
122 func readFile(filename string) []byte {
123         certRequest, err := ioutil.ReadFile(filename)
124         if err != nil {
125                 log.Fatal(err)
126         }
127         return certRequest
128 }
129
130 func createCertificateRequest() *cmapi.CertificateRequest {
131         const CERTIFICATE_DURATION = "1h"
132         const ISSUER_KIND = "CMPv2Issuer"
133         const ISSUER_GROUP = "certmanager.onap.org"
134         const CONDITION_TYPE = "Ready"
135
136         const SPEC_REQUEST_FILENAME = "testdata/test_certificate_request.pem"
137         const STATUS_CERTIFICATE_FILENAME = "testdata/test_certificate.pem"
138
139         duration := new(apimach.Duration)
140         d, _ := time.ParseDuration(CERTIFICATE_DURATION)
141         duration.Duration = d
142
143         request := new(cmapi.CertificateRequest)
144         request.Spec.Duration = duration
145         request.Spec.IssuerRef.Name = ISSUER_NAME
146         request.Spec.IssuerRef.Kind = ISSUER_KIND
147         request.Spec.IssuerRef.Group = ISSUER_GROUP
148         request.Spec.Request = readFile(SPEC_REQUEST_FILENAME)
149         request.Spec.IsCA = true
150
151         cond := new(cmapi.CertificateRequestCondition)
152         cond.Type = CONDITION_TYPE
153         request.Status.Conditions = []cmapi.CertificateRequestCondition{*cond}
154         request.Status.Certificate = readFile(STATUS_CERTIFICATE_FILENAME)
155
156         return request
157 }
158
159 func areSlicesEqual(slice1 []byte, slice2 []byte) bool {
160         return bytes.Compare(slice1, slice2) == 0
161 }
162
163 type certServiceClientMock struct {
164         getCertificatesFunc func(csr []byte, key []byte) (*certserviceclient.CertificatesResponse, error)
165 }
166
167 func (client *certServiceClientMock) GetCertificates(csr []byte, key []byte) (*certserviceclient.CertificatesResponse, error) {
168         return client.getCertificatesFunc(csr, key)
169 }
170
171 func (client *certServiceClientMock) CheckHealth() error {
172         return nil
173 }
174