preliminary AAF changes for DR
[dmaap/datarouter.git] / datarouter-prov / src / test / java / org / onap / dmaap / datarouter / provisioning / InternalServletTest.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.Matchers.anyString;
27 import static org.mockito.Matchers.argThat;
28 import static org.mockito.Matchers.eq;
29 import static org.mockito.Mockito.mock;
30 import static org.mockito.Mockito.verify;
31 import static org.mockito.Mockito.when;
32 import static org.onap.dmaap.datarouter.provisioning.BaseServlet.BEHALF_HEADER;
33
34 import java.net.InetAddress;
35 import java.util.HashMap;
36 import java.util.Map;
37 import javax.servlet.ServletInputStream;
38 import javax.servlet.ServletOutputStream;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.servlet.http.HttpServletResponse;
41 import org.apache.commons.lang3.reflect.FieldUtils;
42 import org.junit.Before;
43 import org.junit.Test;
44 import org.junit.runner.RunWith;
45 import org.mockito.Mock;
46 import org.onap.dmaap.datarouter.authz.AuthorizationResponse;
47 import org.onap.dmaap.datarouter.authz.Authorizer;
48 import org.onap.dmaap.datarouter.provisioning.beans.Deleteable;
49 import org.onap.dmaap.datarouter.provisioning.beans.Feed;
50 import org.onap.dmaap.datarouter.provisioning.beans.Insertable;
51 import org.onap.dmaap.datarouter.provisioning.beans.LogRecord;
52 import org.onap.dmaap.datarouter.provisioning.beans.NodeClass;
53 import org.onap.dmaap.datarouter.provisioning.beans.Parameters;
54 import org.onap.dmaap.datarouter.provisioning.beans.Subscription;
55 import org.onap.dmaap.datarouter.provisioning.beans.Updateable;
56 import org.onap.dmaap.datarouter.provisioning.utils.LogfileLoader;
57 import org.onap.dmaap.datarouter.provisioning.utils.RLEBitSet;
58 import org.powermock.api.mockito.PowerMockito;
59 import org.powermock.core.classloader.annotations.PrepareForTest;
60 import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
61 import org.powermock.modules.junit4.PowerMockRunner;
62
63 @RunWith(PowerMockRunner.class)
64 @PrepareForTest(LogRecord.class)
65 @SuppressStaticInitializationFor({"org.onap.dmaap.datarouter.provisioning.beans.Feed",
66     "org.onap.dmaap.datarouter.provisioning.beans.Parameters",
67     "org.onap.dmaap.datarouter.provisioning.beans.NodeClass",
68     "org.onap.dmaap.datarouter.provisioning.beans.Subscription",
69     "org.onap.dmaap.datarouter.provisioning.utils.LogfileLoader"})
70 public class InternalServletTest extends DrServletTestBase {
71
72   private InternalServlet internalServlet;
73
74   @Mock
75   private HttpServletRequest request;
76
77   @Mock
78   private HttpServletResponse response;
79
80   @Before
81   public void setUp() throws Exception {
82     super.setUp();
83     internalServlet = new InternalServlet();
84     setAuthoriserToReturnRequestIsAuthorized();
85     setUpValidAuthorisedRequest();
86   }
87
88   @Test
89   public void Given_Request_Is_HTTP_GET_And_Address_Not_Authorized_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
90       throws Exception {
91     when(request.getRemoteAddr()).thenReturn("127.100.0.3");
92     FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
93
94     internalServlet.doGet(request, response);
95     verify(response)
96         .sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
97   }
98
99   @Test
100   public void Given_Request_Is_HTTP_GET_With_Halt_In_Endpoint_But_Not_Sent_From_Localhost_Then_Forbidden_Response_Is_Generated()
101       throws Exception {
102     when(request.getPathInfo()).thenReturn("/halt");
103     when(request.isSecure()).thenReturn(false);
104     when(request.getRemoteAddr()).thenReturn("127.100.0.3");
105     internalServlet.doGet(request, response);
106     verify(response).setStatus(eq(HttpServletResponse.SC_FORBIDDEN));
107   }
108
109   @Test
110   public void Given_Request_Is_HTTP_GET_With_Halt_In_Endpoint_Request_Succeeds() throws Exception {
111     when(request.getPathInfo()).thenReturn("/halt");
112     when(request.isSecure()).thenReturn(false);
113     when(request.getRemoteAddr()).thenReturn("127.0.0.1");
114     internalServlet.doGet(request, response);
115     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
116   }
117
118   @Test
119   public void Given_Request_Is_HTTP_GET_With_FetchProv_In_Endpoint_Request_Succeeds()
120       throws Exception {
121     when(request.getPathInfo()).thenReturn("/fetchProv");
122     when(request.isSecure()).thenReturn(false);
123     internalServlet.doGet(request, response);
124     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
125   }
126
127   @Test
128   public void Given_Request_Is_HTTP_GET_With_Prov_In_Endpoint_Request_Succeeds() throws Exception {
129     when(request.getPathInfo()).thenReturn("/prov");
130     when(request.getQueryString()).thenReturn(null);
131     setPokerToNotCreateTimers();
132     ServletOutputStream outStream = mock(ServletOutputStream.class);
133     when(response.getOutputStream()).thenReturn(outStream);
134     internalServlet.doGet(request, response);
135     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
136   }
137
138   @Test
139   public void Given_Request_Is_HTTP_GET_With_Logs_In_Endpoint_Request_Succeeds() throws Exception {
140     when(request.getPathInfo()).thenReturn("/logs/");
141     ServletOutputStream outStream = mock(ServletOutputStream.class);
142     when(response.getOutputStream()).thenReturn(outStream);
143     internalServlet.doGet(request, response);
144     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
145   }
146
147   @Test
148   public void Given_Request_Is_HTTP_GET_Starts_With_Logs_In_Endpoint_Request_Succeeds()
149       throws Exception {
150     when(request.getPathInfo()).thenReturn("/logs/TestFile");
151     internalServlet.doGet(request, response);
152     verify(response)
153         .sendError(eq(HttpServletResponse.SC_NO_CONTENT), argThat(notNullValue(String.class)));
154   }
155
156   @Test
157   public void Given_Request_Is_HTTP_GET_With_Api_In_Endpoint_Request_Succeeds() throws Exception {
158     when(request.getPathInfo()).thenReturn("/api/Key");
159     setParametersToNotContactDb(false);
160     ServletOutputStream outStream = mock(ServletOutputStream.class);
161     when(response.getOutputStream()).thenReturn(outStream);
162     internalServlet.doGet(request, response);
163     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
164   }
165
166   @Test
167   public void Given_Request_Is_HTTP_GET_With_Drlogs_In_Endpoint_Request_Succeeds()
168       throws Exception {
169     when(request.getPathInfo()).thenReturn("/drlogs/");
170     PowerMockito.mockStatic(LogfileLoader.class);
171     LogfileLoader logfileLoader = mock(LogfileLoader.class);
172     when(logfileLoader.getBitSet()).thenReturn(new RLEBitSet());
173     PowerMockito.when(LogfileLoader.getLoader()).thenReturn(logfileLoader);
174     ServletOutputStream outStream = mock(ServletOutputStream.class);
175     when(response.getOutputStream()).thenReturn(outStream);
176     internalServlet.doGet(request, response);
177     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
178   }
179
180   @Test
181   public void Given_Request_Is_HTTP_GET_Incorrect_Endpoint_Then_No_Content_Response_Is_Generated()
182       throws Exception {
183     when(request.getPathInfo()).thenReturn("/incorrect/");
184     internalServlet.doGet(request, response);
185     verify(response)
186         .sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
187   }
188
189   @Test
190   public void Given_Request_Is_HTTP_PUT_And_Address_Not_Authorized_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
191       throws Exception {
192     when(request.getRemoteAddr()).thenReturn("127.100.0.3");
193     FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
194     internalServlet.doPut(request, response);
195     verify(response)
196         .sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
197   }
198
199   @Test
200   public void Given_Request_Is_HTTP_PUT_With_Api_In_Endpoint_Request_Succeeds() throws Exception {
201     when(request.getPathInfo()).thenReturn("/api/Key");
202     setParametersToNotContactDb(false);
203     String[] values = {"V", "a", "l", "u", "e", "s"};
204     when(request.getParameterValues(anyString())).thenReturn(values);
205     internalServlet = internalServerSuccess();
206     setPokerToNotCreateTimers();
207     mockProvisioningParametersChanged();
208     internalServlet.doPut(request, response);
209     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
210   }
211
212   @Test
213   public void Given_Request_Is_HTTP_PUT_With_Api_In_Endpoint_And_Update_Fails_Then_Internal_Server_Error_Is_Generated()
214       throws Exception {
215     when(request.getPathInfo()).thenReturn("/api/Key");
216     setParametersToNotContactDb(false);
217     String[] values = {"V", "a", "l", "u", "e", "s"};
218     when(request.getParameterValues(anyString())).thenReturn(values);
219     internalServlet = internalServerFailure();
220     internalServlet.doPut(request, response);
221     verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
222         argThat(notNullValue(String.class)));
223   }
224
225   @Test
226   public void Given_Request_Is_HTTP_PUT_With_Incorrect_Endpoint_Then_Not_Found_Error_Is_Generated()
227       throws Exception {
228     when(request.getPathInfo()).thenReturn("/incorrect");
229     internalServlet.doPut(request, response);
230     verify(response)
231         .sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
232   }
233
234   @Test
235   public void Given_Request_Is_HTTP_DELETE_And_Address_Not_Authorized_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
236       throws Exception {
237     when(request.getRemoteAddr()).thenReturn("127.100.0.3");
238     FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
239     internalServlet.doDelete(request, response);
240     verify(response)
241         .sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
242   }
243
244   @Test
245   public void Given_Request_Is_HTTP_DELETE_With_Api_In_Endpoint_Request_Succeeds()
246       throws Exception {
247     when(request.getPathInfo()).thenReturn("/api/Key");
248     setParametersToNotContactDb(false);
249     String[] values = {"V", "a", "l", "u", "e", "s"};
250     when(request.getParameterValues(anyString())).thenReturn(values);
251     internalServlet = internalServerSuccess();
252     setPokerToNotCreateTimers();
253     mockProvisioningParametersChanged();
254     internalServlet.doDelete(request, response);
255     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
256   }
257
258   @Test
259   public void Given_Request_Is_HTTP_DELETE_With_Api_In_Endpoint_And_Delete_Fails_Then_Internal_Server_Error_Is_Generated()
260       throws Exception {
261     when(request.getPathInfo()).thenReturn("/api/Key");
262     setParametersToNotContactDb(false);
263     String[] values = {"V", "a", "l", "u", "e", "s"};
264     when(request.getParameterValues(anyString())).thenReturn(values);
265     internalServlet = internalServerFailure();
266     internalServlet.doDelete(request, response);
267     verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
268         argThat(notNullValue(String.class)));
269   }
270
271   @Test
272   public void Given_Request_Is_HTTP_DELETE_With_Incorrect_Endpoint_Then_Not_Found_Error_Is_Generated()
273       throws Exception {
274     when(request.getPathInfo()).thenReturn("/incorrect");
275     internalServlet.doDelete(request, response);
276     verify(response)
277         .sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
278   }
279
280   @Test
281   public void Given_Request_Is_HTTP_POST_And_Address_Not_Authorized_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
282       throws Exception {
283     when(request.getRemoteAddr()).thenReturn("127.100.0.3");
284     internalServlet.doPost(request, response);
285     FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
286     verify(response)
287         .sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
288   }
289
290   @Test
291   public void Given_Request_Is_HTTP_POST_With_Api_In_Endpoint_Request_Succeeds() throws Exception {
292     when(request.getPathInfo()).thenReturn("/api/Key");
293     setParametersToNotContactDb(true);
294     String[] values = {"V", "a", "l", "u", "e", "s"};
295     when(request.getParameterValues(anyString())).thenReturn(values);
296     internalServlet = internalServerSuccess();
297     setPokerToNotCreateTimers();
298     mockProvisioningParametersChanged();
299     internalServlet.doPost(request, response);
300     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
301   }
302
303   @Test
304   public void Given_Request_Is_HTTP_POST_With_Api_In_Endpoint_And_Insert_Fails_Then_Internal_Server_Error_Is_Generated()
305       throws Exception {
306     when(request.getPathInfo()).thenReturn("/api/Key");
307     setParametersToNotContactDb(true);
308     String[] values = {"V", "a", "l", "u", "e", "s"};
309     when(request.getParameterValues(anyString())).thenReturn(values);
310     internalServlet = internalServerFailure();
311     internalServlet.doPost(request, response);
312     verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
313         argThat(notNullValue(String.class)));
314   }
315
316   @Test
317   public void Given_Request_Is_HTTP_POST_To_Logs_And_Content_Header_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated()
318       throws Exception {
319     when(request.getHeader("Content-Type")).thenReturn("stub_contentType");
320     when(request.getPathInfo()).thenReturn("/logs/");
321     internalServlet.doPost(request, response);
322     verify(response).setStatus(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE));
323   }
324
325   @Test
326   public void Given_Request_Is_HTTP_POST_To_Logs_And_Content_Encoding_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated()
327       throws Exception {
328     when(request.getHeader("Content-Encoding")).thenReturn("not-supported");
329     when(request.getPathInfo()).thenReturn("/logs/");
330     internalServlet.doPost(request, response);
331     verify(response).setStatus(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE));
332   }
333
334   @Test
335   public void Given_Request_Is_HTTP_POST_To_Drlogs_And_Then_Unsupported_Media_Type_Response_Is_Generated()
336       throws Exception {
337     when(request.getHeader("Content-Type")).thenReturn("stub_contentType");
338     when(request.getPathInfo()).thenReturn("/drlogs/");
339     internalServlet.doPost(request, response);
340     verify(response).setStatus(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE));
341   }
342
343   @Test
344   public void Given_Request_Is_HTTP_POST_To_Drlogs_And_Request_Succeeds() throws Exception {
345     when(request.getPathInfo()).thenReturn("/drlogs/");
346     ServletInputStream inStream = mock(ServletInputStream.class);
347     when(inStream.read()).thenReturn(1, -1);
348     when(request.getInputStream()).thenReturn(inStream);
349     PowerMockito.mockStatic(LogRecord.class);
350     internalServlet.doPost(request, response);
351     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
352   }
353
354   @Test
355   public void Given_Request_Is_HTTP_POST_With_Incorrect_Endpoint_Then_Not_Found_Error_Is_Generated()
356       throws Exception {
357     when(request.getPathInfo()).thenReturn("/incorrect/");
358     internalServlet.doPost(request, response);
359     verify(response)
360         .sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
361   }
362
363   private void setAuthoriserToReturnRequestIsAuthorized() throws IllegalAccessException {
364     AuthorizationResponse authResponse = mock(AuthorizationResponse.class);
365     Authorizer authorizer = mock(Authorizer.class);
366     FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authz", authorizer, true);
367     when(authorizer.decide(request)).thenReturn(authResponse);
368     when(authResponse.isAuthorized()).thenReturn(true);
369   }
370
371   private void setUpValidAuthorisedRequest() throws Exception {
372     setUpValidSecurityOnHttpRequest();
373     setBehalfHeader("Stub_Value");
374     setValidPathInfoInHttpHeader();
375     when(request.getHeader("Content-Type")).thenReturn("text/plain");
376     when(request.getHeader("Content-Encoding")).thenReturn("gzip");
377   }
378
379   private void setUpValidSecurityOnHttpRequest() throws Exception {
380     when(request.isSecure()).thenReturn(true);
381     when(request.getRemoteAddr()).thenReturn(InetAddress.getLocalHost().getHostAddress());
382     InetAddress[] nodeAddresses = new InetAddress[1];
383     nodeAddresses[0] = InetAddress.getLocalHost();
384     FieldUtils.writeDeclaredStaticField(BaseServlet.class, "nodeAddresses", nodeAddresses, true);
385     FieldUtils.writeDeclaredStaticField(BaseServlet.class, "requireCert", false, true);
386   }
387
388   private void setBehalfHeader(String headerValue) {
389     when(request.getHeader(BEHALF_HEADER)).thenReturn(headerValue);
390   }
391
392   private void setValidPathInfoInHttpHeader() {
393     when(request.getPathInfo()).thenReturn("/123");
394   }
395
396   private void setPokerToNotCreateTimers() throws Exception {
397     Poker poker = mock(Poker.class);
398     FieldUtils.writeDeclaredStaticField(Poker.class, "poker", poker, true);
399   }
400
401   private void setParametersToNotContactDb(boolean isPost) {
402     PowerMockito.mockStatic(Parameters.class);
403     Parameters parameters = mock(Parameters.class);
404     if (isPost) {
405       PowerMockito.when(Parameters.getParameter(anyString())).thenReturn(null);
406     } else {
407       PowerMockito.when(Parameters.getParameter(anyString())).thenReturn(parameters);
408     }
409   }
410
411   private InternalServlet internalServerSuccess() {
412     InternalServlet internalServlet = new InternalServlet() {
413
414       protected boolean doUpdate(Updateable bean) {
415         return true;
416       }
417
418       protected boolean doDelete(Deleteable bean) {
419         return true;
420       }
421
422       protected boolean doInsert(Insertable bean) {
423         return true;
424       }
425     };
426     return internalServlet;
427   }
428
429   private InternalServlet internalServerFailure() {
430     InternalServlet internalServlet = new InternalServlet() {
431
432       protected boolean doUpdate(Updateable bean) {
433         return false;
434       }
435
436       protected boolean doDelete(Deleteable bean) {
437         return false;
438       }
439
440       protected boolean doInsert(Insertable bean) {
441         return false;
442       }
443     };
444     return internalServlet;
445   }
446
447   private void mockProvisioningParametersChanged() throws IllegalAccessException {
448     PowerMockito.mockStatic(Feed.class);
449     PowerMockito.mockStatic(Subscription.class);
450     PowerMockito.when(Feed.countActiveFeeds()).thenReturn(0);
451     PowerMockito.when(Subscription.countActiveSubscriptions()).thenReturn(0);
452     Map<String, Integer> map = new HashMap<>();
453     FieldUtils.writeDeclaredStaticField(NodeClass.class, "map", map, true);
454   }
455 }