aboutsummaryrefslogtreecommitdiffstats
path: root/certService/src/test/java/org/onap/aaf/certservice/cmpv2client/Cmpv2ClientTest.java
blob: 05bda54bf41b8919d5aa4f2e6b5e326f3c89fef7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/*
 * Copyright (C) 2019 Ericsson Software Technology AB. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

package org.onap.aaf.certservice.cmpv2client;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x500.X500NameBuilder;
import org.bouncycastle.asn1.x500.style.BCStyle;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.onap.aaf.certservice.certification.configuration.model.Authentication;
import org.onap.aaf.certservice.certification.configuration.model.Cmpv2Server;
import org.onap.aaf.certservice.certification.model.CsrModel;
import org.onap.aaf.certservice.cmpv2client.exceptions.CmpClientException;
import org.onap.aaf.certservice.cmpv2client.impl.CmpClientImpl;
import org.onap.aaf.certservice.cmpv2client.model.Cmpv2CertificationModel;

class Cmpv2ClientTest {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    private CsrModel csrModel;
    private Cmpv2Server server;
    private Date notBefore;
    private Date notAfter;
    private X500Name dn;

    @Mock
    X509Certificate cert;

    @Mock
    CloseableHttpClient httpClient;

    @Mock
    CloseableHttpResponse httpResponse;

    @Mock
    HttpEntity httpEntity;

    private static KeyPair keyPair;

    @BeforeEach
    void setUp()
            throws NoSuchProviderException, NoSuchAlgorithmException, IOException,
            InvalidKeySpecException {
        keyPair = loadKeyPair();
        dn = new X500NameBuilder()
                .addRDN(BCStyle.O, "TestOrganization")
                .build();
        initMocks(this);
    }

    public KeyPair loadKeyPair()
            throws IOException, NoSuchAlgorithmException, InvalidKeySpecException,
            NoSuchProviderException {

        final InputStream privateInputStream = this.getClass().getResourceAsStream("/privateKey");
        final InputStream publicInputStream = this.getClass().getResourceAsStream("/publicKey");
        BufferedInputStream bis = new BufferedInputStream(privateInputStream);
        byte[] privateBytes = IOUtils.toByteArray(bis);
        bis = new BufferedInputStream(publicInputStream);
        byte[] publicBytes = IOUtils.toByteArray(bis);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicBytes);
        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateBytes);
        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

        return new KeyPair(publicKey, privateKey);
    }

    @Test
    void shouldReturnValidPkiMessageWhenCreateCertificateRequestMessageMethodCalledWithValidCsr()
            throws Exception {
        // given
        Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00");
        Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00");
        setCsrModelAndServerValues(
                "mypassword",
                "senderKID",
                "http://127.0.0.1/ejbca/publicweb/cmp/cmp",
                beforeDate,
                afterDate);
        when(httpClient.execute(any())).thenReturn(httpResponse);
        when(httpResponse.getEntity()).thenReturn(httpEntity);

        try (final InputStream is =
                     this.getClass().getResourceAsStream("/ReturnedSuccessPKIMessageWithCertificateFile");
             BufferedInputStream bis = new BufferedInputStream(is)) {

            byte[] ba = IOUtils.toByteArray(bis);
            doAnswer(
                    invocation -> {
                        OutputStream os = (ByteArrayOutputStream) invocation.getArguments()[0];
                        os.write(ba);
                        return null;
                    })
                    .when(httpEntity)
                    .writeTo(any(OutputStream.class));
        }
        CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient));
        // when
        Cmpv2CertificationModel cmpClientResult =
                cmpClient.createCertificate(csrModel, server, notBefore, notAfter);
        // then
        assertNotNull(cmpClientResult);
    }

    @Test
    void
    shouldThrowCmpClientExceptionWhenCreateCertificateRequestMessageMethodCalledWithWrongProtectedBytesInResponse()
            throws Exception {
        // given
        Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00");
        Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00");
        setCsrModelAndServerValues(
                "password",
                "senderKID",
                "http://127.0.0.1/ejbca/publicweb/cmp/cmp",
                beforeDate,
                afterDate);
        when(httpClient.execute(any())).thenReturn(httpResponse);
        when(httpResponse.getEntity()).thenReturn(httpEntity);

        try (final InputStream is =
                     this.getClass().getResourceAsStream("/ReturnedSuccessPKIMessageWithCertificateFile");
             BufferedInputStream bis = new BufferedInputStream(is)) {

            byte[] ba = IOUtils.toByteArray(bis);
            doAnswer(
                    invocation -> {
                        OutputStream os = (ByteArrayOutputStream) invocation.getArguments()[0];
                        os.write(ba);
                        return null;
                    })
                    .when(httpEntity)
                    .writeTo(any(OutputStream.class));
        }
        CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient));
        // then
        Assertions.assertThrows(
                CmpClientException.class,
                () -> cmpClient.createCertificate(csrModel, server, notBefore, notAfter));
    }

    @Test
    void shouldThrowCmpClientExceptionWithPkiErrorExceptionWhenCmpClientCalledWithBadPassword()
            throws Exception {
        // given
        Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00");
        Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00");
        setCsrModelAndServerValues(
                "password",
                "senderKID",
                "http://127.0.0.1/ejbca/publicweb/cmp/cmp",
                beforeDate,
                afterDate);
        when(httpClient.execute(any())).thenReturn(httpResponse);
        when(httpResponse.getEntity()).thenReturn(httpEntity);

        try (final InputStream is =
                     this.getClass().getResourceAsStream("/ReturnedFailurePKIMessageBadPassword");
             BufferedInputStream bis = new BufferedInputStream(is)) {

            byte[] ba = IOUtils.toByteArray(bis);
            doAnswer(
                    invocation -> {
                        OutputStream os = (ByteArrayOutputStream) invocation.getArguments()[0];
                        os.write(ba);
                        return null;
                    })
                    .when(httpEntity)
                    .writeTo(any(OutputStream.class));
        }
        CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient));

        // then
        Assertions.assertThrows(
                CmpClientException.class,
                () -> cmpClient.createCertificate(csrModel, server, notBefore, notAfter));
    }

    @Test
    void shouldThrowIllegalArgumentExceptionWhencreateCertificateCalledWithInvalidCsr()
            throws ParseException {
        // given
        Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00");
        Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00");
        setCsrModelAndServerValues(
                "password",
                "senderKID",
                "http://127.0.0.1/ejbca/publicweb/cmp/cmp",
                beforeDate,
                afterDate);
        CmpClientImpl cmpClient = new CmpClientImpl(httpClient);
        // then
        Assertions.assertThrows(
                IllegalArgumentException.class,
                () -> cmpClient.createCertificate(csrModel, server, notBefore, notAfter));
    }

    @Test
    void shouldThrowIoExceptionWhenCreateCertificateCalledWithNoServerAvailable()
            throws IOException, ParseException {
        // given
        Date beforeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2019/11/11 12:00:00");
        Date afterDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse("2020/11/11 12:00:00");
        setCsrModelAndServerValues(
                "myPassword",
                "sender",
                "http://127.0.0.1/ejbca/publicweb/cmp/cmpTest",
                beforeDate,
                afterDate);
        when(httpClient.execute(any())).thenThrow(IOException.class);
        CmpClientImpl cmpClient = spy(new CmpClientImpl(httpClient));
        // then
        Assertions.assertThrows(
                CmpClientException.class,
                () -> cmpClient.createCertificate(csrModel, server, notBefore, notAfter));
    }

    private void setCsrModelAndServerValues(String iak, String rv, String externalCaUrl, Date notBefore, Date notAfter) {
        csrModel = new CsrModel(null, dn, keyPair.getPrivate(), keyPair.getPublic(), Collections.emptyList());

        Authentication authentication = new Authentication();
        authentication.setIak(iak);
        authentication.setRv(rv);
        server = new Cmpv2Server();
        server.setAuthentication(authentication);
        server.setUrl(externalCaUrl);
        server.setIssuerDN(dn);
        this.notBefore = notBefore;
        this.notAfter = notAfter;
    }
}