update link to upper-constraints.txt
[dmaap/datarouter.git] / datarouter-prov / src / test / java / org / onap / dmaap / datarouter / provisioning / DRFeedsServletTest.java
1 /*******************************************************************************
2  * ============LICENSE_START==================================================
3  * * org.onap.dmaap
4  * * ===========================================================================
5  * * Copyright © 2017 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  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  * *
22  ******************************************************************************/
23 package org.onap.dmaap.datarouter.provisioning;
24
25 import static org.mockito.ArgumentMatchers.anyString;
26 import static org.mockito.Mockito.contains;
27 import static org.mockito.Mockito.eq;
28 import static org.mockito.Mockito.mock;
29 import static org.mockito.Mockito.verify;
30 import static org.mockito.Mockito.when;
31 import static org.onap.dmaap.datarouter.provisioning.BaseServlet.BEHALF_HEADER;
32
33 import ch.qos.logback.classic.spi.ILoggingEvent;
34 import ch.qos.logback.core.read.ListAppender;
35 import jakarta.servlet.ServletOutputStream;
36 import java.util.HashSet;
37 import java.util.Set;
38 import javax.persistence.EntityManager;
39 import javax.persistence.EntityManagerFactory;
40 import javax.persistence.Persistence;
41 import jakarta.servlet.http.HttpServletRequest;
42 import jakarta.servlet.http.HttpServletResponse;
43 import org.apache.commons.lang3.reflect.FieldUtils;
44 import org.jetbrains.annotations.NotNull;
45 import org.json.JSONArray;
46 import org.json.JSONObject;
47 import org.junit.AfterClass;
48 import org.junit.Before;
49 import org.junit.BeforeClass;
50 import org.junit.Test;
51 import org.junit.runner.RunWith;
52 import org.mockito.Mock;
53 import org.onap.dmaap.datarouter.authz.AuthorizationResponse;
54 import org.onap.dmaap.datarouter.authz.Authorizer;
55 import org.onap.dmaap.datarouter.provisioning.beans.Insertable;
56 import org.onap.dmaap.datarouter.provisioning.utils.Poker;
57 import org.powermock.core.classloader.annotations.PowerMockIgnore;
58 import org.powermock.modules.junit4.PowerMockRunner;
59
60
61 @RunWith(PowerMockRunner.class)
62 @PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*"})
63 public class DRFeedsServletTest extends DrServletTestBase {
64
65     private static DRFeedsServlet drfeedsServlet;
66     private static EntityManagerFactory emf;
67     private static EntityManager em;
68
69     @Mock
70     private HttpServletRequest request;
71     @Mock
72     private HttpServletResponse response;
73
74     private ListAppender<ILoggingEvent> listAppender;
75
76     @BeforeClass
77     public static void init() {
78         emf = Persistence.createEntityManagerFactory("dr-unit-tests");
79         em = emf.createEntityManager();
80         System.setProperty(
81                 "org.onap.dmaap.datarouter.provserver.properties",
82                 "src/test/resources/h2Database.properties");
83     }
84
85     @AfterClass
86     public static void tearDownClass() {
87         em.clear();
88         em.close();
89         emf.close();
90     }
91
92     @Before
93     public void setUp() throws Exception {
94         listAppender = setTestLogger(DRFeedsServlet.class);
95         drfeedsServlet = new DRFeedsServlet();
96         setAuthoriserToReturnRequestIsAuthorized();
97         setPokerToNotCreateTimersWhenDeleteFeedIsCalled();
98         setupValidAuthorisedRequest();
99         setUpValidSecurityOnHttpRequest();
100         setUpValidContentHeadersAndJSONOnHttpRequest();
101     }
102
103     @Test
104     public void Given_Request_Is_HTTP_DELETE_SC_METHOD_NOT_ALLOWED_Response_Is_Generated() throws Exception {
105         drfeedsServlet.doDelete(request, response);
106         verify(response).sendError(eq(HttpServletResponse.SC_METHOD_NOT_ALLOWED), anyString());
107         verifyEnteringExitCalled(listAppender);
108     }
109
110     @Test
111     public void Given_Request_Is_HTTP_GET_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
112         throws Exception {
113         when(request.isSecure()).thenReturn(false);
114         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
115         drfeedsServlet.doGet(request, response);
116         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), anyString());
117         verifyEnteringExitCalled(listAppender);
118     }
119
120     @Test
121     public void Given_Request_Is_HTTP_GET_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated()
122         throws Exception {
123         setBehalfHeader(null);
124         drfeedsServlet.doGet(request, response);
125         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
126     }
127
128
129     @Test
130     public void Given_Request_Is_HTTP_GET_And_URL_Path_Not_Valid_Then_Bad_Request_Response_Is_Generated()
131         throws Exception {
132         when(request.getRequestURI()).thenReturn("/123");
133         drfeedsServlet.doGet(request, response);
134         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString());
135     }
136
137
138     @Test
139     public void Given_Request_Is_HTTP_GET_And_Request_Is_Not_Authorized_Then_Forbidden_Response_Is_Generated()
140         throws Exception {
141         setAuthoriserToReturnRequestNotAuthorized();
142         drfeedsServlet.doGet(request, response);
143         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), anyString());
144     }
145
146     @Test
147     public void Given_Request_Is_HTTP_GET_And_Request_Fails_With_Valid_Name_And_Version() throws Exception {
148         when(request.getParameter("name")).thenReturn("stub_name");
149         when(request.getParameter("version")).thenReturn("stub_version");
150         drfeedsServlet.doGet(request, response);
151         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
152     }
153
154     @Test
155     public void Given_Request_Is_HTTP_GET_And_Request_Succeeds_With_Valid_Name_And_Version() throws Exception {
156         ServletOutputStream outStream = mock(ServletOutputStream.class);
157         when(response.getOutputStream()).thenReturn(outStream);
158         when(request.getParameter("name")).thenReturn("Feed1");
159         when(request.getParameter("version")).thenReturn("v0.1");
160         drfeedsServlet.doGet(request, response);
161         verify(response).setStatus(eq(HttpServletResponse.SC_OK));
162         verify(response).setContentType(BaseServlet.FEEDFULL_CONTENT_TYPE);
163         verifyEnteringExitCalled(listAppender);
164     }
165
166
167     @Test
168     public void Given_Request_Is_HTTP_GET_And_Request_Succeeds_With_Invalid_Name_And_Version() throws Exception {
169         ServletOutputStream outStream = mock(ServletOutputStream.class);
170         when(response.getOutputStream()).thenReturn(outStream);
171         drfeedsServlet.doGet(request, response);
172         verify(response).setStatus(eq(HttpServletResponse.SC_OK));
173     }
174
175
176     @Test
177     public void Given_Request_Is_HTTP_PUT_SC_METHOD_NOT_ALLOWED_Response_Is_Generated() throws Exception {
178         drfeedsServlet.doPut(request, response);
179         verify(response).sendError(eq(HttpServletResponse.SC_METHOD_NOT_ALLOWED), anyString());
180         verifyEnteringExitCalled(listAppender);
181     }
182
183
184     @Test
185     public void Given_Request_Is_HTTP_POST_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
186         throws Exception {
187         when(request.isSecure()).thenReturn(false);
188         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
189         drfeedsServlet.doPost(request, response);
190         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), anyString());
191         verifyEnteringExitCalled(listAppender);
192     }
193
194     @Test
195     public void Given_Request_Is_HTTP_POST_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated()
196         throws Exception {
197         setBehalfHeader(null);
198         drfeedsServlet.doPost(request, response);
199         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
200     }
201
202
203     @Test
204     public void Given_Request_Is_HTTP_POST_And_URL_Path_Not_Valid_Then_Bad_Request_Response_Is_Generated()
205         throws Exception {
206         when(request.getRequestURI()).thenReturn("/123");
207         drfeedsServlet.doPost(request, response);
208         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString());
209     }
210
211
212     @Test
213     public void Given_Request_Is_HTTP_POST_And_Content_Header_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated()
214         throws Exception {
215         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.feed; version=1.1");
216         when(request.getContentType()).thenReturn("stub_contentType");
217         drfeedsServlet.doPost(request, response);
218         verify(response)
219             .sendError(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE), anyString());
220     }
221
222     @Test
223     public void Given_Request_Is_HTTP_POST_And_Request_Contains_Badly_Formed_JSON_Then_Bad_Request_Response_Is_Generated()
224         throws Exception {
225         drfeedsServlet.doPost(request, response);
226         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
227     }
228
229     @Test
230     public void Given_Request_Is_HTTP_POST_And_Active_Feeds_Equals_Max_Feeds_Then_Bad_Request_Response_Is_Generated()
231         throws Exception {
232         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "maxFeeds", 0, true);
233         DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
234             public JSONObject getJSONfromInput(HttpServletRequest req) {
235                 return new JSONObject();
236             }
237         };
238         drfeedsServlet.doPost(request, response);
239         verify(response).sendError(eq(HttpServletResponse.SC_CONFLICT), anyString());
240     }
241
242     @Test
243     public void Given_Request_Is_HTTP_POST_And_Feed_Is_Not_Valid_Object_Bad_Request_Response_Is_Generated()
244         throws Exception {
245         DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
246             public JSONObject getJSONfromInput(HttpServletRequest req) {
247                 return new JSONObject();
248             }
249         };
250
251         drfeedsServlet.doPost(request, response);
252         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
253     }
254
255     @Test
256     public void Given_Request_Is_HTTP_POST_And_Feed_Already_Exists_Bad_Request_Response_Is_Generated()
257         throws Exception {
258         when(request.getParameter("name")).thenReturn("Feed1");
259         when(request.getParameter("version")).thenReturn("v0.1");
260         JSONObject JSObject = buildRequestJsonObject();
261         DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
262             public JSONObject getJSONfromInput(HttpServletRequest req) {
263                 JSONObject jo = new JSONObject();
264                 jo.put("name", "Feed1");
265                 jo.put("version", "v0.1");
266                 jo.put("authorization", JSObject);
267                 return jo;
268             }
269         };
270         drfeedsServlet.doPost(request, response);
271         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), contains("This feed already exists in the database"));
272     }
273
274     @Test
275     public void Given_Request_Is_HTTP_POST_And_POST_Fails_Bad_Request_Response_Is_Generated() throws Exception {
276         JSONObject JSObject = buildRequestJsonObject();
277         DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
278             public JSONObject getJSONfromInput(HttpServletRequest req) {
279                 JSONObject jo = new JSONObject();
280                 jo.put("name", "stub_name");
281                 jo.put("version", "2.0");
282                 jo.put("authorization", JSObject);
283                 return jo;
284             }
285
286             @Override
287             protected boolean doInsert(Insertable bean) {
288                 return false;
289             }
290         };
291         drfeedsServlet.doPost(request, response);
292         verify(response)
293             .sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), anyString());
294     }
295
296     @NotNull
297     private JSONObject buildRequestJsonObject() {
298         JSONObject JSObject = new JSONObject();
299         JSONArray endpointIDs = new JSONArray();
300         JSONObject JOEndpointIDs = new JSONObject();
301         JOEndpointIDs.put("id", "stub_endpoint_id");
302         JOEndpointIDs.put("password", "stub_endpoint_password");
303         endpointIDs.put(JOEndpointIDs);
304
305         JSONArray endpointAddresses = new JSONArray();
306         endpointAddresses.put("127.0.0.1");
307
308         JSObject.put("classification", "stub_classification");
309         JSObject.put("endpoint_ids", endpointIDs);
310         JSObject.put("endpoint_addrs", endpointAddresses);
311         return JSObject;
312     }
313
314     private void setUpValidSecurityOnHttpRequest() throws Exception {
315         when(request.isSecure()).thenReturn(true);
316         Set<String> authAddressesAndNetworks = new HashSet<>();
317         authAddressesAndNetworks.add(("127.0.0.1"));
318         FieldUtils
319             .writeDeclaredStaticField(BaseServlet.class, "authorizedAddressesAndNetworks", authAddressesAndNetworks,
320                 true);
321         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "requireCert", false, true);
322         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "maxFeeds", 100, true);
323     }
324
325     private void setBehalfHeader(String headerValue) {
326         when(request.getHeader(BEHALF_HEADER)).thenReturn(headerValue);
327     }
328
329     private void setAuthoriserToReturnRequestNotAuthorized() throws IllegalAccessException {
330         AuthorizationResponse authResponse = mock(AuthorizationResponse.class);
331         Authorizer authorizer = mock(Authorizer.class);
332         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authz", authorizer, true);
333         when(authorizer.decide(request)).thenReturn(authResponse);
334         when(authResponse.isAuthorized()).thenReturn(false);
335     }
336
337     private void setAuthoriserToReturnRequestIsAuthorized() throws IllegalAccessException {
338         AuthorizationResponse authResponse = mock(AuthorizationResponse.class);
339         Authorizer authorizer = mock(Authorizer.class);
340         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authz", authorizer, true);
341         when(authorizer.decide(request)).thenReturn(authResponse);
342         when(authResponse.isAuthorized()).thenReturn(true);
343     }
344
345     private void setPokerToNotCreateTimersWhenDeleteFeedIsCalled() throws Exception {
346         Poker poker = mock(Poker.class);
347         FieldUtils.writeDeclaredStaticField(Poker.class, "poker", poker, true);
348     }
349
350     private void setupValidAuthorisedRequest() throws Exception {
351         setUpValidSecurityOnHttpRequest();
352         setBehalfHeader("Stub_Value");
353     }
354
355     private void setUpValidContentHeadersAndJSONOnHttpRequest() throws IllegalAccessException {
356         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.feed; version=1.0");
357         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup");
358     }
359 }