67ad98b660c40bfa0579ca4f51fecb99df939007
[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.servicedecomposition.test;
20
21 import static com.github.tomakehurst.wiremock.client.WireMock.get;
22 import static com.github.tomakehurst.wiremock.client.WireMock.notFound;
23 import static com.github.tomakehurst.wiremock.client.WireMock.okJson;
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.github.tomakehurst.wiremock.junit.WireMockRule;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.InputStreamReader;
34 import java.util.Base64;
35 import javax.servlet.http.HttpServletRequest;
36 import javax.ws.rs.core.HttpHeaders;
37 import javax.ws.rs.core.Response;
38 import javax.ws.rs.core.Response.Status;
39 import org.json.JSONArray;
40 import org.json.JSONObject;
41 import org.junit.Rule;
42 import org.junit.Test;
43 import org.junit.runner.RunWith;
44 import org.onap.logging.ref.slf4j.ONAPLogConstants;
45 import org.onap.sdnc.apps.pomba.servicedecomposition.Application;
46 import org.onap.sdnc.apps.pomba.servicedecomposition.PropertyPasswordConfiguration;
47 import org.onap.sdnc.apps.pomba.servicedecomposition.service.rs.RestService;
48 import org.springframework.beans.factory.annotation.Autowired;
49 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
50 import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
51 import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
52 import org.springframework.boot.test.context.SpringBootTest;
53 import org.springframework.test.context.ContextConfiguration;
54 import org.springframework.test.context.TestPropertySource;
55 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
56 import org.springframework.test.context.web.WebAppConfiguration;
57
58 @RunWith(SpringJUnit4ClassRunner.class)
59 @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
60 @WebAppConfiguration
61 @SpringBootTest
62 @TestPropertySource(properties = {
63         "aai.httpProtocol=http",
64         "aai.host=localhost",
65         "aai.port=8081",
66         "basicAuth.username=admin",
67         "basicAuth.password=password(OBF:1u2a1toa1w8v1tok1u30)"
68 })
69 @ContextConfiguration(initializers = PropertyPasswordConfiguration.class, classes = Application.class)
70 public class ServiceDecompositionTest {
71
72     private static final String AUTH = "Basic " + Base64.getEncoder().encodeToString(("admin:admin").getBytes());
73
74     // TODO missing code coverage for VNFC resources
75
76     @Rule
77     public WireMockRule aai = new WireMockRule(wireMockConfig().port(8081));
78
79     @Autowired
80     private RestService service;
81
82     /**
83      * Simulation of the firewall demo service, using json captured from real A&AI queries.
84      * The resource relationship looks something like.
85      * <pre>
86      * service instance
87      * +- generic-vnf 1
88      * |  +- vserver
89      * +- generic-vnf 2
90      *    +- network 1
91      *    +- network 2
92      * </pre>
93      */
94     @Test
95     public void testDemoFirewallService() throws Exception {
96         // setup A&AI responses
97         addResponse(
98                 "/aai/v13/nodes/service-instance/c6456519-6acf-4adb-997c-3c363dd4caaf",
99                 "junit/aai-service-instance.json");
100         addResponse(
101                 "/aai/v13/network/generic-vnfs/generic-vnf/6700c313-fbb7-4cf9-ac70-0293ec56df68?depth=2",
102                 "junit/aai-generic-vnf1.json");
103         addResponse(
104                 "/aai/v13/network/generic-vnfs/generic-vnf/8a9ddb25-2e79-449c-a40d-5011bac0da39?depth=2",
105                 "junit/aai-generic-vnf2.json");
106         addResponse(
107                 "/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/RegionOne/tenants/tenant"
108                         + "/b49b830686654191bb1e952a74b014ad/vservers/vserver/b494cd6e-b9f3-45e0-afe7-e1d1a5f5d74a",
109                 "junit/aai-vserver.json");
110         addResponse(
111                 "/aai/v13/network/l3-networks/l3-network/HNP1d77c-1094-41ec-b7f3-94bb30951870",
112                 "junit/aai-l3-network1.json");
113         addResponse(
114                 "/aai/v13/network/l3-networks/l3-network/HNP1d77c-1094-41ec-b7f3-94bb30951872",
115                 "junit/aai-l3-network2.json");
116
117         final String serviceInstanceId = "c6456519-6acf-4adb-997c-3c363dd4caaf";
118         final String vnfId1 = "6700c313-fbb7-4cf9-ac70-0293ec56df68";
119         final String vnfId2 = "8a9ddb25-2e79-449c-a40d-5011bac0da39";
120         final String vserverId = "b494cd6e-b9f3-45e0-afe7-e1d1a5f5d74a";
121         final String networkId1 = "HNP1d77c-1094-41ec-b7f3-94bb30951870";
122         final String networkId2 = "HNP1d77c-1094-41ec-b7f3-94bb30951872";
123
124         HttpServletRequest httpRequest = new TestHttpServletRequest();
125         Response response = this.service.getContext(httpRequest, AUTH, "network-discovery-context-builder", null,
126                 serviceInstanceId);
127         assertEquals(200, response.getStatus());
128
129         JSONObject serviceInstance = new JSONObject((String)response.getEntity());
130
131         // verify two generic-vnfs added to service instance data
132         verifyResource(serviceInstance, "generic-vnfs", "vnf-id", vnfId1);
133         verifyResource(serviceInstance, "generic-vnfs", "vnf-id", vnfId2);
134
135         JSONArray vnfs = serviceInstance.getJSONArray("generic-vnfs");
136         for (int i = 0; i < vnfs.length(); i++) {
137             JSONObject vnf = vnfs.getJSONObject(i);
138             String vnfId = vnf.getString("vnf-id");
139             switch (vnfId) {
140                 case vnfId1:
141                     // verify vserver resource
142                     verifyResource(vnf, "vservers", "vserver-id", vserverId);
143                     break;
144                 case vnfId2:
145                     // verify network resources
146                     verifyResource(vnf, "l3-networks", "network-id", networkId1);
147                     verifyResource(vnf, "l3-networks", "network-id", networkId2);
148                     break;
149                 default:
150                     fail("Unexpected generic-vnf " + vnfId);
151             }
152         }
153     }
154
155     @Test
156     public void testNoAuthHeader() throws Exception {
157         String fromAppId = "junit";
158         String transactionId = null;
159         String serviceInstanceId = "aServiceInstanceId";
160         // no Authorization header
161         Response response = this.service.getContext(new TestHttpServletRequest(), null, fromAppId, transactionId,
162                 serviceInstanceId);
163         assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
164         // should get WWW-Authenticate header in response
165         assertTrue(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE).startsWith("Basic realm"));
166     }
167
168     @Test
169     public void testUnauthorized() throws Exception {
170         // bad credentials
171         String authorization = "Basic " + Base64.getEncoder().encodeToString("aaa:bbb".getBytes());
172         String fromAppId = "junit";
173         String transactionId = null;
174         String serviceInstanceId = "aServiceInstanceId";
175
176         Response response = this.service.getContext(new TestHttpServletRequest(), authorization, fromAppId,
177                 transactionId, serviceInstanceId);
178         assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
179         // should not get WWW-Authenticate header in response
180         assertNull(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE));
181     }
182
183     /** Fail if calling app name is missing. */
184     @Test
185     public void verifyFromAppId() throws Exception {
186         String fromAppId = null;
187         String transactionId = null;
188         String serviceInstanceId = "someValue";
189
190         Response response = this.service.getContext(new TestHttpServletRequest(), AUTH, fromAppId, transactionId,
191                 serviceInstanceId);
192         assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
193         assertTrue(((String)response.getEntity()).contains(ONAPLogConstants.Headers.PARTNER_NAME));
194     }
195
196     /** Fail if service instance id is missing. */
197     @Test
198     public void verifyServiceInstanceId() throws Exception {
199         String fromAppId = "junit";
200         String transactionId = null;
201         String serviceInstanceId = null;
202
203         Response response = this.service.getContext(new TestHttpServletRequest(), AUTH, fromAppId, transactionId,
204                 serviceInstanceId);
205         assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
206         assertTrue(((String)response.getEntity()).contains("service-instance-id"));
207     }
208
209     /** Unknown service-instance-id return HTTP 404. */
210     @Test
211     public void testInvalidServiceId() throws Exception {
212         aai.stubFor(get("/aai/v13/nodes/service-instance/noSuchServiceId").willReturn(notFound()));
213
214         Response response =
215                 this.service.getContext(new TestHttpServletRequest(), AUTH, "junit", null, "noSuchServiceId");
216
217         assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
218     }
219
220     private void verifyResource(JSONObject parent, String arrayName, String field, String value) {
221         JSONArray array = parent.getJSONArray(arrayName);
222         for (int i = 0; i < array.length(); i++) {
223             JSONObject item = array.getJSONObject(i);
224             if (value.equals(item.getString(field))) {
225                 return;
226             }
227         }
228         fail("Did not find " + field + "=" + value + " in " + arrayName + " array");
229     }
230
231     private void addResponse(String path, String classpathResource) throws IOException {
232         String payload = readFully(ClassLoader.getSystemResourceAsStream(classpathResource));
233         aai.stubFor(get(path).willReturn(okJson(payload)));
234     }
235
236     private String readFully(InputStream in) throws IOException {
237         char[] cbuf = new char[1024];
238         StringBuilder content = new StringBuilder();
239         try (InputStreamReader reader = new InputStreamReader(in, "UTF-8")) {
240             int count;
241             while ((count = reader.read(cbuf)) >= 0) {
242                 content.append(cbuf, 0, count);
243             }
244         }
245         return content.toString();
246     }
247 }