update link to upper-constraints.txt
[dmaap/datarouter.git] / datarouter-prov / src / test / java / org / onap / dmaap / datarouter / provisioning / SubscribeServletTest.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.JSONObject;
46 import org.junit.AfterClass;
47 import org.junit.Before;
48 import org.junit.BeforeClass;
49 import org.junit.Test;
50 import org.junit.runner.RunWith;
51 import org.mockito.Mock;
52 import org.onap.dmaap.datarouter.authz.AuthorizationResponse;
53 import org.onap.dmaap.datarouter.authz.Authorizer;
54 import org.onap.dmaap.datarouter.provisioning.beans.Insertable;
55 import org.onap.dmaap.datarouter.provisioning.utils.Poker;
56 import org.onap.dmaap.datarouter.provisioning.utils.ProvDbUtils;
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 SubscribeServletTest extends DrServletTestBase {
64     private static SubscribeServlet subscribeServlet;
65     private static EntityManagerFactory emf;
66     private static EntityManager em;
67
68     @Mock
69     private HttpServletRequest request;
70     @Mock
71     private HttpServletResponse response;
72
73     private ListAppender<ILoggingEvent> listAppender;
74
75     @BeforeClass
76     public static void init() {
77         emf = Persistence.createEntityManagerFactory("dr-unit-tests");
78         em = emf.createEntityManager();
79         System.setProperty(
80                 "org.onap.dmaap.datarouter.provserver.properties",
81                 "src/test/resources/h2Database.properties");
82     }
83
84     @AfterClass
85     public static void tearDownClass() {
86         em.clear();
87         em.close();
88         emf.close();
89     }
90
91     @Before
92     public void setUp() throws Exception {
93         ProvDbUtils.getInstance().initProvDB();
94         listAppender = setTestLogger(SubscribeServlet.class);
95         subscribeServlet = new SubscribeServlet();
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         subscribeServlet.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() throws Exception {
112         when(request.isSecure()).thenReturn(false);
113         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
114         subscribeServlet.doGet(request, response);
115         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), anyString());
116         verifyEnteringExitCalled(listAppender);
117     }
118
119     @Test
120     public void Given_Request_Is_HTTP_GET_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated() throws Exception {
121         setBehalfHeader(null);
122         subscribeServlet.doGet(request, response);
123         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
124     }
125
126
127     @Test
128     public void Given_Request_Is_HTTP_GET_And_Path_Header_Is_Not_Set_In_Request_With_Valid_Path_Then_Bad_Request_Response_Is_Generated() throws Exception {
129         when(request.getPathInfo()).thenReturn(null);
130         subscribeServlet.doGet(request, response);
131         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
132     }
133
134     @Test
135     public void Given_Request_Is_HTTP_GET_And_Feed_Id_Is_Invalid_Then_Not_Found_Response_Is_Generated() throws Exception {
136         when(request.getPathInfo()).thenReturn("/123");
137         subscribeServlet.doGet(request, response);
138         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString());
139     }
140
141     @Test
142     public void Given_Request_Is_HTTP_GET_And_Request_Succeeds() throws Exception {
143         ServletOutputStream outStream = mock(ServletOutputStream.class);
144         when(response.getOutputStream()).thenReturn(outStream);
145         when(request.getPathInfo()).thenReturn("/1");
146         subscribeServlet.doGet(request, response);
147         verify(response).setStatus(eq(HttpServletResponse.SC_OK));
148         verifyEnteringExitCalled(listAppender);
149     }
150
151
152     @Test
153     public void Given_Request_Is_HTTP_PUT_SC_METHOD_NOT_ALLOWED_Response_Is_Generated() throws Exception {
154         subscribeServlet.doPut(request, response);
155         verify(response).sendError(eq(HttpServletResponse.SC_METHOD_NOT_ALLOWED), anyString());
156         verifyEnteringExitCalled(listAppender);
157     }
158     @Test
159     public void Given_Request_Is_HTTP_POST_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated() throws Exception {
160         when(request.isSecure()).thenReturn(false);
161         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
162         subscribeServlet.doPost(request, response);
163         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), anyString());
164         verifyEnteringExitCalled(listAppender);
165     }
166
167     @Test
168     public void Given_Request_Is_HTTP_POST_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated() throws Exception {
169         setBehalfHeader(null);
170         subscribeServlet.doPost(request, response);
171         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
172     }
173
174
175     @Test
176     public void Given_Request_Is_HTTP_POST_And_Path_Header_Is_Not_Set_In_Request_With_Valid_Path_Then_Bad_Request_Response_Is_Generated() throws Exception {
177         when(request.getPathInfo()).thenReturn(null);
178         subscribeServlet.doPost(request, response);
179         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
180     }
181
182
183     @Test
184     public void Given_Request_Is_HTTP_POST_And_Feed_Id_Is_Invalid_Then_Not_Found_Response_Is_Generated() throws Exception {
185         when(request.getPathInfo()).thenReturn("/123");
186         subscribeServlet.doPost(request, response);
187         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString());
188     }
189
190     @Test
191     public void Given_Request_Is_HTTP_POST_And_Password_Is_Too_Long_Then_Bad_Request_Response_Is_Generated() throws Exception {
192         when(request.getPathInfo()).thenReturn("/1");
193         JSONObject JSObject = buildRequestJsonObject();
194         JSObject.put("password", "aervaervaervgaervaestbnswtrnsrnsrdtnsrtnsrtnydstyndtrynsrnsrtnsrtnsrtnswtrnswtrn");
195         SubscribeServlet subscribeServlet = new SubscribeServlet() {
196              public JSONObject getJSONfromInput(HttpServletRequest req) {
197                 JSONObject jo = new JSONObject();
198                 jo.put("name", "stub_name");
199                 jo.put("version", "2.0");
200                 jo.put("metadataOnly", true);
201                 jo.put("suspend", true);
202                 jo.put("delivery", JSObject);
203                 jo.put("sync", false);
204                 return jo;
205             }
206
207         };
208         subscribeServlet.doPost(request, response);
209         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
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() throws Exception {
214         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.feed; version=1.1");
215         when(request.getContentType()).thenReturn("stub_contentType");
216         when(request.getPathInfo()).thenReturn("/1");
217         subscribeServlet.doPost(request, response);
218         verify(response).sendError(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE), anyString());
219     }
220
221     @Test
222     public void Given_Request_Is_HTTP_POST_And_Request_Contains_Badly_Formed_JSON_Then_Bad_Request_Response_Is_Generated() throws Exception {
223         when(request.getPathInfo()).thenReturn("/1");
224         subscribeServlet.doPost(request, response);
225         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), anyString());
226     }
227
228     @Test
229     public void Given_Request_Is_HTTP_POST_And_Active_Feeds_Equals_Max_Feeds_Then_Bad_Request_Response_Is_Generated() throws Exception {
230         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "maxSubs", 0, true);
231         when(request.getPathInfo()).thenReturn("/1");
232         SubscribeServlet subscribeServlet = new SubscribeServlet() {
233             public JSONObject getJSONfromInput(HttpServletRequest req) {
234                 return new JSONObject();
235             }
236         };
237         subscribeServlet.doPost(request, response);
238         verify(response).sendError(eq(HttpServletResponse.SC_CONFLICT), anyString());
239     }
240
241     @Test
242     public void Given_Request_Is_HTTP_POST_And_POST_Fails_Bad_Request_Response_Is_Generated() throws Exception {
243         when(request.getPathInfo()).thenReturn("/1");
244         JSONObject JSObject = buildRequestJsonObject();
245         SubscribeServlet subscribeServlet = new SubscribeServlet() {
246             public JSONObject getJSONfromInput(HttpServletRequest req) {
247                 JSONObject jo = new JSONObject();
248                 jo.put("name", "stub_name");
249                 jo.put("version", "2.0");
250                 jo.put("metadataOnly", true);
251                 jo.put("suspend", true);
252                 jo.put("delivery", JSObject);
253                 jo.put("follow_redirect", false);
254                 jo.put("sync", false);
255                 return jo;
256             }
257
258             @Override
259             protected boolean doInsert(Insertable bean) {
260                 return false;
261             }
262         };
263         subscribeServlet.doPost(request, response);
264         verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), anyString());
265     }
266
267     @NotNull
268     private JSONObject buildRequestJsonObject() {
269         JSONObject JSObject = new JSONObject();
270         JSObject.put("url", "https://stub_address");
271         JSObject.put("use100", "true");
272         JSObject.put("password", "stub_password");
273         JSObject.put("user", "stub_user");
274         return JSObject;
275     }
276
277     private void setUpValidSecurityOnHttpRequest() throws Exception {
278         when(request.isSecure()).thenReturn(true);
279         Set<String> authAddressesAndNetworks = new HashSet<>();
280         authAddressesAndNetworks.add(("127.0.0.1"));
281         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authorizedAddressesAndNetworks", authAddressesAndNetworks, true);
282         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "requireCert", false, true);
283         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "maxSubs", 100, true);
284     }
285
286     private void setBehalfHeader(String headerValue) {
287         when(request.getHeader(BEHALF_HEADER)).thenReturn(headerValue);
288     }
289
290     private void setAuthoriserToReturnRequestNotAuthorized() throws IllegalAccessException {
291         AuthorizationResponse authResponse = mock(AuthorizationResponse.class);
292         Authorizer authorizer = mock(Authorizer.class);
293         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authz", authorizer, true);
294         when(authorizer.decide(request)).thenReturn(authResponse);
295         when(authResponse.isAuthorized()).thenReturn(false);
296     }
297
298     private void setAuthoriserToReturnRequestIsAuthorized() throws IllegalAccessException {
299         AuthorizationResponse authResponse = mock(AuthorizationResponse.class);
300         Authorizer authorizer = mock(Authorizer.class);
301         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authz", authorizer, true);
302         when(authorizer.decide(request)).thenReturn(authResponse);
303         when(authResponse.isAuthorized()).thenReturn(true);
304     }
305
306     private void setPokerToNotCreateTimersWhenDeleteFeedIsCalled() throws Exception {
307         Poker poker = mock(Poker.class);
308         FieldUtils.writeDeclaredStaticField(Poker.class, "poker", poker, true);
309     }
310
311     private void setupValidAuthorisedRequest() throws Exception {
312         setUpValidSecurityOnHttpRequest();
313         setBehalfHeader("Stub_Value");
314     }
315
316     private void setUpValidContentHeadersAndJSONOnHttpRequest() {
317         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.subscription; version=1.0");
318         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup");
319
320     }
321 }