39239e9427c3cfe1fe5b6942278b1eb943756808
[sdnc/apps.git] /
1 /*
2  *  ============LICENSE_START===================================================
3  * Copyright (c) 2018 Amdocs
4  * ============================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * ============LICENSE_END=====================================================
17  */
18
19 package org.onap.sdnc.apps.pomba.networkdiscovery.unittest.service;
20
21 import static com.github.tomakehurst.wiremock.client.WireMock.get;
22 import static com.github.tomakehurst.wiremock.client.WireMock.okJson;
23 import static com.github.tomakehurst.wiremock.client.WireMock.post;
24 import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertNull;
27 import static org.junit.Assert.assertTrue;
28 import static org.junit.Assert.fail;
29
30 import com.bazaarvoice.jolt.JsonUtils;
31 import com.github.tomakehurst.wiremock.client.WireMock;
32 import com.github.tomakehurst.wiremock.junit.WireMockRule;
33
34 import java.net.URISyntaxException;
35 import java.text.MessageFormat;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Base64;
39 import java.util.List;
40 import java.util.UUID;
41
42 import javax.servlet.http.HttpServletRequest;
43 import javax.ws.rs.core.HttpHeaders;
44 import javax.ws.rs.core.Response;
45 import javax.ws.rs.core.Response.Status;
46
47 import org.eclipse.jetty.util.security.Password;
48 import org.junit.After;
49 import org.junit.Before;
50 import org.junit.Rule;
51 import org.junit.Test;
52 import org.junit.runner.RunWith;
53 import org.mockito.Mockito;
54 import org.onap.logging.ref.slf4j.ONAPLogConstants;
55 import org.onap.pomba.common.datatypes.DataQuality;
56 import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.Attribute;
57 import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.NetworkDiscoveryNotification;
58 import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.Resource;
59 import org.onap.sdnc.apps.pomba.networkdiscovery.service.rs.RestService;
60 import org.springframework.beans.factory.annotation.Autowired;
61 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
62 import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
63 import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
64 import org.springframework.boot.test.context.SpringBootTest;
65 import org.springframework.test.context.TestPropertySource;
66 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
67 import org.springframework.test.context.web.WebAppConfiguration;
68
69 @RunWith(SpringJUnit4ClassRunner.class)
70 @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
71 @WebAppConfiguration
72 @SpringBootTest
73 @TestPropertySource(properties = { "openstack.type.vserver.url=http://localhost:8774/v2.1/servers/{0}",
74         "openstack.identity.url=http://localhost:5000/v3/auth/tokens",
75         "enricher.keyStorePath=src/test/resources/client-cert-onap.p12",
76         "enricher.keyStorePassword=OBF:1y0q1uvc1uum1uvg1pil1pjl1uuq1uvk1uuu1y10",
77         "basicAuth.username=admin",
78         "basicAuth.password=OBF:1u2a1toa1w8v1tok1u30" })
79
80 public class NetworkDiscoveryTest {
81     private static final String V1 = "v1";
82     private static final String APP = "junit";
83
84     private static final String RESOURCE_TYPE_VSERVER = "vserver";
85
86     private static final String AUTH = "Basic " + Base64.getEncoder().encodeToString((
87             "admin:" + Password.deobfuscate("OBF:1u2a1toa1w8v1tok1u30")).getBytes());
88
89     @Rule
90     public WireMockRule identityRule = new WireMockRule(wireMockConfig().port(5000));
91
92     @Rule
93     public WireMockRule openstackRule = new WireMockRule(wireMockConfig().port(8774));
94
95     @Rule
96     public WireMockRule callbackRule = new WireMockRule(wireMockConfig().dynamicPort());
97
98     @Autowired
99     private RestService service;
100
101     private String transactionId = UUID.randomUUID().toString();
102     private String requestId = UUID.randomUUID().toString();
103     private HttpServletRequest httpRequest = Mockito.mock(HttpServletRequest.class);
104     
105     private static final String TEST_RESOURCES = "src/test/resources/jolt/";
106
107
108     public NetworkDiscoveryTest() throws URISyntaxException {
109
110     }
111
112     @Before
113     public void setUp() throws Exception {
114     }
115
116     @After
117     public void tearDown() throws Exception {
118     }
119
120     @Test
121     public void testNoAuthHeader() throws Exception {
122         // no Authorization header
123         List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
124         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, null, APP, this.transactionId,
125                         this.requestId, RESOURCE_TYPE_VSERVER, resourceIds);
126         assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
127         // should get WWW-Authenticate header in response
128         assertTrue(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE).startsWith("Basic realm"));
129     }
130
131     @Test
132     public void testUnauthorized() throws Exception {
133         String authorization = "Basic " + Base64.getEncoder().encodeToString("aaa:bbb".getBytes());
134         // bad Authorization header
135         List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
136         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, authorization, APP,
137                         this.transactionId, this.requestId, RESOURCE_TYPE_VSERVER, resourceIds);
138         assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
139         // should not get WWW-Authenticate header in response
140         assertNull(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE));
141     }
142
143     @Test
144     public void testNoVersion() throws Exception {
145         // no Authorization header
146         String authorization = "Basic " + Base64.getEncoder().encodeToString("aaa:bbb".getBytes());
147         List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
148         Response response = this.service.findbyResourceIdAndType(this.httpRequest, null, authorization, APP,
149                 this.transactionId, this.requestId, RESOURCE_TYPE_VSERVER, resourceIds);
150         assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
151         // should get WWW-Authenticate header in response
152         assertTrue(((String) response.getEntity()).contains("version"));
153     }
154
155     @Test
156     public void testVerifyAppId() throws Exception {
157         // no X-FromAppId header
158         List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
159         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, null, this.transactionId,
160                         this.requestId, RESOURCE_TYPE_VSERVER, resourceIds);
161         assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
162         assertTrue(((String) response.getEntity()).contains(ONAPLogConstants.Headers.PARTNER_NAME));
163     }
164
165     @Test
166     public void testVerifyRequestId() throws Exception {
167         List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
168         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
169                         null, RESOURCE_TYPE_VSERVER, resourceIds);
170         assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
171         assertTrue(((String) response.getEntity()).contains("requestId"));
172     }
173
174     @Test
175     public void testVerifyResourceIds() throws Exception {
176         // no resourceIds list
177         {
178             List<String> resourceIds = null;
179             Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP,
180                             this.transactionId, this.requestId, RESOURCE_TYPE_VSERVER, resourceIds);
181             assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
182             assertTrue(((String) response.getEntity()).contains("resourceIds"));
183         }
184
185         // empty resourceId list
186         {
187             List<String> resourceIds = new ArrayList<>();
188             Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP,
189                             this.transactionId, this.requestId, RESOURCE_TYPE_VSERVER, resourceIds);
190             assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
191             assertTrue(((String) response.getEntity()).contains("resourceIds"));
192         }
193     }
194
195     @Test
196     public void testVerifyResourceType() throws Exception {
197         // no resource type
198         List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
199         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
200                         this.requestId, null, resourceIds);
201         assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
202         assertTrue(((String) response.getEntity()).contains("resourceType"));
203     }
204
205     @Test
206     public void testVerifyInternalError() throws Exception {
207         // no request
208         List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
209         Response response = this.service.findbyResourceIdAndType(null, V1, AUTH, APP, this.transactionId,
210                         this.requestId, null, resourceIds);
211         assertEquals(Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
212     }
213
214     @Test
215     public void testDiscoverVserver() throws Exception {
216         String vserverId = "2c311eae-f542-4173-8a01-582922abd495";
217
218         String resourcePath = MessageFormat.format("/v2.1/servers/{0}",
219                 new Object[] { vserverId });
220
221         String identityPath = "/v3/auth/tokens";
222       
223         Object sourceObject = JsonUtils.filepathToObject(TEST_RESOURCES + "vserver-input.json");
224
225         String openstackApiResponse = JsonUtils.toJsonString(sourceObject);
226
227         this.openstackRule.stubFor(get(resourcePath).willReturn(okJson(openstackApiResponse)));
228
229         this.identityRule.stubFor(post(identityPath).willReturn(okJson("{}").withHeader("X-Subject-Token", "tokenId")));
230
231         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, null, this.requestId,
232                         RESOURCE_TYPE_VSERVER, Arrays.asList(vserverId));
233
234         assertEquals(Status.OK.getStatusCode(), response.getStatus());
235         NetworkDiscoveryNotification notification = (NetworkDiscoveryNotification) response.getEntity();
236
237         assertEquals(requestId, notification.getRequestId());
238         assertEquals(Status.OK.getStatusCode(), notification.getCode().intValue());
239         assertEquals(Boolean.TRUE, notification.getAckFinalIndicator());
240
241         assertEquals(1, notification.getResources().size());
242         Resource vserver = notification.getResources().get(0);
243         assertEquals(vserverId, vserver.getId());
244         assertEquals("vserver", vserver.getType());
245         assertEquals(DataQuality.Status.ok, vserver.getDataQuality().getStatus());
246
247         verifyAttribute(vserver.getAttributeList(), "status", "ACTIVE");
248         verifyAttribute(vserver.getAttributeList(), "inMaintenance", "true");
249         verifyAttribute(vserver.getAttributeList(), "hostname", "norm-bouygues");
250         verifyAttribute(vserver.getAttributeList(), "vmState", "active");
251     }
252     
253     @Test
254     public void testDiscoverVserverFailureNotFound() throws Exception {
255         String vserverId = UUID.randomUUID().toString();
256
257         String resourcePath = MessageFormat.format("/v2.1/servers/{0}",
258                 new Object[] { vserverId });
259
260         String identityPath = "/v3/auth/tokens";
261  
262         this.openstackRule.stubFor(get(resourcePath).willReturn(WireMock.notFound()));
263
264         this.identityRule.stubFor(post(identityPath).willReturn(okJson("{}").withHeader("X-Subject-Token", "tokenId")));
265
266         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, null, this.requestId,
267                         RESOURCE_TYPE_VSERVER, Arrays.asList(vserverId));
268
269         assertEquals(Status.OK.getStatusCode(), response.getStatus());
270         NetworkDiscoveryNotification notification = (NetworkDiscoveryNotification) response.getEntity();
271         assertEquals(requestId, notification.getRequestId());
272         assertEquals(Status.OK.getStatusCode(), notification.getCode().intValue());
273         assertEquals(Boolean.TRUE, notification.getAckFinalIndicator());
274
275         assertEquals(1, notification.getResources().size());
276         Resource vserver = notification.getResources().get(0);
277         assertEquals(vserverId, vserver.getId());
278         assertEquals("vserver", vserver.getType());
279         assertEquals(DataQuality.Status.error, vserver.getDataQuality().getStatus());
280         assertNull(vserver.getAttributeList());
281     }
282
283     /**
284      * Verify API returns a final response indicating no discovery possible.
285      */
286     @Test
287     public void testUnsupportedResourceType() throws Exception {
288
289         String resourceType = "unsupported";
290         List<String> resourceIds = Arrays.asList("dummyId");
291         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
292                         this.requestId, resourceType, resourceIds);
293         assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
294     }
295     
296     @Test
297     public void testLoginFailure() throws Exception {
298         String vserverId = UUID.randomUUID().toString();
299
300         String identityPath = "/v3/auth/tokens";
301       
302         this.identityRule.stubFor(post(identityPath).willReturn(WireMock.unauthorized()));
303
304         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, null, this.requestId,
305                         RESOURCE_TYPE_VSERVER, Arrays.asList(vserverId));
306
307         assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
308     }
309     
310     @Test
311     public void testLoginFailureMissingToken() throws Exception {        
312         String vserverId = UUID.randomUUID().toString();
313         String identityPath = "/v3/auth/tokens";
314
315         this.identityRule.stubFor(post(identityPath).willReturn(okJson("{}")));
316         
317         Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, null, this.requestId,
318                         RESOURCE_TYPE_VSERVER, Arrays.asList(vserverId));
319
320         assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
321     }
322
323     private void verifyAttribute(List<Attribute> attributeList, String attrName, String attrValue) {
324         for (Attribute attr : attributeList) {
325             if (attr.getName().equals(attrName)) {
326                 assertEquals("Unexpected value for attribute " + attrName, attrValue, attr.getValue());
327                 return;
328             }
329         }
330         fail("Attribute " + attrName + " not found");
331     }
332
333 }