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