Fix Security Vulnerabilities
[sdc.git] / openecomp-be / api / openecomp-sdc-rest-webapp / vendor-software-products-rest / vendor-software-products-rest-services / src / test / java / org / openecomp / sdcrests / vsp / rest / services / OrchestrationTemplateCandidateImplTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. 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.openecomp.sdcrests.vsp.rest.services;
22
23 import static junit.framework.TestCase.assertEquals;
24 import static junit.framework.TestCase.assertFalse;
25 import static org.junit.Assert.assertTrue;
26 import static org.mockito.ArgumentMatchers.any;
27 import static org.mockito.MockitoAnnotations.initMocks;
28 import static org.mockito.Mockito.when;
29
30 import java.io.IOException;
31 import java.net.URL;
32 import java.util.Arrays;
33 import java.util.Objects;
34 import java.util.Optional;
35 import java.util.UUID;
36 import javax.activation.DataHandler;
37 import javax.ws.rs.core.Response;
38 import javax.ws.rs.core.Response.Status;
39 import org.apache.commons.io.IOUtils;
40 import org.apache.commons.lang3.tuple.Pair;
41 import org.apache.cxf.jaxrs.ext.multipart.Attachment;
42 import org.apache.cxf.jaxrs.ext.multipart.ContentDisposition;
43 import org.junit.Assert;
44 import org.junit.Before;
45 import org.junit.Test;
46 import org.mockito.ArgumentMatchers;
47 import org.mockito.Mock;
48 import org.mockito.Mockito;
49 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
50 import org.openecomp.sdc.activitylog.ActivityLogManager;
51 import org.openecomp.sdc.logging.api.Logger;
52 import org.openecomp.sdc.logging.api.LoggerFactory;
53 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
54 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
55 import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse;
56 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
57 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileStatus;
58 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
59 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure;
60 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.Module;
61 import org.openecomp.sdcrests.vendorsoftwareproducts.types.FileDataStructureDto;
62 import org.openecomp.sdcrests.vendorsoftwareproducts.types.OrchestrationTemplateActionResponseDto;
63 import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto;
64
65 public class OrchestrationTemplateCandidateImplTest {
66
67     private Logger logger = LoggerFactory.getLogger(OrchestrationTemplateCandidateImplTest.class);
68
69     @Mock
70     private OrchestrationTemplateCandidateManager candidateManager;
71     @Mock
72     private VendorSoftwareProductManager vendorSoftwareProductManager;
73
74     @Mock
75     private ActivityLogManager activityLogManager;
76
77     private OrchestrationTemplateCandidateImpl orchestrationTemplateCandidate;
78
79     private final String candidateId = UUID.randomUUID().toString();
80     private final String softwareProductId = UUID.randomUUID().toString();
81     private final String versionId = UUID.randomUUID().toString();
82
83     private final String user = "cs0008";
84
85     @Before
86     public void setUp(){
87         try {
88             initMocks(this);
89             UploadFileResponse uploadFileResponse = new UploadFileResponse();
90             uploadFileResponse.setOnboardingType(OnboardingTypesEnum.ZIP);
91             uploadFileResponse.setNetworkPackageName("test");
92             when(candidateManager.upload(any(), any())).thenReturn(uploadFileResponse);
93
94
95             // get using the candidate manager.
96             Optional<Pair<String,byte[]>> zipFile =
97                     Optional.of(Pair.of("Hello", "World".getBytes()));
98
99             when(candidateManager.get(
100                     ArgumentMatchers.eq(candidateId),
101                     ArgumentMatchers.any())).thenReturn(zipFile);
102
103             when(vendorSoftwareProductManager.get(
104                     ArgumentMatchers.eq(softwareProductId),
105                     ArgumentMatchers.any())).thenReturn(zipFile);
106
107
108             OrchestrationTemplateActionResponse processResponse =
109                     new OrchestrationTemplateActionResponse();
110             processResponse.setStatus(UploadFileStatus.Success);
111             when(candidateManager.process(
112                     ArgumentMatchers.eq(candidateId),
113                     ArgumentMatchers.any())).thenReturn(processResponse);
114
115
116             ValidationResponse vr = new ValidationResponse();
117             when(candidateManager.updateFilesDataStructure(
118                     ArgumentMatchers.eq(candidateId),
119                     ArgumentMatchers.any(),
120                     ArgumentMatchers.any())).thenReturn(vr);
121
122             FilesDataStructure fds = new FilesDataStructure();
123             fds.setArtifacts(Arrays.asList("a","b"));
124             fds.setNested(Arrays.asList("foo", "bar"));
125             fds.setUnassigned(Arrays.asList("c", "d"));
126             fds.setModules(Arrays.asList(new Module(), new Module()));
127
128             when(candidateManager.getFilesDataStructure(
129                     ArgumentMatchers.eq(candidateId),
130                     ArgumentMatchers.any())).thenReturn(Optional.of(fds));
131
132             orchestrationTemplateCandidate =
133                 new OrchestrationTemplateCandidateImpl(candidateManager, vendorSoftwareProductManager, activityLogManager);
134
135
136         }catch (Exception e){
137            logger.error(e.getMessage(), e);
138         }
139     }
140
141     @Test
142     public void uploadSignedTest() {
143         Response response = orchestrationTemplateCandidate
144             .upload("1", "1", mockAttachment("filename.zip", this.getClass().getResource("/files/sample-signed.zip")),
145                 "1");
146         assertEquals(Status.OK.getStatusCode(), response.getStatus());
147         assertTrue(((UploadFileResponseDto) response.getEntity()).getErrors().isEmpty());
148     }
149
150     @Test
151     public void uploadNotSignedTest() {
152         Response response = orchestrationTemplateCandidate.upload("1", "1",
153             mockAttachment("filename.csar", this.getClass().getResource("/files/sample-not-signed.csar")), "1");
154         assertEquals(Status.OK.getStatusCode(), response.getStatus());
155         assertTrue(((UploadFileResponseDto) response.getEntity()).getErrors().isEmpty());
156     }
157
158     private Attachment mockAttachment(final String fileName, final URL fileToUpload) {
159         final Attachment attachment = Mockito.mock(Attachment.class);
160         when(attachment.getContentDisposition()).thenReturn(new ContentDisposition("test"));
161         final DataHandler dataHandler = Mockito.mock(DataHandler.class);
162         when(dataHandler.getName()).thenReturn(fileName);
163         when(attachment.getDataHandler()).thenReturn(dataHandler);
164         byte[] bytes = "upload package Test".getBytes();
165         if (Objects.nonNull(fileToUpload)) {
166             try {
167                 bytes = IOUtils.toByteArray(fileToUpload);
168             } catch (final IOException e) {
169                 logger.error("unexpected exception", e);
170                 Assert.fail("Not able to convert file to byte array");
171             }
172         }
173         when(attachment.getObject(ArgumentMatchers.any())).thenReturn(bytes);
174         return attachment;
175     }
176
177     @Test
178     public void uploadSignNotValidTest() {
179         Response response = orchestrationTemplateCandidate
180             .upload("1", "1", mockAttachment("filename.zip", null), "1");
181         assertEquals(Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus());
182         assertFalse(((UploadFileResponseDto) response.getEntity()).getErrors().isEmpty());
183     }
184
185     @Test
186     public void testCandidateGet() throws IOException {
187         Response rsp = orchestrationTemplateCandidate.get(candidateId, versionId, user);
188         Assert.assertEquals("Response status equals", Response.Status.OK.getStatusCode(), rsp.getStatus());
189         Assert.assertNotEquals(rsp.getHeaderString("Content-Disposition").indexOf("Candidate"),-1);
190         byte[] content = (byte[])rsp.getEntity();
191         Assert.assertEquals("World", new String(content));
192     }
193
194     @Test
195     public void testVendorSoftwareProductGet() throws IOException {
196         Response rsp = orchestrationTemplateCandidate.get(softwareProductId, versionId, user);
197         Assert.assertEquals("Response status equals", Response.Status.OK.getStatusCode(), rsp.getStatus());
198         Assert.assertNotEquals(rsp.getHeaderString("Content-Disposition").indexOf("Processed"),-1);
199         byte[] content = (byte[])rsp.getEntity();
200         Assert.assertEquals("World", new String(content));
201     }
202
203     @Test
204     public void testMissingGet() throws IOException {
205         Response rsp = orchestrationTemplateCandidate.get(UUID.randomUUID().toString(), versionId, user);
206         Assert.assertEquals("Response status equals", Response.Status.NOT_FOUND.getStatusCode(), rsp.getStatus());
207     }
208
209     @Test
210     public void testAbort() {
211         try {
212             Response rsp = orchestrationTemplateCandidate.abort(candidateId, versionId);
213             Assert.assertEquals("Response status equals", Response.Status.OK.getStatusCode(), rsp.getStatus());
214             Assert.assertNull(rsp.getEntity());
215         }
216         catch (Exception ex) {
217             logger.error("unexpected exception", ex);
218             Assert.fail("abort should not throw an exception");
219         }
220     }
221
222     @Test
223     public void testProcess() {
224         try {
225             Response rsp = orchestrationTemplateCandidate.process(candidateId, versionId, user);
226             Assert.assertEquals("Response status equals", Response.Status.OK.getStatusCode(), rsp.getStatus());
227             Assert.assertNotNull(rsp.getEntity());
228             OrchestrationTemplateActionResponseDto dto = (OrchestrationTemplateActionResponseDto)rsp.getEntity();
229             Assert.assertEquals("status check", UploadFileStatus.Success, dto.getStatus());
230         }
231         catch (Exception ex) {
232             logger.error("unexpected exception", ex);
233             Assert.fail("abort should not throw an exception");
234         }
235     }
236
237     @Test
238     public void testFilesDataStructureUpload() {
239         try {
240             FileDataStructureDto dto = new FileDataStructureDto();
241             dto.setArtifacts(Arrays.asList("a", "b", "c"));
242             Response rsp = orchestrationTemplateCandidate.updateFilesDataStructure(candidateId, versionId, dto, user);
243             Assert.assertEquals("Response status equals", Response.Status.OK.getStatusCode(), rsp.getStatus());
244         }
245         catch (Exception ex) {
246             logger.error("unexpected exception", ex);
247             Assert.fail("abort should not throw an exception");
248         }
249     }
250
251     @Test
252     public void testFilesDataStructureGet() {
253         try {
254             FileDataStructureDto dto = new FileDataStructureDto();
255             dto.setArtifacts(Arrays.asList("a", "b", "c"));
256             Response rsp = orchestrationTemplateCandidate.getFilesDataStructure(candidateId, versionId, user);
257             Assert.assertEquals("Response status equals", Response.Status.OK.getStatusCode(), rsp.getStatus());
258         }
259         catch (Exception ex) {
260             logger.error("unexpected exception", ex);
261             Assert.fail("abort should not throw an exception");
262         }
263     }
264
265 }