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