Fix sonar issues
[aai/babel.git] / src / test / java / org / onap / aai / babel / service / TestGenerateArtifactsServiceImpl.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright (c) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * Copyright (c) 2017-2019 European Software Marketing Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.aai.babel.service;
23
24 import static org.hamcrest.CoreMatchers.containsString;
25 import static org.hamcrest.Matchers.is;
26 import static org.junit.Assert.assertThat;
27
28 import com.google.gson.Gson;
29 import java.io.IOException;
30 import java.net.URI;
31 import java.net.URISyntaxException;
32 import java.security.cert.X509Certificate;
33 import java.util.Collections;
34 import java.util.List;
35 import java.util.Map.Entry;
36 import java.util.Optional;
37 import javax.inject.Inject;
38 import javax.security.auth.x500.X500Principal;
39 import javax.ws.rs.core.HttpHeaders;
40 import javax.ws.rs.core.MultivaluedHashMap;
41 import javax.ws.rs.core.Response;
42 import javax.ws.rs.core.UriInfo;
43 import org.junit.BeforeClass;
44 import org.junit.Ignore;
45 import org.junit.Test;
46 import org.junit.runner.RunWith;
47 import org.junit.runners.Parameterized;
48 import org.mockito.Mockito;
49 import org.onap.aai.auth.AAIAuthException;
50 import org.onap.aai.auth.AAIMicroServiceAuth;
51 import org.onap.aai.babel.service.data.BabelRequest;
52 import org.onap.aai.babel.testdata.CsarTest;
53 import org.onap.aai.babel.util.ArtifactTestUtils;
54 import org.springframework.mock.web.MockHttpServletRequest;
55 import org.springframework.test.context.ContextConfiguration;
56 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
57
58 /**
59  * Direct invocation of the generate artifacts service implementation.
60  *
61  */
62 @RunWith(SpringJUnit4ClassRunner.class)
63 @ContextConfiguration(locations = {"classpath:/babel-beans.xml"})
64 public class TestGenerateArtifactsServiceImpl {
65
66     static {
67         System.setProperty("CONFIG_HOME", "src/test/resources");
68     }
69
70     @Inject
71     private AAIMicroServiceAuth auth;
72
73     @BeforeClass
74     public static void setup() {
75         new ArtifactTestUtils().setGeneratorSystemProperties();
76     }
77
78     /**
79      * Test with a valid request (and valid CSAR content) by calling the Service implementation directly using a mocked
80      * HTTPS request.
81      *
82      * @throws URISyntaxException
83      *             if the URI cannot be created
84      * @throws IOException
85      *             if the resource cannot be loaded
86      */
87     @Test
88     public void testGenerateArtifacts() throws URISyntaxException, IOException {
89         Response response = processJsonRequest(CsarTest.VNF_VENDOR_CSAR, auth);
90         assertThat(response.toString(), response.getStatus(), is(Response.Status.OK.getStatusCode()));
91         assertThat(response.getEntity(), is(getResponseJson("response.json")));
92     }
93
94     /**
95      * Test with a valid request that has no Transaction ID header value.
96      *
97      * @throws URISyntaxException
98      *             if the URI cannot be created
99      * @throws IOException
100      *             if the resource cannot be loaded
101      */
102     @Test
103     public void testGenerateArtifactsWithoutRequestId() throws URISyntaxException, IOException {
104         Response response = invokeService(CsarTest.VNF_VENDOR_CSAR.getJsonRequest(), Optional.empty(), auth);
105         assertThat(response.toString(), response.getStatus(), is(Response.Status.OK.getStatusCode()));
106         assertThat(response.getEntity(), is(getResponseJson("response.json")));
107     }
108     
109     /**
110      * Test with a valid request without Minor Artifact version.
111      *
112      * @throws URISyntaxException
113      *             if the URI cannot be created
114      * @throws IOException
115      *             if the resource cannot be loaded
116      */
117     @Test
118     public void testGenerateArtifactsWithoutMinorArtifactVersion() throws URISyntaxException, IOException {
119         Response response = invokeService(CsarTest.VNF_VENDOR_CSAR.getJsonRequestWithArtifactVersion("1"),
120                         Optional.of("transaction-id"), auth);
121         assertThat(response.toString(), response.getStatus(), is(Response.Status.OK.getStatusCode()));
122         assertThat(response.getEntity(), is(getResponseJson("response.json")));
123     }
124     
125     /**
126      * Test with a valid request without Minor Artifact version.
127      *
128      * @throws URISyntaxException
129      *             if the URI cannot be created
130      * @throws IOException
131      *             if the resource cannot be loaded
132      */
133     @Test
134     public void testGenerateArtifactsWithInvalidArtifactVersion() throws URISyntaxException, IOException {
135         Response response = invokeService(CsarTest.VNF_VENDOR_CSAR.getJsonRequestWithArtifactVersion("a"),
136                         Optional.of("transaction-id"), auth);
137         assertThat(response.toString(), response.getStatus(), is(Response.Status.OK.getStatusCode()));
138         assertThat(response.getEntity(), is(getResponseJson("response.json")));
139     }
140     
141     
142     /**
143      * Test with a valid request with Artifact version less than 1.
144      *
145      * @throws URISyntaxException
146      *             if the URI cannot be created
147      * @throws IOException
148      *             if the resource cannot be loaded
149      */
150     @Test
151     public void testGenerateArtifactsWithArtifactVerLessThan1() throws URISyntaxException, IOException {
152         Response response = invokeService(CsarTest.VNF_VENDOR_CSAR.getJsonRequestWithArtifactVersion("0.1"),
153                         Optional.of("transaction-id"), auth);
154         assertThat(response.toString(), response.getStatus(), is(Response.Status.OK.getStatusCode()));
155         assertThat(response.getEntity(), is(getResponseJson("responseWithVersionLessThan1.json")));
156     }
157
158
159     /**
160      * Test with a valid request, using a CSAR file that has no VNF configuration present.
161      *
162      * @throws URISyntaxException
163      *             if the URI cannot be created
164      * @throws IOException
165      *             if the resource cannot be loaded
166      */
167     @Test
168     public void testGenerateArtifactsWithoutVnfConfiguration() throws IOException, URISyntaxException {
169         Response response = processJsonRequest(CsarTest.NO_VNF_CONFIG_CSAR, auth);
170         assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
171         assertThat(response.getEntity(), is(getResponseJson("validNoVnfConfigurationResponse.json")));
172     }
173
174     /**
175      * Test for a valid request with invalid CSAR file content.
176      *
177      * @throws URISyntaxException
178      *             if the URI cannot be created
179      * @throws IOException
180      *             if the resource cannot be loaded
181      */
182     @Test
183     public void testGenerateArtifactsInvalidCsar() throws IOException, URISyntaxException {
184         Response response = processJsonRequest(CsarTest.MULTIPLE_VNF_CSAR, auth);
185         assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
186         assertThat(response.getEntity().toString(), containsString("VNF catalog"));
187     }
188
189     @Test
190     public void testUninitializedService() throws IOException, URISyntaxException, AAIAuthException {
191         AAIMicroServiceAuth uninitializedAuth = Mockito.mock(AAIMicroServiceAuth.class);
192         Mockito.when(uninitializedAuth.validateRequest(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
193                 .thenThrow(new AAIAuthException("test"));
194         Response response = processJsonRequest(CsarTest.NO_VNF_CONFIG_CSAR, uninitializedAuth);
195         assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
196         assertThat(response.getEntity().toString(), containsString("check the Babel service logs"));
197     }
198
199     @Test
200     public void testUnauthorizedRequest() throws IOException, URISyntaxException, AAIAuthException {
201         AAIMicroServiceAuth uninitializedAuth = Mockito.mock(AAIMicroServiceAuth.class);
202         Mockito.when(uninitializedAuth.validateRequest(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
203                 .thenReturn(false);
204         Response response = processJsonRequest(CsarTest.NO_VNF_CONFIG_CSAR, uninitializedAuth);
205         assertThat(response.getStatus(), is(Response.Status.UNAUTHORIZED.getStatusCode()));
206         assertThat(response.getEntity().toString(), containsString("User not authorized"));
207     }
208
209     @Test
210     public void testInvalidCsarFile() throws URISyntaxException, IOException {
211         BabelRequest request = new BabelRequest();
212         request.setArtifactName("hello");
213         request.setArtifactVersion("1.0");
214         request.setCsar("xxxx");
215         Response response = invokeService(new Gson().toJson(request));
216         assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
217         assertThat(response.getEntity(), is("Error converting CSAR artifact to XML model."));
218     }
219
220     @Test
221     public void testInvalidJsonFile() throws URISyntaxException, IOException {
222         Response response = invokeService("{\"csar:\"xxxx\"");
223         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
224         assertThat(response.getEntity(), is("Malformed request."));
225     }
226
227     @Test
228     public void testMissingArtifactName() throws Exception {
229         BabelRequest request = new BabelRequest();
230         request.setArtifactVersion("1.0");
231         request.setCsar("");
232         Response response = invokeService(new Gson().toJson(request));
233         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
234         assertThat(response.getEntity(), is("No artifact name attribute found in the request body."));
235     }
236
237     @Test
238     public void testMissingArtifactVersion() throws Exception {
239         BabelRequest request = new BabelRequest();
240         request.setArtifactName("hello");
241         request.setCsar("");
242         Response response = invokeService(new Gson().toJson(request));
243         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
244         assertThat(response.getEntity(), is("No artifact version attribute found in the request body."));
245     }
246
247     @Test
248     public void testMissingCsarFile() throws Exception {
249         BabelRequest request = new BabelRequest();
250         request.setArtifactName("test-name");
251         request.setArtifactVersion("1.0");
252         Response response = invokeService(new Gson().toJson(request));
253         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
254         assertThat(response.getEntity(), is("No csar attribute found in the request body."));
255     }
256
257     /**
258      * Create a (mocked) HTTPS request and invoke the Babel generate artifacts API.
259      *
260      * @param csar
261      *            test CSAR file
262      * @param auth
263      *            the auth module
264      * @return the Response from the HTTP API
265      * @throws URISyntaxException
266      *             if the URI cannot be created
267      * @throws IOException
268      *             if the resource cannot be loaded
269      */
270     private Response processJsonRequest(CsarTest csar, AAIMicroServiceAuth auth)
271             throws URISyntaxException, IOException {
272         return invokeService(csar.getJsonRequest(), Optional.of("transaction-id"), auth);
273     }
274
275     /**
276      * Create a (mocked) HTTPS request and invoke the Babel generate artifacts API.
277      *
278      * @param jsonString
279      *            the JSON request
280      * @return the Response from the HTTP API
281      * @throws URISyntaxException
282      *             if the URI cannot be created
283      */
284     private Response invokeService(String jsonRequest) throws URISyntaxException {
285         return invokeService(jsonRequest, Optional.of("transaction-id"), auth);
286     }
287
288     /**
289      * Create a (mocked) HTTPS request and invoke the Babel generate artifacts API.
290      *
291      * @param jsonString
292      *            the JSON request
293      * @param transactionId
294      *            optional X-TransactionId value for the HTTP request
295      * @param auth
296      *            the auth module
297      * @return the Response from the HTTP API
298      * @throws URISyntaxException
299      *             if the URI cannot be created
300      */
301     private Response invokeService(String jsonString, Optional<String> transactionId, AAIMicroServiceAuth auth)
302             throws URISyntaxException {
303         UriInfo mockUriInfo = Mockito.mock(UriInfo.class);
304         Mockito.when(mockUriInfo.getRequestUri()).thenReturn(new URI("/validate")); // NOSONAR (mocked)
305         Mockito.when(mockUriInfo.getPath(false)).thenReturn("validate"); // URI prefix is stripped by AJSC routing
306         Mockito.when(mockUriInfo.getPathParameters()).thenReturn(new MultivaluedHashMap<String, String>());
307
308         // Create mocked request headers map
309         MultivaluedHashMap<String, String> headersMap = new MultivaluedHashMap<>();
310         if (transactionId.isPresent()) {
311             headersMap.put("X-TransactionId", createSingletonList(transactionId.get()));
312         }
313         headersMap.put("X-FromAppId", createSingletonList("app-id"));
314         headersMap.put("Host", createSingletonList("hostname"));
315
316         HttpHeaders headers = Mockito.mock(HttpHeaders.class);
317         for (Entry<String, List<String>> entry : headersMap.entrySet()) {
318             Mockito.when(headers.getRequestHeader(entry.getKey())).thenReturn(entry.getValue());
319             Mockito.when(headers.getHeaderString(entry.getKey())).thenReturn(entry.getValue().get(0));
320         }
321         Mockito.when(headers.getRequestHeaders()).thenReturn(headersMap);
322
323         MockHttpServletRequest servletRequest = new MockHttpServletRequest();
324         servletRequest.setSecure(true);
325         servletRequest.setScheme("https");
326         servletRequest.setServerPort(9501);
327         servletRequest.setServerName("localhost");
328         servletRequest.setRequestURI("/services/validation-service/v1/app/validate");
329
330         X509Certificate mockCertificate = Mockito.mock(X509Certificate.class);
331         Mockito.when(mockCertificate.getSubjectX500Principal())
332                 .thenReturn(new X500Principal("CN=test, OU=qa, O=Test Ltd, L=London, ST=London, C=GB"));
333
334         servletRequest.setAttribute("javax.servlet.request.X509Certificate", new X509Certificate[] {mockCertificate});
335         servletRequest.setAttribute("javax.servlet.request.cipher_suite", "");
336
337         GenerateArtifactsServiceImpl service = new GenerateArtifactsServiceImpl(auth);
338         return service.generateArtifacts(mockUriInfo, headers, servletRequest, jsonString);
339     }
340
341     private String getResponseJson(String jsonResponse) throws IOException, URISyntaxException {
342         return new ArtifactTestUtils().getResponseJson(jsonResponse);
343     }
344
345     private List<String> createSingletonList(String listItem) {
346         return Collections.<String>singletonList(listItem);
347     }
348
349 }