Merge "Fix some security vulnerabilities"
[vfc/nfvo/driver/vnfm/svnfm.git] / nokiav2 / driver / src / test / java / org / onap / vfc / nfvo / driver / vnfm / svnfm / nokia / vnfm / TestCbamCatalogManager.java
1 /*
2  * Copyright 2016-2017, Nokia Corporation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm;
17
18 import com.nokia.cbam.catalog.v1.model.CatalogAdapterVnfpackage;
19 import okhttp3.Headers;
20 import okhttp3.RequestBody;
21 import okhttp3.ResponseBody;
22 import okhttp3.internal.http.RealResponseBody;
23 import okio.Buffer;
24 import okio.BufferedSource;
25 import org.junit.Before;
26 import org.junit.Test;
27 import org.mockito.ArgumentCaptor;
28 import org.mockito.Mock;
29 import org.mockito.Mockito;
30 import org.mockito.invocation.InvocationOnMock;
31 import org.mockito.stubbing.Answer;
32 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.api.IPackageProvider;
33 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.TestUtil;
34 import retrofit2.Call;
35
36 import java.io.ByteArrayInputStream;
37 import java.io.IOException;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.List;
41
42 import static junit.framework.TestCase.*;
43 import static org.junit.Assert.assertArrayEquals;
44 import static org.mockito.Mockito.*;
45 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CatalogManager.getFileInZip;
46 import static org.springframework.test.util.ReflectionTestUtils.setField;
47
48 public class TestCbamCatalogManager extends TestBase {
49
50     private static final String CSAR_ID = "csarId";
51     private static final String CBAM_VNFD_ID = "CBAM_VNFD_ID";
52     private CatalogManager cbamCatalogManager;
53     @Mock
54     private IPackageProvider packageProvider;
55
56     private List<CatalogAdapterVnfpackage> existingVnfPackages = new ArrayList<>();
57     private ArgumentCaptor<RequestBody> uploadedFile = ArgumentCaptor.forClass(RequestBody.class);
58
59     @Before
60     public void initMocks() throws Exception {
61         setField(CatalogManager.class, "logger", logger);
62         Call<List<CatalogAdapterVnfpackage>> value = buildCall(existingVnfPackages);
63         when(cbamCatalogApi.list()).thenReturn(value);
64         cbamCatalogManager = new CatalogManager(cbamRestApiProvider, packageProvider);
65     }
66
67     /**
68      * the package is transferred from source to CBAM catalog
69      */
70     @Test
71     public void testPackageTransfer() throws Exception {
72         CatalogAdapterVnfpackage existingPackage = new CatalogAdapterVnfpackage();
73         existingPackage.setVnfdId("unknownId");
74         existingVnfPackages.add(existingPackage);
75         CatalogAdapterVnfpackage createdPackage = new CatalogAdapterVnfpackage();
76         createdPackage.setVnfdId(CBAM_VNFD_ID);
77         Call<CatalogAdapterVnfpackage> catalogAdapterVnfpackageCall = buildCall(createdPackage);
78         when(cbamCatalogApi.create(uploadedFile.capture())).thenReturn(catalogAdapterVnfpackageCall);
79         byte[] onapPackageContent = TestUtil.loadFile("unittests/TestCbamCatalogManager.sample.csar");
80         when(packageProvider.getPackage(CSAR_ID)).thenReturn(onapPackageContent);
81         when(packageProvider.getCbamVnfdId(CSAR_ID)).thenReturn(CBAM_VNFD_ID);
82         //when
83         CatalogAdapterVnfpackage cbamPackage = cbamCatalogManager.preparePackageInCbam(VNFM_ID, CSAR_ID);
84         //verify
85         byte[] a2 = getContent(uploadedFile.getValue());
86         assertArrayEquals(getFileInZip(new ByteArrayInputStream(onapPackageContent), "Artifacts/Deployment/OTHER/cbam.package.zip").toByteArray(), a2);
87         assertEquals(createdPackage, cbamPackage);
88     }
89
90     /**
91      * the package is transfer fails, but the package has been uploaded (possibly by other thread / work flow)
92      * the transfer succeeds
93      */
94     @Test
95     public void testPackageTransferConcurrency() throws Exception {
96         CatalogAdapterVnfpackage existingPackage = new CatalogAdapterVnfpackage();
97         existingPackage.setVnfdId("unknownId");
98         existingVnfPackages.add(existingPackage);
99         CatalogAdapterVnfpackage createdPackage = new CatalogAdapterVnfpackage();
100         createdPackage.setVnfdId(CBAM_VNFD_ID);
101         byte[] onapPackageContent = TestUtil.loadFile("unittests/TestCbamCatalogManager.sample.csar");
102         when(packageProvider.getPackage(CSAR_ID)).thenReturn(onapPackageContent);
103         when(packageProvider.getCbamVnfdId(CSAR_ID)).thenReturn(CBAM_VNFD_ID);
104         RuntimeException can_not_upload_package = new RuntimeException("Can not upload package");
105         when(cbamCatalogApi.create(uploadedFile.capture())).thenAnswer(new Answer<CatalogAdapterVnfpackage>() {
106             @Override
107             public CatalogAdapterVnfpackage answer(InvocationOnMock invocationOnMock) throws Throwable {
108                 //this is done by an other thread
109                 existingVnfPackages.add(createdPackage);
110                 Call<CatalogAdapterVnfpackage> catalogAdapterVnfpackageCall = buildCall(createdPackage);
111                 when(cbamCatalogApi.getById(CBAM_VNFD_ID)).thenReturn(catalogAdapterVnfpackageCall);
112                 throw can_not_upload_package;
113             }
114         });
115         //when
116         CatalogAdapterVnfpackage cbamPackage = cbamCatalogManager.preparePackageInCbam(VNFM_ID, CSAR_ID);
117         //verify
118         //the correct portion of the package is extracted and uploaded to CBAM
119         byte[] expectedContentToUpload = getFileInZip(new ByteArrayInputStream(onapPackageContent), "Artifacts/Deployment/OTHER/cbam.package.zip").toByteArray();
120         assertTrue(Arrays.equals(expectedContentToUpload, getContent(uploadedFile.getValue())));
121         assertEquals(createdPackage, cbamPackage);
122         verify(logger).debug("Probably concurrent package uploads", can_not_upload_package);
123     }
124
125     /**
126      * If the package already exists in CBAM catalog it is not re-uploaded
127      */
128     @Test
129     public void testIdempotentPackageUpload() throws Exception {
130         CatalogAdapterVnfpackage createdPackage = new CatalogAdapterVnfpackage();
131         createdPackage.setVnfdId(CBAM_VNFD_ID);
132         when(cbamCatalogApi.create(uploadedFile.capture())).thenAnswer(new Answer<CatalogAdapterVnfpackage>() {
133             @Override
134             public CatalogAdapterVnfpackage answer(InvocationOnMock invocationOnMock) throws Throwable {
135                 return createdPackage;
136             }
137         });
138         when(packageProvider.getCbamVnfdId(CSAR_ID)).thenReturn(CBAM_VNFD_ID);
139         CatalogAdapterVnfpackage existingPackage = new CatalogAdapterVnfpackage();
140         existingPackage.setVnfdId(CBAM_VNFD_ID);
141         existingVnfPackages.add(existingPackage);
142         Call<CatalogAdapterVnfpackage> catalogAdapterVnfpackageCall = buildCall(existingPackage);
143         when(cbamCatalogApi.getById(CBAM_VNFD_ID)).thenReturn(catalogAdapterVnfpackageCall);
144         //when
145         CatalogAdapterVnfpackage cbamPackage = cbamCatalogManager.preparePackageInCbam(VNFM_ID, CSAR_ID);
146         //verify
147         verify(cbamCatalogApi, never()).create(Mockito.any());
148         assertEquals(existingPackage, cbamPackage);
149         verify(packageProvider, never()).getPackage(CSAR_ID);
150     }
151
152     /**
153      * failure to list package in CBAM results in error
154      */
155     @Test
156     public void testFailureToListVnfPackagesInCbam() throws Exception {
157         when(packageProvider.getCbamVnfdId(CSAR_ID)).thenReturn(CBAM_VNFD_ID);
158         RuntimeException expectedException = new RuntimeException();
159         when(cbamCatalogApi.list()).thenThrow(expectedException);
160         //when
161         try {
162             cbamCatalogManager.preparePackageInCbam(VNFM_ID, CSAR_ID);
163             fail();
164         } catch (Exception e) {
165             verify(logger).error("Unable to determine if the VNF package has been replicated in CBAM", expectedException);
166             assertEquals(expectedException, e.getCause());
167         }
168     }
169
170     /**
171      * failure to query package from CBAM results in error
172      */
173     @Test
174     public void testFailureToQueryVnfPackagesFromCbam() throws Exception {
175         when(packageProvider.getCbamVnfdId(CSAR_ID)).thenReturn(CBAM_VNFD_ID);
176         CatalogAdapterVnfpackage existingPackage = new CatalogAdapterVnfpackage();
177         existingPackage.setVnfdId(CBAM_VNFD_ID);
178         existingVnfPackages.add(existingPackage);
179         RuntimeException expectedException = new RuntimeException();
180         when(cbamCatalogApi.getById(CBAM_VNFD_ID)).thenThrow(expectedException);
181         //when
182         try {
183             cbamCatalogManager.preparePackageInCbam(VNFM_ID, CSAR_ID);
184             fail();
185         } catch (Exception e) {
186             verify(logger).error("Unable to query VNF package with CBAM_VNFD_ID from CBAM", expectedException);
187             assertEquals(expectedException, e.getCause());
188         }
189     }
190
191     /**
192      * failure to create package in CBAM results in error
193      */
194     @Test
195     public void testFailureToCreatePackageInCbam() throws Exception {
196         CatalogAdapterVnfpackage existingPackage = new CatalogAdapterVnfpackage();
197         existingPackage.setVnfdId("unknownId");
198         existingVnfPackages.add(existingPackage);
199         when(packageProvider.getCbamVnfdId(CSAR_ID)).thenReturn(CBAM_VNFD_ID);
200         byte[] onapPackageContent = TestUtil.loadFile("unittests/TestCbamCatalogManager.sample.csar");
201         when(packageProvider.getPackage(CSAR_ID)).thenReturn(onapPackageContent);
202         RuntimeException expectedException = new RuntimeException();
203         when(cbamCatalogApi.create(Mockito.any())).thenThrow(expectedException);
204         try {
205             cbamCatalogManager.preparePackageInCbam(VNFM_ID, CSAR_ID);
206             fail();
207         } catch (Exception e) {
208             verify(logger).error("Unable to create VNF with csarId CSAR identifier in package in CBAM", expectedException);
209             assertEquals(expectedException, e.getCause());
210         }
211     }
212
213     /**
214      * the VNFD is extracted from zip
215      */
216     @Test
217     public void testExtractVnfdFromPackage() throws Exception {
218         Call<ResponseBody> responseBodyCall = buildCall(buildResponse(TestUtil.loadFile("unittests/cbam.package.zip")));
219         when(cbamCatalogApi.content(CBAM_VNFD_ID)).thenReturn(responseBodyCall);
220         //when
221         String content = cbamCatalogManager.getCbamVnfdContent(VNFM_ID, CBAM_VNFD_ID);
222         //verify
223         assertEquals("dummy vnfd\n", content);
224     }
225
226     /**
227      * if VNFD the Tosca meta can not be extracted sensible error is returned
228      */
229     @Test
230     public void testEmptyCbamPackage() throws Exception {
231         Call<ResponseBody> responseBodyCall = buildCall(buildResponse(TestUtil.loadFile("unittests/empty.zip")));
232         when(cbamCatalogApi.content(CBAM_VNFD_ID)).thenReturn(responseBodyCall);
233         //when
234         try {
235             cbamCatalogManager.getCbamVnfdContent(VNFM_ID, CBAM_VNFD_ID);
236             fail();
237         } catch (RuntimeException e) {
238             verify(logger).error("Unable to get package with (CBAM_VNFD_ID)", e.getCause());
239             assertEquals("Unable to find the TOSCA-Metadata/TOSCA.meta in archive found: []", e.getCause().getMessage());
240         }
241     }
242
243     /**
244      * if VNFD can not be extracted sensible error is returned
245      */
246     @Test
247     public void testMissingVnfdCbamPackage() throws Exception {
248         byte[] bytes = TestUtil.loadFile("unittests/missing.vnfd.zip");
249         Call<ResponseBody> response = buildCall(buildResponse(bytes));
250         when(cbamCatalogApi.content(CBAM_VNFD_ID)).thenReturn(response);
251         //when
252         try {
253             cbamCatalogManager.getCbamVnfdContent(VNFM_ID, CBAM_VNFD_ID);
254             fail();
255         } catch (RuntimeException e) {
256             verify(logger).error("Unable to get package with (" + CBAM_VNFD_ID + ")", e.getCause());
257             assertTrue("Unable to find the vnfdloc/a.yaml in archive found: [TOSCA-Metadata/, TOSCA-Metadata/TOSCA.meta]".equals(e.getCause().getMessage())
258                     || "Unable to find the vnfdloc/a.yaml in archive found: [TOSCA-Metadata/TOSCA.meta, TOSCA-Metadata/]".equals(e.getCause().getMessage())
259             );
260         }
261     }
262
263     private ResponseBody buildResponse(byte[] content) throws IOException {
264         Headers headers = new Headers.Builder().build();
265         Buffer buffer = new Buffer();
266         buffer.write(content);
267         BufferedSource response = buffer;
268         return new RealResponseBody(headers, response);
269     }
270 }