7d75a6554f68716d8df1422d30dd5eb73f3fa3c3
[oom/platform/cert-service.git] / certService / src / test / java / org / onap / oom / certservice / certification / CertificationProviderTest.java
1 /*
2  * ============LICENSE_START=======================================================
3  * OOM Certification Service
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 org.onap.oom.certservice.certification;
22
23 import java.io.StringReader;
24 import java.util.List;
25 import org.apache.commons.io.IOUtils;
26 import org.bouncycastle.cert.X509CertificateHolder;
27 import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
28 import org.bouncycastle.jce.provider.BouncyCastleProvider;
29 import org.bouncycastle.openssl.PEMParser;
30 import org.junit.jupiter.api.BeforeEach;
31 import org.junit.jupiter.api.Test;
32 import org.junit.jupiter.api.extension.ExtendWith;
33 import org.mockito.Mock;
34 import org.mockito.junit.jupiter.MockitoExtension;
35 import org.onap.oom.certservice.certification.configuration.model.Cmpv2Server;
36 import org.onap.oom.certservice.certification.model.CertificateUpdateModel;
37 import org.onap.oom.certservice.certification.model.CertificateUpdateModel.CertificateUpdateModelBuilder;
38 import org.onap.oom.certservice.certification.model.CertificationModel;
39 import org.onap.oom.certservice.certification.model.CsrModel;
40 import org.onap.oom.certservice.cmpv2client.api.CmpClient;
41 import org.onap.oom.certservice.cmpv2client.exceptions.CmpClientException;
42 import org.onap.oom.certservice.cmpv2client.model.Cmpv2CertificationModel;
43
44 import java.io.IOException;
45 import java.io.InputStream;
46 import java.nio.charset.StandardCharsets;
47 import java.security.NoSuchProviderException;
48 import java.security.cert.CertificateException;
49 import java.security.cert.X509Certificate;
50 import java.util.Collections;
51 import java.util.Objects;
52
53 import static org.assertj.core.api.Assertions.assertThat;
54 import static org.junit.jupiter.api.Assertions.assertThrows;
55 import static org.mockito.ArgumentMatchers.any;
56 import static org.mockito.Mockito.when;
57 import static org.onap.oom.certservice.certification.TestData.TEST_CMPv2_KEYSTORE;
58 import static org.onap.oom.certservice.certification.TestData.TEST_CMPv2_TRUSTSTORE;
59
60 @ExtendWith(MockitoExtension.class)
61 class CertificationProviderTest {
62
63     private static final int EXPECTED_SIZE_ONE = 1;
64     @Mock
65     private CsrModel csrModel;
66     @Mock
67     private Cmpv2Server server;
68     @Mock
69     private CsrModel testCsrModel;
70     @Mock
71     private Cmpv2Server testServer;
72     @Mock
73     private CmpClient cmpClient;
74
75     private CertificationProvider certificationProvider;
76
77     private static final CertificateUpdateModel TEST_CERTIFICATE_UPDATE_MODEL = new CertificateUpdateModelBuilder()
78         .setEncodedCsr("encodedCSR")
79         .setEncodedPrivateKey("encodedPK")
80         .setEncodedOldCert("encodedOldCert")
81         .setEncodedOldPrivateKey("encodedOldPK")
82         .setCaName("TestCA")
83         .build();
84     private static final String EXPECTED_BEGIN_OF_CERTIFICATE = "-----BEGIN CERTIFICATE-----\n";
85     private static final String EXPECTED_END_OF_CERTIFICATE = "-----END CERTIFICATE-----\n";
86
87     @BeforeEach
88     public void init() {
89         certificationProvider = new CertificationProvider(cmpClient);
90     }
91
92     @Test
93     void shouldConvertToCertificationModelForSignCsr()
94             throws CertificateException, NoSuchProviderException, IOException, CmpClientException {
95         // When
96         when(
97                 cmpClient.createCertificate(any(CsrModel.class), any(Cmpv2Server.class))
98         ).thenReturn(createCorrectClientResponse());
99
100         CertificationModel certificationModel = certificationProvider.signCsr(csrModel, server);
101
102         // Then
103         InputStream certificate = getClass().getClassLoader().getResourceAsStream("certificateModelChain.first");
104         InputStream trustedCertificate =
105                 getClass().getClassLoader().getResourceAsStream("trustedCertificatesModel.first");
106         String certificateModel = removeLineEndings(certificationModel.getCertificateChain().get(0));
107         String expectedCertificate =
108                 removeLineEndings(IOUtils.toString(Objects.requireNonNull(certificate), StandardCharsets.UTF_8));
109         String trustedCertificateModel = removeLineEndings(certificationModel.getTrustedCertificates().get(0));
110         String expectedTrustedCertificate =
111                 removeLineEndings(IOUtils.toString(Objects.requireNonNull(trustedCertificate), StandardCharsets.UTF_8));
112
113         assertThat(certificateModel).isEqualTo(expectedCertificate);
114         assertThat(trustedCertificateModel).isEqualTo(expectedTrustedCertificate);
115     }
116
117
118
119     @Test
120     void certificationProviderThrowCmpClientWhenCallingClientFailsForSignCsr()
121             throws CmpClientException {
122         // Given
123         String expectedErrorMessage = "connecting to CMP client failed";
124
125         when(
126                 cmpClient.createCertificate(any(CsrModel.class), any(Cmpv2Server.class))
127         ).thenThrow(new CmpClientException(expectedErrorMessage));
128
129         // When
130         Exception exception = assertThrows(
131                 CmpClientException.class, () ->
132                         certificationProvider.signCsr(testCsrModel, testServer)
133         );
134
135         // Then
136         assertThat(exception.getMessage()).isEqualTo(expectedErrorMessage);
137     }
138
139     @Test
140     void shouldCorrectConvertToCertificationModelForUpdateRequest()
141         throws IOException, CertificateException, CmpClientException {
142
143         // When
144         when(
145             cmpClient.updateCertificate(any(CsrModel.class), any(Cmpv2Server.class), any(CertificateUpdateModel.class))
146         ).thenReturn(getCMPv2CertificationModel());
147
148         CertificationModel certificationModel = certificationProvider
149             .updateCertificate(csrModel, server, TEST_CERTIFICATE_UPDATE_MODEL);
150         List<String> certificateChain = certificationModel.getCertificateChain();
151         List<String> trustedCertificates = certificationModel.getTrustedCertificates();
152
153         assertThat(certificateChain.size()).isEqualTo(EXPECTED_SIZE_ONE);
154         assertThat(certificateChain.get(0)).startsWith(EXPECTED_BEGIN_OF_CERTIFICATE);
155         assertThat(certificateChain.get(0)).endsWith(EXPECTED_END_OF_CERTIFICATE);
156
157         assertThat(trustedCertificates.size()).isEqualTo(EXPECTED_SIZE_ONE);
158         assertThat(trustedCertificates.get(0)).startsWith(EXPECTED_BEGIN_OF_CERTIFICATE);
159         assertThat(trustedCertificates.get(0)).endsWith(EXPECTED_END_OF_CERTIFICATE);
160     }
161
162     @Test
163     void shouldCorrectConvertToCertificationModelForCertificationRequest()
164         throws IOException, CertificateException, CmpClientException {
165
166         when(
167             cmpClient.certificationRequest(any(CsrModel.class), any(Cmpv2Server.class))
168         ).thenReturn(getCMPv2CertificationModel());
169
170         CertificationModel certificationModel = certificationProvider
171             .certificationRequest(csrModel, server);
172         List<String> certificateChain = certificationModel.getCertificateChain();
173         List<String> trustedCertificates = certificationModel.getTrustedCertificates();
174
175         assertThat(certificateChain.size()).isEqualTo(EXPECTED_SIZE_ONE);
176         assertThat(certificateChain.get(0)).startsWith(EXPECTED_BEGIN_OF_CERTIFICATE);
177         assertThat(certificateChain.get(0)).endsWith(EXPECTED_END_OF_CERTIFICATE);
178
179         assertThat(trustedCertificates.size()).isEqualTo(EXPECTED_SIZE_ONE);
180         assertThat(trustedCertificates.get(0)).startsWith(EXPECTED_BEGIN_OF_CERTIFICATE);
181         assertThat(trustedCertificates.get(0)).endsWith(EXPECTED_END_OF_CERTIFICATE);
182     }
183
184     @Test
185     void certificationProviderThrowCmpClientWhenCallingClientFailsForUpdateCertificate()
186         throws CmpClientException {
187         // Given
188         String expectedErrorMessage = "Exception occurred while send request to CMPv2 Server";
189
190         when(
191             cmpClient.updateCertificate(any(CsrModel.class), any(Cmpv2Server.class), any(CertificateUpdateModel.class))
192         ).thenThrow(new CmpClientException(expectedErrorMessage));
193
194         // When
195         Exception exception = assertThrows(
196             CmpClientException.class, () ->
197                 certificationProvider.updateCertificate(testCsrModel, testServer, TEST_CERTIFICATE_UPDATE_MODEL)
198         );
199
200         // Then
201         assertThat(exception.getMessage()).isEqualTo(expectedErrorMessage);
202     }
203
204
205     private Cmpv2CertificationModel createCorrectClientResponse()
206             throws CertificateException, NoSuchProviderException {
207         InputStream certificateChain = getClass().getClassLoader().getResourceAsStream("certificateChain.first");
208         InputStream trustedCertificate = getClass().getClassLoader().getResourceAsStream("trustedCertificates.first");
209         X509Certificate x509Certificate = new CertificateFactoryProvider().generateCertificate(certificateChain);
210         X509Certificate x509TrustedCertificate =
211                 new CertificateFactoryProvider().generateCertificate(trustedCertificate);
212         return new Cmpv2CertificationModel(
213                 Collections.singletonList(x509Certificate),
214                 Collections.singletonList(x509TrustedCertificate));
215     }
216
217     private String removeLineEndings(String string) {
218         return string.replace("\n", "").replace("\r", "");
219     }
220
221     private Cmpv2CertificationModel getCMPv2CertificationModel() throws IOException, CertificateException {
222         List<X509Certificate> certificateChain = getX509CertificateFromPem(TEST_CMPv2_KEYSTORE);
223         List<X509Certificate> trustedCertificates = getX509CertificateFromPem(TEST_CMPv2_TRUSTSTORE);
224         return new Cmpv2CertificationModel(certificateChain, trustedCertificates);
225     }
226
227
228     private List<X509Certificate> getX509CertificateFromPem(String pemString) throws IOException, CertificateException {
229         PEMParser pemParser = new PEMParser(new StringReader(pemString));
230         X509CertificateHolder certHolder = (X509CertificateHolder) pemParser.readObject();
231         X509Certificate x509Certificate = new JcaX509CertificateConverter()
232             .setProvider(new BouncyCastleProvider())
233             .getCertificate(certHolder);
234         return List.of(x509Certificate);
235     }
236 }