Merge "[OOM-K8S-CERT-EXTERNAL-PROVIDER] Format golang code"
[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 certificationProviderThrowCmpClientWhenCallingClientFailsForUpdateCertificate()
164         throws CmpClientException {
165         // Given
166         String expectedErrorMessage = "Exception occurred while send request to CMPv2 Server";
167
168         when(
169             cmpClient.updateCertificate(any(CsrModel.class), any(Cmpv2Server.class), any(CertificateUpdateModel.class))
170         ).thenThrow(new CmpClientException(expectedErrorMessage));
171
172         // When
173         Exception exception = assertThrows(
174             CmpClientException.class, () ->
175                 certificationProvider.updateCertificate(testCsrModel, testServer, TEST_CERTIFICATE_UPDATE_MODEL)
176         );
177
178         // Then
179         assertThat(exception.getMessage()).isEqualTo(expectedErrorMessage);
180     }
181
182
183     private Cmpv2CertificationModel createCorrectClientResponse()
184             throws CertificateException, NoSuchProviderException {
185         InputStream certificateChain = getClass().getClassLoader().getResourceAsStream("certificateChain.first");
186         InputStream trustedCertificate = getClass().getClassLoader().getResourceAsStream("trustedCertificates.first");
187         X509Certificate x509Certificate = new CertificateFactoryProvider().generateCertificate(certificateChain);
188         X509Certificate x509TrustedCertificate =
189                 new CertificateFactoryProvider().generateCertificate(trustedCertificate);
190         return new Cmpv2CertificationModel(
191                 Collections.singletonList(x509Certificate),
192                 Collections.singletonList(x509TrustedCertificate));
193     }
194
195     private String removeLineEndings(String string) {
196         return string.replace("\n", "").replace("\r", "");
197     }
198
199     private Cmpv2CertificationModel getCMPv2CertificationModel() throws IOException, CertificateException {
200         List<X509Certificate> certificateChain = getX509CertificateFromPem(TEST_CMPv2_KEYSTORE);
201         List<X509Certificate> trustedCertificates = getX509CertificateFromPem(TEST_CMPv2_TRUSTSTORE);
202         return new Cmpv2CertificationModel(certificateChain, trustedCertificates);
203     }
204
205
206     private List<X509Certificate> getX509CertificateFromPem(String pemString) throws IOException, CertificateException {
207         PEMParser pemParser = new PEMParser(new StringReader(pemString));
208         X509CertificateHolder certHolder = (X509CertificateHolder) pemParser.readObject();
209         X509Certificate x509Certificate = new JcaX509CertificateConverter()
210             .setProvider(new BouncyCastleProvider())
211             .getCertificate(certHolder);
212         return List.of(x509Certificate);
213     }
214 }