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