Updated pom to remove distribution-management section and corrected aai base image...
[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.mockito.Mockito;
48 import org.onap.aai.auth.AAIAuthException;
49 import org.onap.aai.auth.AAIMicroServiceAuth;
50 import org.onap.aai.babel.service.data.BabelRequest;
51 import org.onap.aai.babel.testdata.CsarTest;
52 import org.onap.aai.babel.util.ArtifactTestUtils;
53 import org.springframework.mock.web.MockHttpServletRequest;
54 import org.springframework.test.context.ContextConfiguration;
55 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
56
57 /**
58  * Direct invocation of the generate artifacts service implementation.
59  *
60  */
61 @RunWith(SpringJUnit4ClassRunner.class)
62 @ContextConfiguration(locations = {"classpath:/babel-beans.xml"})
63 public class TestGenerateArtifactsServiceImpl {
64
65     static {
66         System.setProperty("CONFIG_HOME", "src/test/resources");
67     }
68
69     @Inject
70     private AAIMicroServiceAuth auth;
71
72     @BeforeClass
73     public static void setup() {
74         new ArtifactTestUtils().setGeneratorSystemProperties();
75     }
76
77     /**
78      * Test with a valid request (and valid CSAR content) by calling the Service implementation directly using a mocked
79      * HTTPS request.
80      *
81      * @throws URISyntaxException
82      *             if the URI cannot be created
83      * @throws IOException
84      *             if the resource cannot be loaded
85      */
86     @Test
87     public void testGenerateArtifacts() throws URISyntaxException, IOException {
88         Response response = processJsonRequest(CsarTest.VNF_VENDOR_CSAR, auth);
89         assertThat(response.toString(), response.getStatus(), is(Response.Status.OK.getStatusCode()));
90         assertThat(response.getEntity(), is(getResponseJson("response.json")));
91     }
92
93     /**
94      * Test with a valid request that has no Transaction ID header value.
95      *
96      * @throws URISyntaxException
97      *             if the URI cannot be created
98      * @throws IOException
99      *             if the resource cannot be loaded
100      */
101     @Test
102     public void testGenerateArtifactsWithoutRequestId() throws URISyntaxException, IOException {
103         Response response = invokeService(CsarTest.VNF_VENDOR_CSAR.getJsonRequest(), Optional.empty(), auth);
104         assertThat(response.toString(), response.getStatus(), is(Response.Status.OK.getStatusCode()));
105         assertThat(response.getEntity(), is(getResponseJson("response.json")));
106     }
107     
108     /**
109      * Test with a valid request without Minor Artifact version.
110      *
111      * @throws URISyntaxException
112      *             if the URI cannot be created
113      * @throws IOException
114      *             if the resource cannot be loaded
115      */
116     @Test
117     public void testGenerateArtifactsWithoutMinorArtifactVersion() throws URISyntaxException, IOException {
118         Response response = invokeService(CsarTest.VNF_VENDOR_CSAR.getJsonRequestWithArtifactVersion("1"),
119                         Optional.of("transaction-id"), auth);
120         assertThat(response.toString(), response.getStatus(), is(Response.Status.OK.getStatusCode()));
121         assertThat(response.getEntity(), is(getResponseJson("response.json")));
122     }
123     
124     /**
125      * Test with a valid request without Minor Artifact version.
126      *
127      * @throws URISyntaxException
128      *             if the URI cannot be created
129      * @throws IOException
130      *             if the resource cannot be loaded
131      */
132     @Test
133     public void testGenerateArtifactsWithInvalidArtifactVersion() throws URISyntaxException, IOException {
134         Response response = invokeService(CsarTest.VNF_VENDOR_CSAR.getJsonRequestWithArtifactVersion("a"),
135                         Optional.of("transaction-id"), auth);
136         assertThat(response.toString(), response.getStatus(), is(Response.Status.OK.getStatusCode()));
137         assertThat(response.getEntity(), is(getResponseJson("response.json")));
138     }
139     
140     
141     /**
142      * Test with a valid request with Artifact version less than 1.
143      *
144      * @throws URISyntaxException
145      *             if the URI cannot be created
146      * @throws IOException
147      *             if the resource cannot be loaded
148      */
149     @Test
150     public void testGenerateArtifactsWithArtifactVerLessThan1() throws URISyntaxException, IOException {
151         Response response = invokeService(CsarTest.VNF_VENDOR_CSAR.getJsonRequestWithArtifactVersion("0.1"),
152                         Optional.of("transaction-id"), auth);
153         assertThat(response.toString(), response.getStatus(), is(Response.Status.OK.getStatusCode()));
154         assertThat(response.getEntity(), is(getResponseJson("responseWithVersionLessThan1.json")));
155     }
156
157
158     /**
159      * Test with a valid request, using a CSAR file that has no VNF configuration present.
160      *
161      * @throws URISyntaxException
162      *             if the URI cannot be created
163      * @throws IOException
164      *             if the resource cannot be loaded
165      */
166     @Test
167     public void testGenerateArtifactsWithoutVnfConfiguration() throws IOException, URISyntaxException {
168         Response response = processJsonRequest(CsarTest.NO_VNF_CONFIG_CSAR, auth);
169         assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
170         assertThat(response.getEntity(), is(getResponseJson("validNoVnfConfigurationResponse.json")));
171     }
172
173     /**
174      * Test for a valid request with invalid CSAR file content.
175      *
176      * @throws URISyntaxException
177      *             if the URI cannot be created
178      * @throws IOException
179      *             if the resource cannot be loaded
180      */
181     @Test
182     public void testGenerateArtifactsInvalidCsar() throws IOException, URISyntaxException {
183         Response response = processJsonRequest(CsarTest.MULTIPLE_VNF_CSAR, auth);
184         assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
185         assertThat(response.getEntity().toString(), containsString("VNF catalog"));
186     }
187
188     @Test
189     public void testUninitializedService() throws IOException, URISyntaxException, AAIAuthException {
190         AAIMicroServiceAuth uninitializedAuth = Mockito.mock(AAIMicroServiceAuth.class);
191         Mockito.when(uninitializedAuth.validateRequest(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
192                 .thenThrow(new AAIAuthException("test"));
193         Response response = processJsonRequest(CsarTest.NO_VNF_CONFIG_CSAR, uninitializedAuth);
194         assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
195         assertThat(response.getEntity().toString(), containsString("check the Babel service logs"));
196     }
197
198     @Test
199     public void testUnauthorizedRequest() throws IOException, URISyntaxException, AAIAuthException {
200         AAIMicroServiceAuth uninitializedAuth = Mockito.mock(AAIMicroServiceAuth.class);
201         Mockito.when(uninitializedAuth.validateRequest(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
202                 .thenReturn(false);
203         Response response = processJsonRequest(CsarTest.NO_VNF_CONFIG_CSAR, uninitializedAuth);
204         assertThat(response.getStatus(), is(Response.Status.UNAUTHORIZED.getStatusCode()));
205         assertThat(response.getEntity().toString(), containsString("User not authorized"));
206     }
207
208     @Test
209     public void testInvalidCsarFile() throws URISyntaxException, IOException {
210         BabelRequest request = new BabelRequest();
211         request.setArtifactName("hello");
212         request.setArtifactVersion("1.0");
213         request.setCsar("xxxx");
214         Response response = invokeService(new Gson().toJson(request));
215         assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
216         assertThat(response.getEntity(), is("Error converting CSAR artifact to XML model."));
217     }
218
219     @Test
220     public void testInvalidJsonFile() throws URISyntaxException, IOException {
221         Response response = invokeService("{\"csar:\"xxxx\"");
222         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
223         assertThat(response.getEntity(), is("Malformed request."));
224     }
225
226     @Test
227     public void testMissingArtifactName() throws Exception {
228         BabelRequest request = new BabelRequest();
229         request.setArtifactVersion("1.0");
230         request.setCsar("");
231         Response response = invokeService(new Gson().toJson(request));
232         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
233         assertThat(response.getEntity(), is("No artifact name attribute found in the request body."));
234     }
235
236     @Test
237     public void testMissingArtifactVersion() throws Exception {
238         BabelRequest request = new BabelRequest();
239         request.setArtifactName("hello");
240         request.setCsar("");
241         Response response = invokeService(new Gson().toJson(request));
242         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
243         assertThat(response.getEntity(), is("No artifact version attribute found in the request body."));
244     }
245
246     @Test
247     public void testMissingCsarFile() throws Exception {
248         BabelRequest request = new BabelRequest();
249         request.setArtifactName("test-name");
250         request.setArtifactVersion("1.0");
251         Response response = invokeService(new Gson().toJson(request));
252         assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
253         assertThat(response.getEntity(), is("No csar attribute found in the request body."));
254     }
255
256     /**
257      * Create a (mocked) HTTPS request and invoke the Babel generate artifacts API.
258      *
259      * @param csar
260      *            test CSAR file
261      * @param auth
262      *            the auth module
263      * @return the Response from the HTTP API
264      * @throws URISyntaxException
265      *             if the URI cannot be created
266      * @throws IOException
267      *             if the resource cannot be loaded
268      */
269     private Response processJsonRequest(CsarTest csar, AAIMicroServiceAuth auth)
270             throws URISyntaxException, IOException {
271         return invokeService(csar.getJsonRequest(), Optional.of("transaction-id"), auth);
272     }
273
274     /**
275      * Create a (mocked) HTTPS request and invoke the Babel generate artifacts API.
276      *
277      * @param jsonString
278      *            the JSON request
279      * @return the Response from the HTTP API
280      * @throws URISyntaxException
281      *             if the URI cannot be created
282      */
283     private Response invokeService(String jsonRequest) throws URISyntaxException {
284         return invokeService(jsonRequest, Optional.of("transaction-id"), auth);
285     }
286
287     /**
288      * Create a (mocked) HTTPS request and invoke the Babel generate artifacts API.
289      *
290      * @param jsonString
291      *            the JSON request
292      * @param transactionId
293      *            optional X-TransactionId value for the HTTP request
294      * @param auth
295      *            the auth module
296      * @return the Response from the HTTP API
297      * @throws URISyntaxException
298      *             if the URI cannot be created
299      */
300     private Response invokeService(String jsonString, Optional<String> transactionId, AAIMicroServiceAuth auth)
301             throws URISyntaxException {
302         UriInfo mockUriInfo = Mockito.mock(UriInfo.class);
303         Mockito.when(mockUriInfo.getRequestUri()).thenReturn(new URI("/validate")); // NOSONAR (mocked)
304         Mockito.when(mockUriInfo.getPath(false)).thenReturn("validate"); // URI prefix is stripped by AJSC routing
305         Mockito.when(mockUriInfo.getPathParameters()).thenReturn(new MultivaluedHashMap<String, String>());
306
307         // Create mocked request headers map
308         MultivaluedHashMap<String, String> headersMap = new MultivaluedHashMap<>();
309         if (transactionId.isPresent()) {
310             headersMap.put("X-TransactionId", createSingletonList(transactionId.get()));
311         }
312         headersMap.put("X-FromAppId", createSingletonList("app-id"));
313         headersMap.put("Host", createSingletonList("hostname"));
314
315         HttpHeaders headers = Mockito.mock(HttpHeaders.class);
316         for (Entry<String, List<String>> entry : headersMap.entrySet()) {
317             Mockito.when(headers.getRequestHeader(entry.getKey())).thenReturn(entry.getValue());
318             Mockito.when(headers.getHeaderString(entry.getKey())).thenReturn(entry.getValue().get(0));
319         }
320         Mockito.when(headers.getRequestHeaders()).thenReturn(headersMap);
321
322         MockHttpServletRequest servletRequest = new MockHttpServletRequest();
323         servletRequest.setSecure(true);
324         servletRequest.setScheme("https");
325         servletRequest.setServerPort(9501);
326         servletRequest.setServerName("localhost");
327         servletRequest.setRequestURI("/services/validation-service/v1/app/validate");
328
329         X509Certificate mockCertificate = Mockito.mock(X509Certificate.class);
330         Mockito.when(mockCertificate.getSubjectX500Principal())
331                 .thenReturn(new X500Principal("CN=test, OU=qa, O=Test Ltd, L=London, ST=London, C=GB"));
332
333         servletRequest.setAttribute("javax.servlet.request.X509Certificate", new X509Certificate[] {mockCertificate});
334         servletRequest.setAttribute("javax.servlet.request.cipher_suite", "");
335
336         GenerateArtifactsServiceImpl service = new GenerateArtifactsServiceImpl(auth);
337         return service.generateArtifacts(mockUriInfo, headers, servletRequest, jsonString);
338     }
339
340     private String getResponseJson(String jsonResponse) throws IOException, URISyntaxException {
341         return new ArtifactTestUtils().getResponseJson(jsonResponse);
342     }
343
344     private List<String> createSingletonList(String listItem) {
345         return Collections.<String>singletonList(listItem);
346     }
347
348 }