e1c6bb9167ce381d6a6927c6670f92835d4fcf38
[oom/platform/cert-service.git] / certServiceK8sExternalProvider / src / certserviceclient / cert_service_client_test.go
1 /*
2  * ============LICENSE_START=======================================================
3  * oom-certservice-k8s-external-provider
4  * ================================================================================
5  * Copyright (C) 2020-2021 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 certserviceclient
22
23 import (
24         "bytes"
25         "fmt"
26         "io"
27         "io/ioutil"
28         "net/http"
29         "testing"
30
31         "github.com/stretchr/testify/assert"
32
33         "onap.org/oom-certservice/k8s-external-provider/src/model"
34         "onap.org/oom-certservice/k8s-external-provider/src/testdata"
35 )
36
37 const (
38         certificationUrl     = "https://oom-cert-service:8443/v1/certificate/RA"
39         certificateUpdateUrl = "https://oom-cert-service:8443/v1/certificate-update/RA"
40 )
41
42 func Test_GetCertificates_shouldParseCertificateResponseCorrectly(t *testing.T) {
43         responseJson := `{"certificateChain": ["cert-0", "cert-1"], "trustedCertificates": ["trusted-cert-0", "trusted-cert-1"]}`
44         responseJsonReader := ioutil.NopCloser(bytes.NewReader([]byte(responseJson)))
45         client := CertServiceClientImpl{
46                 certificationUrl: certificationUrl,
47                 httpClient:       getMockedClient(responseJsonReader, http.StatusOK),
48         }
49         response, _ := client.GetCertificates(testdata.CsrBytes, testdata.PkBytes)
50         assert.ElementsMatch(t, []string{"cert-0", "cert-1"}, response.CertificateChain)
51         assert.ElementsMatch(t, []string{"trusted-cert-0", "trusted-cert-1"}, response.TrustedCertificates)
52 }
53
54 func Test_GetCertificates_shouldReturnError_whenResponseIsNotJson(t *testing.T) {
55         responseJson := `not a json`
56         responseJsonReader := ioutil.NopCloser(bytes.NewReader([]byte(responseJson)))
57         client := CertServiceClientImpl{
58                 certificationUrl: certificationUrl,
59                 httpClient: &httpClientMock{
60                         DoFunc: func(req *http.Request) (response *http.Response, e error) {
61                                 mockedResponse := &http.Response{
62                                         Body: responseJsonReader,
63                                 }
64                                 return mockedResponse, nil
65                         },
66                 },
67         }
68         response, err := client.GetCertificates(testdata.CsrBytes, testdata.PkBytes)
69
70         assert.Nil(t, response)
71         assert.Error(t, err)
72 }
73
74 func Test_GetCertificates_shouldReturnError_whenHttpClientReturnsError(t *testing.T) {
75         client := CertServiceClientImpl{
76                 certificationUrl: certificationUrl,
77                 httpClient: &httpClientMock{
78                         DoFunc: func(req *http.Request) (response *http.Response, err error) {
79                                 return nil, fmt.Errorf("mock error")
80                         },
81                 },
82         }
83         response, err := client.GetCertificates(testdata.CsrBytes, testdata.PkBytes)
84
85         assert.Nil(t, response)
86         assert.Error(t, err)
87 }
88
89 func Test_GetCertificates_shouldReturnError_whenResponseOtherThan200(t *testing.T) {
90         responseJson := `{"errorMessage": "CertService API error"}`
91         responseJsonReader := ioutil.NopCloser(bytes.NewReader([]byte(responseJson)))
92         client := CertServiceClientImpl{
93                 certificationUrl: certificationUrl,
94                 httpClient:       getMockedClient(responseJsonReader, http.StatusNotFound),
95         }
96         response, err := client.GetCertificates(testdata.CsrBytes, testdata.PkBytes)
97
98         assert.Nil(t, response)
99         assert.Error(t, err)
100 }
101
102 func Test_UpdateCertificates_shouldParseCertificateResponseCorrectly(t *testing.T) {
103         responseJson := `{"certificateChain": ["cert-0", "cert-1"], "trustedCertificates": ["trusted-cert-0", "trusted-cert-1"]}`
104         responseJsonReader := ioutil.NopCloser(bytes.NewReader([]byte(responseJson)))
105         client := CertServiceClientImpl{
106                 updateUrl:  certificateUpdateUrl,
107                 httpClient: getMockedClient(responseJsonReader, http.StatusOK),
108         }
109
110         response, _ := client.UpdateCertificate(testdata.CsrBytes, testdata.PkBytes, getTestSignCertificateModel())
111         assert.ElementsMatch(t, []string{"cert-0", "cert-1"}, response.CertificateChain)
112         assert.ElementsMatch(t, []string{"trusted-cert-0", "trusted-cert-1"}, response.TrustedCertificates)
113 }
114
115
116 func Test_UpdateCertificates_shouldReturnError_whenHttpClientReturnsError(t *testing.T) {
117         client := CertServiceClientImpl{
118                 updateUrl: certificateUpdateUrl,
119                 httpClient: &httpClientMock{
120                         DoFunc: func(req *http.Request) (response *http.Response, err error) {
121                                 return nil, fmt.Errorf("mock error")
122                         },
123                 },
124         }
125         response, err := client.UpdateCertificate(testdata.CsrBytes, testdata.PkBytes, getTestSignCertificateModel())
126
127         assert.Nil(t, response)
128         assert.Error(t, err)
129 }
130
131 func Test_UpdateCertificates_shouldReturnError_whenResponseOtherThan200(t *testing.T) {
132         responseJson := `{"errorMessage": "CertService API error"}`
133         responseJsonReader := ioutil.NopCloser(bytes.NewReader([]byte(responseJson)))
134         client := CertServiceClientImpl{
135                 updateUrl:  updateEndpoint,
136                 httpClient: getMockedClient(responseJsonReader, http.StatusNotFound),
137         }
138         response, err := client.UpdateCertificate(testdata.CsrBytes, testdata.PkBytes, getTestSignCertificateModel())
139
140         assert.Nil(t, response)
141         assert.Error(t, err)
142 }
143
144 func Test_CheckHealth_shouldReturnNil_whenHttpClientReturnsStatusCode200(t *testing.T) {
145         client := CertServiceClientImpl{
146                 certificationUrl: certificationUrl,
147                 httpClient: &httpClientMock{
148                         DoFunc: func(req *http.Request) (response *http.Response, e error) {
149                                 mockedResponse := &http.Response{
150                                         Body:       nil,
151                                         StatusCode: 200,
152                                 }
153                                 return mockedResponse, nil
154                         },
155                 },
156         }
157
158         err := client.CheckHealth()
159
160         assert.Nil(t, err)
161 }
162
163 func Test_CheckHealth_shouldReturnError_whenHttpClientReturnsStatusCode404(t *testing.T) {
164         client := CertServiceClientImpl{
165                 certificationUrl: certificationUrl,
166                 httpClient: &httpClientMock{
167                         DoFunc: func(req *http.Request) (response *http.Response, e error) {
168                                 mockedResponse := &http.Response{
169                                         Body:       nil,
170                                         StatusCode: 404,
171                                 }
172                                 return mockedResponse, nil
173                         },
174                 },
175         }
176
177         err := client.CheckHealth()
178
179         assert.Error(t, err)
180 }
181
182 func Test_CheckHealth_shouldReturnError_whenHttpClientReturnsError(t *testing.T) {
183         client := CertServiceClientImpl{
184                 certificationUrl: certificationUrl,
185                 httpClient: &httpClientMock{
186                         DoFunc: func(req *http.Request) (response *http.Response, err error) {
187                                 return nil, fmt.Errorf("mock error")
188                         },
189                 },
190         }
191         err := client.CheckHealth()
192
193         assert.Error(t, err)
194 }
195
196 func getMockedClient(responseJsonReader io.ReadCloser, responseCode int) *httpClientMock {
197         return &httpClientMock{
198                 DoFunc: func(req *http.Request) (response *http.Response, e error) {
199                         mockedResponse := &http.Response{
200                                 Body:       responseJsonReader,
201                                 StatusCode: responseCode,
202                         }
203                         return mockedResponse, nil
204                 },
205         }
206 }
207
208 type httpClientMock struct {
209         DoFunc func(*http.Request) (*http.Response, error)
210 }
211
212 func (client httpClientMock) Do(req *http.Request) (*http.Response, error) {
213         return client.DoFunc(req)
214 }
215
216 func getTestSignCertificateModel() model.SignCertificateModel {
217         testSignCertificateModel := model.SignCertificateModel{
218                 OldCertificate: testdata.OldCertificateEncoded,
219                 OldPrivateKey:  testdata.OldPrivateKeyEncoded,
220         }
221         return testSignCertificateModel
222 }