Replace ATT headers
[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.hamcrest.Matchers.notNullValue;
26 import static org.mockito.Mockito.anyInt;
27 import static org.mockito.Mockito.anyString;
28 import static org.mockito.Mockito.argThat;
29 import static org.mockito.Mockito.eq;
30 import static org.mockito.Mockito.mock;
31 import static org.mockito.Mockito.verify;
32 import static org.mockito.Mockito.when;
33 import static org.onap.dmaap.datarouter.provisioning.BaseServlet.BEHALF_HEADER;
34
35 import java.util.HashSet;
36 import java.util.Set;
37 import javax.servlet.ServletOutputStream;
38 import javax.servlet.http.HttpServletRequest;
39 import javax.servlet.http.HttpServletResponse;
40
41 import ch.qos.logback.classic.spi.ILoggingEvent;
42 import ch.qos.logback.core.read.ListAppender;
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.Before;
48 import org.junit.Test;
49 import org.junit.runner.RunWith;
50 import org.mockito.Mock;
51 import org.onap.dmaap.datarouter.authz.AuthorizationResponse;
52 import org.onap.dmaap.datarouter.authz.Authorizer;
53 import org.onap.dmaap.datarouter.provisioning.beans.Feed;
54 import org.onap.dmaap.datarouter.provisioning.beans.Insertable;
55 import org.powermock.api.mockito.PowerMockito;
56 import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
57 import org.powermock.modules.junit4.PowerMockRunner;
58
59
60 @RunWith(PowerMockRunner.class)
61 @SuppressStaticInitializationFor("org.onap.dmaap.datarouter.provisioning.beans.Feed")
62 public class DRFeedsServletTest extends DrServletTestBase {
63
64     private static DRFeedsServlet drfeedsServlet;
65
66     @Mock
67     private HttpServletRequest request;
68     @Mock
69     private HttpServletResponse response;
70
71     ListAppender<ILoggingEvent> listAppender;
72
73     @Before
74     public void setUp() throws Exception {
75         super.setUp();
76         listAppender = setTestLogger(DRFeedsServlet.class);
77         drfeedsServlet = new DRFeedsServlet();
78         setAuthoriserToReturnRequestIsAuthorized();
79         setPokerToNotCreateTimersWhenDeleteFeedIsCalled();
80         setupValidAuthorisedRequest();
81         setUpValidSecurityOnHttpRequest();
82         setUpValidContentHeadersAndJSONOnHttpRequest();
83     }
84
85     @Test
86     public void Given_Request_Is_HTTP_DELETE_SC_METHOD_NOT_ALLOWED_Response_Is_Generated() throws Exception {
87         drfeedsServlet.doDelete(request, response);
88         verify(response).sendError(eq(HttpServletResponse.SC_METHOD_NOT_ALLOWED), argThat(notNullValue(String.class)));
89         verifyEnteringExitCalled(listAppender);
90     }
91
92     @Test
93     public void Given_Request_Is_HTTP_GET_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
94         throws Exception {
95         when(request.isSecure()).thenReturn(false);
96         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
97         drfeedsServlet.doGet(request, response);
98         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
99         verifyEnteringExitCalled(listAppender);
100     }
101
102     @Test
103     public void Given_Request_Is_HTTP_GET_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated()
104         throws Exception {
105         setBehalfHeader(null);
106         drfeedsServlet.doGet(request, response);
107         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
108     }
109
110
111     @Test
112     public void Given_Request_Is_HTTP_GET_And_URL_Path_Not_Valid_Then_Bad_Request_Response_Is_Generated()
113         throws Exception {
114         when(request.getRequestURI()).thenReturn("/123");
115         drfeedsServlet.doGet(request, response);
116         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
117     }
118
119
120     @Test
121     public void Given_Request_Is_HTTP_GET_And_Request_Is_Not_Authorized_Then_Forbidden_Response_Is_Generated()
122         throws Exception {
123         setAuthoriserToReturnRequestNotAuthorized();
124         drfeedsServlet.doGet(request, response);
125         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
126     }
127
128     @Test
129     public void Given_Request_Is_HTTP_GET_And_Request_Fails_With_Valid_Name_And_Version() throws Exception {
130         when(request.getParameter("name")).thenReturn("stub_name");
131         when(request.getParameter("version")).thenReturn("stub_version");
132         drfeedsServlet.doGet(request, response);
133         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
134     }
135
136     @Test
137     public void Given_Request_Is_HTTP_GET_And_Request_Succeeds_With_Valid_Name_And_Version() throws Exception {
138         ServletOutputStream outStream = mock(ServletOutputStream.class);
139         when(response.getOutputStream()).thenReturn(outStream);
140         when(request.getParameter("name")).thenReturn("stub_name");
141         when(request.getParameter("version")).thenReturn("stub_version");
142         PowerMockito.mockStatic(Feed.class);
143         Feed feed = mock(Feed.class);
144         PowerMockito.when(Feed.getFeedByNameVersion(anyString(), anyString())).thenReturn(feed);
145         when(feed.asJSONObject(true)).thenReturn(mock(JSONObject.class));
146         drfeedsServlet.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_GET_And_Request_Succeeds_With_Invalid_Name_And_Version() throws Exception {
154         ServletOutputStream outStream = mock(ServletOutputStream.class);
155         when(response.getOutputStream()).thenReturn(outStream);
156         drfeedsServlet.doGet(request, response);
157         verify(response).setStatus(eq(HttpServletResponse.SC_OK));
158     }
159
160
161     @Test
162     public void Given_Request_Is_HTTP_PUT_SC_METHOD_NOT_ALLOWED_Response_Is_Generated() throws Exception {
163         drfeedsServlet.doPut(request, response);
164         verify(response).sendError(eq(HttpServletResponse.SC_METHOD_NOT_ALLOWED), argThat(notNullValue(String.class)));
165         verifyEnteringExitCalled(listAppender);
166     }
167
168
169     @Test
170     public void Given_Request_Is_HTTP_POST_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
171         throws Exception {
172         when(request.isSecure()).thenReturn(false);
173         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
174         drfeedsServlet.doPost(request, response);
175         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
176         verifyEnteringExitCalled(listAppender);
177     }
178
179     @Test
180     public void Given_Request_Is_HTTP_POST_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated()
181         throws Exception {
182         setBehalfHeader(null);
183         drfeedsServlet.doPost(request, response);
184         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
185     }
186
187
188     @Test
189     public void Given_Request_Is_HTTP_POST_And_URL_Path_Not_Valid_Then_Bad_Request_Response_Is_Generated()
190         throws Exception {
191         when(request.getRequestURI()).thenReturn("/123");
192         drfeedsServlet.doPost(request, response);
193         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
194     }
195
196
197     @Test
198     public void Given_Request_Is_HTTP_POST_And_Content_Header_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated()
199         throws Exception {
200         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.feed; version=1.1");
201         when(request.getContentType()).thenReturn("stub_contentType");
202         drfeedsServlet.doPost(request, response);
203         verify(response)
204             .sendError(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE), argThat(notNullValue(String.class)));
205     }
206
207     @Test
208     public void Given_Request_Is_HTTP_POST_And_Request_Is_Not_Authorized_Then_Forbidden_Response_Is_Generated()
209         throws Exception {
210         setAuthoriserToReturnRequestNotAuthorized();
211         drfeedsServlet.doPost(request, response);
212         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
213     }
214
215     @Test
216     public void Given_Request_Is_HTTP_POST_And_Request_Contains_Badly_Formed_JSON_Then_Bad_Request_Response_Is_Generated()
217         throws Exception {
218         drfeedsServlet.doPost(request, response);
219         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
220     }
221
222     @Test
223     public void Given_Request_Is_HTTP_POST_And_Active_Feeds_Equals_Max_Feeds_Then_Bad_Request_Response_Is_Generated()
224         throws Exception {
225         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "maxFeeds", 0, true);
226         DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
227             protected JSONObject getJSONfromInput(HttpServletRequest req) {
228                 return new JSONObject();
229             }
230         };
231         drfeedsServlet.doPost(request, response);
232         verify(response).sendError(eq(HttpServletResponse.SC_CONFLICT), argThat(notNullValue(String.class)));
233     }
234
235     @Test
236     public void Given_Request_Is_HTTP_POST_And_Feed_Is_Not_Valid_Object_Bad_Request_Response_Is_Generated()
237         throws Exception {
238         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF-GROUP")).thenReturn(null);
239         JSONObject JSObject = buildRequestJsonObject();
240
241         DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
242             protected JSONObject getJSONfromInput(HttpServletRequest req) {
243                 JSONObject jo = new JSONObject();
244                 return jo;
245             }
246         };
247
248         drfeedsServlet.doPost(request, response);
249         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
250     }
251
252     @Test
253     public void Given_Request_Is_HTTP_POST_And_Feed_Already_Exists_Bad_Request_Response_Is_Generated()
254         throws Exception {
255         setFeedToReturnInvalidFeedIdSupplied();
256         JSONObject JSObject = buildRequestJsonObject();
257         DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
258             protected JSONObject getJSONfromInput(HttpServletRequest req) {
259                 JSONObject jo = new JSONObject();
260                 jo.put("name", "not_stub_name");
261                 jo.put("version", "1.0");
262                 jo.put("authorization", JSObject);
263                 return jo;
264             }
265         };
266         drfeedsServlet.doPost(request, response);
267         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
268     }
269
270     @Test
271     public void Given_Request_Is_HTTP_POST_And_POST_Fails_Bad_Request_Response_Is_Generated() throws Exception {
272         JSONObject JSObject = buildRequestJsonObject();
273         DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
274             protected JSONObject getJSONfromInput(HttpServletRequest req) {
275                 JSONObject jo = new JSONObject();
276                 jo.put("name", "stub_name");
277                 jo.put("version", "2.0");
278                 jo.put("authorization", JSObject);
279                 return jo;
280             }
281
282             @Override
283             protected boolean doInsert(Insertable bean) {
284                 return false;
285             }
286         };
287         drfeedsServlet.doPost(request, response);
288         verify(response)
289             .sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), argThat(notNullValue(String.class)));
290     }
291
292
293     @Test
294     public void Given_Request_Is_HTTP_POST_And_Change_On_Feeds_Succeeds_A_STATUS_OK_Response_Is_Generated()
295         throws Exception {
296         ServletOutputStream outStream = mock(ServletOutputStream.class);
297         when(response.getOutputStream()).thenReturn(outStream);
298         JSONObject JSObject = buildRequestJsonObject();
299         DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
300             protected JSONObject getJSONfromInput(HttpServletRequest req) {
301                 JSONObject jo = new JSONObject();
302                 jo.put("name", "stub_name");
303                 jo.put("version", "1.0");
304                 jo.put("authorization", JSObject);
305                 return jo;
306             }
307
308             @Override
309             protected boolean doInsert(Insertable bean) {
310                 return true;
311             }
312         };
313         drfeedsServlet.doPost(request, response);
314         verify(response).setStatus(eq(HttpServletResponse.SC_CREATED));
315         verifyEnteringExitCalled(listAppender);
316     }
317
318     @NotNull
319     private JSONObject buildRequestJsonObject() {
320         JSONObject JSObject = new JSONObject();
321         JSONArray endpointIDs = new JSONArray();
322         JSONObject JOEndpointIDs = new JSONObject();
323         JOEndpointIDs.put("id", "stub_endpoint_id");
324         JOEndpointIDs.put("password", "stub_endpoint_password");
325         endpointIDs.put(JOEndpointIDs);
326
327         JSONArray endpointAddresses = new JSONArray();
328         endpointAddresses.put("127.0.0.1");
329
330         JSObject.put("classification", "stub_classification");
331         JSObject.put("endpoint_ids", endpointIDs);
332         JSObject.put("endpoint_addrs", endpointAddresses);
333         return JSObject;
334     }
335
336     private void setUpValidSecurityOnHttpRequest() throws Exception {
337         when(request.isSecure()).thenReturn(true);
338         Set<String> authAddressesAndNetworks = new HashSet<String>();
339         authAddressesAndNetworks.add(("127.0.0.1"));
340         FieldUtils
341             .writeDeclaredStaticField(BaseServlet.class, "authorizedAddressesAndNetworks", authAddressesAndNetworks,
342                 true);
343         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "requireCert", false, true);
344         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "maxFeeds", 100, true);
345     }
346
347     private void setBehalfHeader(String headerValue) {
348         when(request.getHeader(BEHALF_HEADER)).thenReturn(headerValue);
349     }
350
351     private void setValidPathInfoInHttpHeader() {
352         when(request.getPathInfo()).thenReturn("/123");
353     }
354
355     private void setFeedToReturnInvalidFeedIdSupplied() {
356         PowerMockito.mockStatic(Feed.class);
357         PowerMockito.when(Feed.getFeedById(anyInt())).thenReturn(null);
358         when(Feed.getFeedByNameVersion(anyString(), anyString())).thenReturn(mock(Feed.class));
359     }
360
361     private void setFeedToReturnValidFeedForSuppliedId() {
362         PowerMockito.mockStatic(Feed.class);
363         Feed feed = mock(Feed.class);
364         PowerMockito.when(Feed.getFeedById(anyInt())).thenReturn(feed);
365         when(feed.isDeleted()).thenReturn(false);
366         when(feed.asJSONObject(true)).thenReturn(mock(JSONObject.class));
367         when(feed.getPublisher()).thenReturn("Stub_Value");
368         when(feed.getName()).thenReturn("stub_name");
369         when(feed.getVersion()).thenReturn("1.0");
370         when(feed.asLimitedJSONObject()).thenReturn(mock(JSONObject.class));
371         PowerMockito.when(feed.getFeedByNameVersion(anyString(), anyString())).thenReturn(null);
372     }
373
374     private void setAuthoriserToReturnRequestNotAuthorized() throws IllegalAccessException {
375         AuthorizationResponse authResponse = mock(AuthorizationResponse.class);
376         Authorizer authorizer = mock(Authorizer.class);
377         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authz", authorizer, true);
378         when(authorizer.decide(request)).thenReturn(authResponse);
379         when(authResponse.isAuthorized()).thenReturn(false);
380     }
381
382     private void setAuthoriserToReturnRequestIsAuthorized() throws IllegalAccessException {
383         AuthorizationResponse authResponse = mock(AuthorizationResponse.class);
384         Authorizer authorizer = mock(Authorizer.class);
385         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authz", authorizer, true);
386         when(authorizer.decide(request)).thenReturn(authResponse);
387         when(authResponse.isAuthorized()).thenReturn(true);
388     }
389
390     private void setPokerToNotCreateTimersWhenDeleteFeedIsCalled() throws Exception {
391         Poker poker = mock(Poker.class);
392         FieldUtils.writeDeclaredStaticField(Poker.class, "poker", poker, true);
393     }
394
395     private void setupValidAuthorisedRequest() throws Exception {
396         setUpValidSecurityOnHttpRequest();
397         setBehalfHeader("Stub_Value");
398         setValidPathInfoInHttpHeader();
399         setFeedToReturnValidFeedForSuppliedId();
400     }
401
402     private void setUpValidContentHeadersAndJSONOnHttpRequest() {
403         when(request.getHeader("Content-Type")).thenReturn("application/vnd.dmaap-dr.feed; version=1.0");
404         when(request.getHeader("X-DMAAP-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup");
405
406     }
407 }