[OOM-CERT-SERVICE] Refactor CertService API code
[oom/platform/cert-service.git] / certService / src / test / java / org / onap / oom / certservice / certification / model / CsrModelTest.java
1 /*
2  * ============LICENSE_START=======================================================
3  * PROJECT
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.model;
22
23 import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
24 import org.bouncycastle.pkcs.PKCS10CertificationRequest;
25 import org.bouncycastle.util.io.pem.PemObject;
26 import org.junit.jupiter.api.Test;
27 import org.onap.oom.certservice.certification.TestData;
28 import org.onap.oom.certservice.certification.conversion.PemObjectFactory;
29 import org.onap.oom.certservice.certification.conversion.Pkcs10CertificationRequestFactory;
30 import org.onap.oom.certservice.certification.exception.CsrDecryptionException;
31 import org.onap.oom.certservice.certification.exception.DecryptionException;
32 import org.onap.oom.certservice.certification.exception.KeyDecryptionException;
33
34 import java.io.IOException;
35 import java.security.KeyFactory;
36 import java.security.NoSuchAlgorithmException;
37 import java.security.PrivateKey;
38 import java.security.spec.InvalidKeySpecException;
39 import java.security.spec.PKCS8EncodedKeySpec;
40 import java.util.Arrays;
41 import java.util.List;
42 import java.util.stream.Collectors;
43
44 import static org.assertj.core.api.Assertions.assertThat;
45 import static org.junit.jupiter.api.Assertions.assertThrows;
46 import static org.junit.jupiter.api.Assertions.assertTrue;
47 import static org.mockito.Mockito.mock;
48 import static org.mockito.Mockito.when;
49 import static org.onap.oom.certservice.certification.TestData.LOCALHOST_IP_IN_HEX;
50 import static org.onap.oom.certservice.certification.TestData.TEST_CSR;
51 import static org.onap.oom.certservice.certification.TestData.TEST_PEM;
52 import static org.onap.oom.certservice.certification.TestData.TEST_PK;
53
54
55 class CsrModelTest {
56
57     private final Pkcs10CertificationRequestFactory certificationRequestFactory
58         = new Pkcs10CertificationRequestFactory();
59     private final PemObjectFactory pemObjectFactory
60         = new PemObjectFactory();
61
62     @Test
63     void shouldByConstructedAndReturnProperFields() throws DecryptionException, IOException {
64         // Given
65         PrivateKey testPrivateKey = getPemPrivateKey();
66         PemObject testPublicKey = generateTestPublicKey();
67         PKCS10CertificationRequest testCsr = generateTestCertificationRequest();
68
69         // When
70         CsrModel csrModel = generateTestCsrModel(testCsr);
71         List<String> sansList = Arrays.stream(csrModel.getSans())
72             .map(generalName ->  generalName.getName().toString())
73             .collect(Collectors.toList());
74         // Then
75         assertThat(csrModel.getCsr())
76             .isEqualTo(testCsr);
77         assertThat(csrModel.getPrivateKey().getEncoded())
78             .isEqualTo(testPrivateKey.getEncoded());
79         assertThat(csrModel.getPublicKey().getEncoded())
80             .contains(testPublicKey.getContent());
81         assertThat(sansList)
82             .contains("localhost", "onap.org", "test.onap.org", "onap@onap.org", LOCALHOST_IP_IN_HEX,
83                 "onap://cluster.local/");
84
85         assertThat(csrModel.getSubjectData().toString())
86             .contains(TestData.EXPECTED_CERT_SUBJECT);
87     }
88
89     @Test
90     void shouldThrowExceptionWhenPublicKeyIsNotCorrect() throws DecryptionException, IOException {
91         // Given
92         PrivateKey testPrivateKey = getPemPrivateKey();
93         PKCS10CertificationRequest testCsr = mock(PKCS10CertificationRequest.class);
94         SubjectPublicKeyInfo wrongKryInfo = mock(SubjectPublicKeyInfo.class);
95         when(testCsr.getSubjectPublicKeyInfo())
96             .thenReturn(wrongKryInfo);
97         when(wrongKryInfo.getEncoded())
98             .thenThrow(new IOException());
99
100         // When
101         Exception exception = assertThrows(
102             CsrDecryptionException.class,
103             () -> new CsrModel.CsrModelBuilder(testCsr, testPrivateKey).build()
104         );
105
106         String expectedMessage = "Reading Public Key from CSR failed";
107         String actualMessage = exception.getMessage();
108
109         // Then
110         assertTrue(actualMessage.contains(expectedMessage));
111     }
112
113     @Test
114     void shouldThrowExceptionWhenPublicKeyPemIsNotProperPublicKey() throws KeyDecryptionException, IOException {
115         // Given
116         PrivateKey testPrivateKey = getPemPrivateKey();
117         PemObject testPublicKey = getPemWrongKey();
118         PKCS10CertificationRequest testCsr = mock(PKCS10CertificationRequest.class);
119         SubjectPublicKeyInfo wrongKryInfo = mock(SubjectPublicKeyInfo.class);
120         when(testCsr.getSubjectPublicKeyInfo())
121             .thenReturn(wrongKryInfo);
122         when(wrongKryInfo.getEncoded())
123             .thenReturn(testPublicKey.getContent());
124
125         // When
126         Exception exception = assertThrows(
127             KeyDecryptionException.class,
128             () -> new CsrModel.CsrModelBuilder(testCsr, testPrivateKey).build()
129         );
130
131         String expectedMessage = "Converting Public Key from CSR failed";
132         String actualMessage = exception.getMessage();
133
134         // Then
135         assertTrue(actualMessage.contains(expectedMessage));
136     }
137
138     private PrivateKey getPemPrivateKey() throws KeyDecryptionException {
139         PemObjectFactory pemObjectFactory = new PemObjectFactory();
140         PemObject pemObject = pemObjectFactory.createPemObject(TEST_PK).orElseThrow(
141                 () -> new KeyDecryptionException("Private key decoding fail")
142         );
143         return convertToPrivateKey(pemObject);
144     }
145
146     private PemObject getPemWrongKey() throws KeyDecryptionException {
147         PemObjectFactory pemObjectFactory = new PemObjectFactory();
148         return pemObjectFactory.createPemObject(TEST_PEM).orElseThrow(
149             () -> new KeyDecryptionException("Private key decoding fail")
150         );
151     }
152
153     private CsrModel generateTestCsrModel(PKCS10CertificationRequest testCsr) throws DecryptionException {
154         PemObject testPrivateKey = pemObjectFactory.createPemObject(TEST_PK).orElseThrow(
155             () -> new DecryptionException("Incorrect Private Key, decryption failed")
156         );
157         return new CsrModel.CsrModelBuilder(testCsr, convertToPrivateKey(testPrivateKey)).build();
158     }
159
160     private PemObject generateTestPublicKey() throws DecryptionException, IOException {
161         PKCS10CertificationRequest testCsr = generateTestCertificationRequest();
162         return new PemObject("PUBLIC KEY", testCsr.getSubjectPublicKeyInfo().getEncoded());
163     }
164
165     private PKCS10CertificationRequest generateTestCertificationRequest() throws DecryptionException {
166         return pemObjectFactory.createPemObject(TEST_CSR)
167             .flatMap(
168                 certificationRequestFactory::createPkcs10CertificationRequest
169             ).orElseThrow(
170                 () -> new DecryptionException("Incorrect CSR, decryption failed")
171             );
172     }
173
174     private PrivateKey convertToPrivateKey(PemObject privateKey)
175             throws KeyDecryptionException {
176         try {
177             KeyFactory factory = KeyFactory.getInstance("RSA");
178             PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey.getContent());
179             return factory.generatePrivate(keySpec);
180         } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
181             throw new KeyDecryptionException("Converting Private Key failed", e.getCause());
182         }
183     }
184
185 }